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