Merge pull request #3 from tkummermehr/Fix_CDEV_Write
[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 /** Callback when ever UNICENS forms a human readable message. */
108 void UCSI_CB_OnUserMessage(void *pTag, const char format[],
109     uint16_t vargsCnt, ...) {
110     //DEBUG (afbIface, format, args);
111     va_list args;
112     va_start (args, format);
113     vfprintf (stderr, format, args);
114     va_end(args);
115 }
116
117 /** UCSI_Service cannot be called directly within UNICENS context, need to service stack through mainloop */
118 STATIC int OnServiceRequiredCB (sd_event_source *source, uint64_t usec, void *pTag) {
119     ucsContextT *ucsContext = (ucsContextT*) pTag;
120
121     sd_event_source_unref(source);
122     UCSI_Service(&ucsContext->ucsiData);
123     return (0);
124 }
125
126 /* UCS Callback fire when ever UNICENS needs to be serviced */
127 PUBLIC void UCSI_CB_OnServiceRequired(void *pTag) {
128
129    /* push an asynchronous request for loopback to call UCSI_Service */
130    sd_event_add_time(afb_daemon_get_event_loop(afbIface->daemon), NULL, CLOCK_MONOTONIC, 0, 0, OnServiceRequiredCB, pTag);
131 }
132
133
134 /**
135  * \brief Callback when ever a MOST error message was received.
136  * \note This function must be implemented by the integrator
137  * \param pTag - Pointer given by the integrator by UCSI_Init
138  * \note All following parameters belong to the usual MOST message
139  */
140 PUBLIC void UCSI_CB_OnMostError(void *pTag, uint16_t sourceAddr,
141     uint8_t fblock, uint8_t inst, uint16_t function, uint8_t op,
142     const uint8_t *pPayload, uint32_t payloadLen) {
143
144     // Error to send to syslog
145     DEBUG (afbIface, "OnMostError source=0x%x", sourceAddr);
146 }
147
148
149
150 /* Callback when ever this UNICENS wants to send a message to INIC. */
151 PUBLIC void UCSI_CB_SendMostMessage(void *pTag, const uint8_t *pData, uint32_t len) {
152
153     ucsContextT *ucsContext = (ucsContextT*) pTag;
154     CdevData_t *cdevTx = &ucsContext->tx;
155     uint32_t total = 0;
156
157     if (NULL == pData || 0 == len) return;
158
159     if (O_RDONLY == cdevTx->fileFlags) return;
160     if (-1 == cdevTx->fileHandle)
161         cdevTx->fileHandle = open(cdevTx->fileName, cdevTx->fileFlags);
162     if (-1 == cdevTx->fileHandle)
163         return;
164
165     while(total < len) {
166         ssize_t written = write(cdevTx->fileHandle, &pData[total], (len - total));
167         if (0 >= written)
168         {
169             /* Silently ignore write error (only occur in non-blocking mode) */
170             break;
171         }
172         total += (uint32_t) written;
173     }
174 }
175
176 /**
177  * \brief Callback when UNICENS instance has been stopped.
178  * \note This event can be used to free memory holding the resources
179  *       passed with UCSI_NewConfig
180  * \note This function must be implemented by the integrator
181  * \param pTag - Pointer given by the integrator by UCSI_Init
182  */
183 void UCSI_CB_OnStop(void *pTag) {
184     NOTICE (afbIface, "UNICENS stopped");
185
186 }
187
188 /**
189  * \brief Callback on Unicens management results.
190  * \note This function must be implemented by the integrator
191  * \param pTag - Pointer given by the integrator by UCSI_Init
192  * \param code - Result code
193  * \param nodeAddress - Node address of the device causing this event
194  * \param pNode - Pointer to node structure holding details of changed node
195  */
196 extern void UCSI_CB_OnMgrReport(void *pTag, Ucs_MgrReport_t code, uint16_t nodeAddress, Ucs_Rm_Node_t *pNode) {
197
198     DEBUG (afbIface, "OnMgrReport: Ucs_MgrReport_t=%d nodeAdresse=0x%x", code, nodeAddress);
199 }
200
201 bool Cdev_Init(CdevData_t *d, const char *fileName, bool read, bool write)
202 {
203     if (NULL == d || NULL == fileName)  goto OnErrorExit;
204
205     memset(d, 0, sizeof(CdevData_t));
206     strncpy(d->fileName, fileName, MAX_FILENAME_LEN);
207     d->fileHandle = -1;
208
209     if (read && write)
210         d->fileFlags = O_RDWR | O_NONBLOCK;
211     else if (read)
212         d->fileFlags = O_RDONLY | O_NONBLOCK;
213     else if (write)
214         d->fileFlags = O_WRONLY | O_NONBLOCK;
215
216     /* open file to enable event loop */
217     d->fileHandle = open(d->fileName, d->fileFlags);
218     if (d->fileHandle  <= 0) goto OnErrorExit;
219
220     return true;
221
222  OnErrorExit:
223     return false;
224 }
225
226 static bool InitializeCdevs(ucsContextT *ucsContext)
227 {
228     if(!Cdev_Init(&ucsContext->tx, CONTROL_CDEV_TX, false, true))
229         return false;
230     if(!Cdev_Init(&ucsContext->rx, CONTROL_CDEV_RX, true, false))
231         return false;
232     return true;
233 }
234
235 /* Callback fire when something is avaliable on MOST cdev */
236 int onReadCB (sd_event_source* src, int fileFd, uint32_t revents, void* pTag) {
237     ucsContextT *ucsContext =( ucsContextT*) pTag;
238     ssize_t len;
239     uint8_t pBuffer[RX_BUFFER];
240     int ok;
241
242     len = read (ucsContext->rx.fileHandle, &pBuffer, sizeof(pBuffer));
243
244     ok= UCSI_ProcessRxData(&ucsContext->ucsiData, pBuffer, (uint16_t)len);
245     if (!ok) {
246         DEBUG (afbIface, "Buffer overrun (not handle)");
247         /* Buffer overrun could replay pBuffer */
248     }
249     return 0;
250 }
251
252 STATIC UcsXmlVal_t* ParseFile(struct afb_req request) {
253     char *xmlBuffer;
254     ssize_t readSize;
255     int fdHandle ;
256     struct stat fdStat;
257     UcsXmlVal_t* ucsConfig;
258
259     const char *filename = afb_req_value(request, "filename");
260     if (!filename) {
261         afb_req_fail_f (request, "filename-missing", "No filename given");
262         goto OnErrorExit;
263     }
264
265     fdHandle = open(filename, O_RDONLY);
266     if (fdHandle <= 0) {
267         afb_req_fail_f (request, "fileread-error", "File not accessible: '%s' err=%s", filename, strerror(fdHandle));
268         goto OnErrorExit;
269     }
270
271     /* read file into buffer as a \0 terminated string */
272     fstat(fdHandle, &fdStat);
273     xmlBuffer = (char*)alloca(fdStat.st_size + 1);
274     readSize = read(fdHandle, xmlBuffer, fdStat.st_size);
275     close(fdHandle);
276     xmlBuffer[readSize] = '\0'; /* In any case, terminate it. */
277
278     if (readSize != fdStat.st_size)  {
279         afb_req_fail_f (request, "fileread-fail", "File to read fullfile '%s' size(%d!=%d)", filename, readSize, fdStat.st_size);
280         goto OnErrorExit;
281     }
282
283     ucsConfig = UcsXml_Parse(xmlBuffer);
284     if (!ucsConfig)  {
285         afb_req_fail_f (request, "filexml-error", "File XML invalid: '%s'", filename);
286         goto OnErrorExit;
287     }
288
289     return (ucsConfig);
290
291  OnErrorExit:
292     return NULL;
293 }
294
295 STATIC int volOnSvcCB (sd_event_source* source,uint64_t timer, void* pTag) {
296     ucsContextT *ucsContext = (ucsContextT*) pTag;
297
298     sd_event_source_unref(source);
299     UCSI_Vol_Service(&ucsContext->ucsiData);
300
301     return 0;
302 }
303
304 /* This callback is fire each time an volume event wait in the queue */
305 void volumeCB (uint16_t timeout) {
306     uint64_t usec;
307     sd_event_now(afb_daemon_get_event_loop(afbIface->daemon), CLOCK_BOOTTIME, &usec);
308     sd_event_add_time(afb_daemon_get_event_loop(afbIface->daemon), NULL, CLOCK_MONOTONIC, usec + (timeout*1000), 250, volOnSvcCB, ucsContextS);
309 }
310
311 STATIC int volSndCmd (struct afb_req request, struct json_object *commandJ, ucsContextT *ucsContext) {
312     int numid, vol, err;
313     struct json_object *nameJ, *channelJ, *volJ;
314
315     enum json_type jtype= json_object_get_type(commandJ);
316     switch (jtype) {
317         case json_type_array:
318             if (!sscanf (json_object_get_string (json_object_array_get_idx(commandJ, 0)), "%d", &numid)) {
319                 afb_req_fail_f (request, "channel-invalid","command=%s channel is not an integer", json_object_get_string (channelJ));
320                 goto OnErrorExit;
321             }
322             if (!sscanf (json_object_get_string (json_object_array_get_idx(commandJ, 1)), "%d", &vol)) {
323                 afb_req_fail_f (request, "vol-invalid","command=%s vol is not an integer", json_object_get_string (channelJ));
324                 goto OnErrorExit;
325             }
326             break;
327
328         case json_type_object:
329             if (json_object_object_get_ex (commandJ, "numid", &channelJ)) {
330                 if (!sscanf (json_object_get_string (channelJ), "%d", &numid)) {
331                     afb_req_fail_f (request, "channel-invalid","command=%s numid is not an integer", json_object_get_string (channelJ));
332                     goto OnErrorExit;
333                 }
334             } else {
335                 if (json_object_object_get_ex (commandJ, "channel", &nameJ)) {
336                     int idx;
337                     const char *name = json_object_get_string(nameJ);
338
339                     for (idx =0; ucsContext->channels[idx].name != NULL; idx++) {
340                         if (!strcasecmp(ucsContext->channels[idx].name, name)) {
341                             numid = ucsContext->channels[idx].numid;
342                             break;
343                         }
344                     }
345                     if (ucsContext->channels[idx].name == NULL) {
346                         afb_req_fail_f (request, "channel-invalid","command=%s channel name does not exist", name);
347                         goto OnErrorExit;
348                     }
349                 } else {
350                     afb_req_fail_f (request, "channel-invalid","command=%s no valid channel name or channel", json_object_get_string(commandJ));
351                     goto OnErrorExit;
352                 };
353             }
354
355             if (!json_object_object_get_ex (commandJ, "volume", &volJ)) {
356                 afb_req_fail_f (request, "vol-missing","command=%s vol not present", json_object_get_string (commandJ));
357                 goto OnErrorExit;
358             }
359
360             if (!sscanf (json_object_get_string (volJ), "%d", &vol)) {
361                 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));
362                 goto OnErrorExit;
363             }
364
365             break;
366
367         default:
368             afb_req_fail_f (request, "setvol-invalid","command=%s not valid JSON Volume Command", json_object_get_string(commandJ));
369             goto OnErrorExit;
370     }
371
372
373     /* Fulup what's append when channel or vol are invalid ??? */
374     err = UCSI_Vol_Set  (&ucsContext->ucsiData, numid, (uint8_t) vol);
375     if (err) {
376         /* Fulup this might only be a warning (not sure about it) */
377         afb_req_fail_f (request, "vol-refused","command=%s vol was refused by UNICENS", json_object_get_string (volJ));
378         goto OnErrorExit;
379     }
380
381     return 0;
382
383   OnErrorExit:
384     return 1;
385 }
386
387
388 PUBLIC void ucs2SetVol (struct afb_req request) {
389     struct json_object *queryJ;
390     int err;
391
392     /* check UNICENS is initialised */
393     if (!ucsContextS) {
394         afb_req_fail_f (request, "UNICENS-init","Should Load Config before using setvol");
395         goto OnErrorExit;
396     }
397
398     queryJ = afb_req_json(request);
399     if (!queryJ) {
400         afb_req_fail_f (request, "query-notjson","query=%s not a valid json entry", afb_req_value(request,""));
401         goto OnErrorExit;
402     };
403
404     enum json_type jtype= json_object_get_type(queryJ);
405     switch (jtype) {
406         case json_type_array:
407             for (int idx=0; idx < json_object_array_length (queryJ); idx ++) {
408                err= volSndCmd (request, json_object_array_get_idx (queryJ, idx), ucsContextS);
409                if (err) goto OnErrorExit;
410             }
411             break;
412
413         case json_type_object:
414             err = volSndCmd (request, queryJ, ucsContextS);
415             if (err) goto OnErrorExit;
416             break;
417
418         default:
419             afb_req_fail_f (request, "query-notarray","query=%s not valid JSON Volume Command Array", afb_req_value(request,""));
420             goto OnErrorExit;
421     }
422
423
424     afb_req_success(request,NULL,NULL);
425
426  OnErrorExit:
427     return;
428 }
429
430
431 PUBLIC void ucs2Init (struct afb_req request) {
432     static UcsXmlVal_t *ucsConfig;
433     static ucsContextT ucsContext;
434
435     sd_event_source *evtSource;
436     int err;
437
438     /* Read and parse XML file */
439     ucsConfig = ParseFile (request);
440     if (NULL == ucsConfig) goto OnErrorExit;
441
442     // Fulup->Thorsten BUG InitializeCdevs should fail when control does not exit
443     if (!InitializeCdevs(&ucsContext))  {
444         afb_req_fail_f (request, "devnit-error", "Fail to initialise device [rx=%s tx=%s]", CONTROL_CDEV_RX, CONTROL_CDEV_TX);
445         goto OnErrorExit;
446     }
447
448     // Initialise Unicens Config Data Structure
449     UCSI_Init(&ucsContext.ucsiData, &ucsContext);
450
451     // Initialise Unicens with parsed config
452     if (!UCSI_NewConfig(&ucsContext.ucsiData, ucsConfig))   {
453         afb_req_fail_f (request, "UNICENS-init", "Fail to initialize Unicens");
454         goto OnErrorExit;
455     }
456
457     // register aplayHandle file fd into binder mainloop
458     err = sd_event_add_io(afb_daemon_get_event_loop(afbIface->daemon), &evtSource, ucsContext.rx.fileHandle, EPOLLIN, onReadCB, &ucsContext);
459     if (err < 0) {
460         afb_req_fail_f (request, "register-mainloop", "Cannot hook events to mainloop");
461         goto OnErrorExit;
462     }
463
464     // init Unicens Volume Library
465     ucsContext.channels = UCSI_Vol_Init (&ucsContext.ucsiData, volumeCB);
466     if (!ucsContext.channels) {
467         afb_req_fail_f (request, "register-volume", "Could not enqueue new Unicens config");
468         goto OnErrorExit;
469     }
470     // save this in a statical variable until ucs2vol move to C
471     ucsContextS = &ucsContext;
472
473     afb_req_success(request,NULL,"UNICENS-active");
474
475  OnErrorExit:
476     return;
477 }