adds init function and getter for default cfg path
[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 #define I2C_MAX_DATA_SZ    32 /* max. number of bytes to be written to i2c */
27
28 #include <systemd/sd-event.h>
29 #include <sys/types.h>
30 #include <sys/stat.h>
31 #include <stdio.h>
32 #include <fcntl.h>
33 #include <string.h>
34 #include <unistd.h>
35 #include <time.h>
36 #include <assert.h>
37 #include <errno.h>
38 #include <dirent.h> 
39
40 #include "ucs_binding.h"
41 #include "ucs_interface.h"
42
43 #define MAX_FILENAME_LEN (100)
44 #define RX_BUFFER (64)
45 #define XML_CONFIG_FOLDER "/data/"
46 #define XML_CONFIG_FILE "config_multichannel_audio_kit.xml"
47
48 /** Internal structure, enabling multiple instances of this component.
49  * \note Do not access any of this variables.
50  *  */
51 typedef struct {
52     int fileHandle;
53     int fileFlags;
54     char fileName[MAX_FILENAME_LEN];
55     uint8_t rxBuffer[RX_BUFFER];
56     uint32_t rxLen;
57 } CdevData_t;
58
59
60 typedef struct {
61   CdevData_t rx;
62   CdevData_t tx;
63   UCSI_Data_t ucsiData;
64 } ucsContextT;
65
66 typedef struct {
67     struct afb_event node_event;
68     
69 } EventData_t;
70
71 static ucsContextT *ucsContextS;
72 static EventData_t *eventData = NULL;
73
74 PUBLIC void UcsXml_CB_OnError(const char format[], uint16_t vargsCnt, ...) {
75     /*AFB_DEBUG (afbIface, format, args); */
76     va_list args;
77     va_start (args, vargsCnt);
78     vfprintf (stderr, format, args);
79     va_end(args);
80     
81     va_list argptr;
82     char outbuf[300];
83     va_start(argptr, vargsCnt);
84     vsprintf(outbuf, format, argptr);
85     va_end(argptr);
86     AFB_WARNING (outbuf);
87 }
88
89 PUBLIC uint16_t UCSI_CB_OnGetTime(void *pTag) {
90     struct timespec currentTime;
91     uint16_t timer;
92     pTag = pTag;
93
94     if (clock_gettime(CLOCK_MONOTONIC_RAW, &currentTime))   {
95         assert(false);
96         return 0;
97     }
98
99     timer = (uint16_t) ((currentTime.tv_sec * 1000 ) + ( currentTime.tv_nsec / 1000000 ));
100     return(timer);
101 }
102
103 STATIC int onTimerCB (sd_event_source* source,uint64_t timer, void* pTag) {
104     ucsContextT *ucsContext = (ucsContextT*) pTag;
105
106     sd_event_source_unref(source);
107     UCSI_Timeout(&ucsContext->ucsiData);
108
109     return 0;
110 }
111
112 void UCSI_CB_OnNetworkState(void *pTag, bool isAvailable, uint16_t packetBandwidth, uint8_t amountOfNodes)
113 {
114 }
115
116 /* UCS2 Interface Timer Callback */
117 PUBLIC void UCSI_CB_OnSetServiceTimer(void *pTag, uint16_t timeout) {
118   uint64_t usec;
119   /* set a timer with  250ms accuracy */
120   sd_event_now(afb_daemon_get_event_loop(), CLOCK_BOOTTIME, &usec);
121   sd_event_add_time(afb_daemon_get_event_loop(), NULL, CLOCK_MONOTONIC, usec + (timeout*1000), 250, onTimerCB, pTag);
122
123 }
124
125 /**
126  * \brief Callback when ever an Unicens forms a human readable message.
127  *        This can be error events or when enabled also debug messages.
128  * \note This function must be implemented by the integrator
129  * \param pTag - Pointer given by the integrator by UCSI_Init
130  * \param format - Zero terminated format string (following printf rules)
131  * \param vargsCnt - Amount of parameters stored in "..."
132  */
133 void UCSI_CB_OnUserMessage(void *pTag, bool isError, const char format[],
134     uint16_t vargsCnt, ...) {
135     va_list argptr;
136     char outbuf[300];
137     pTag = pTag;
138     va_start(argptr, vargsCnt);
139     vsprintf(outbuf, format, argptr);
140     va_end(argptr);
141     if (isError)
142         AFB_NOTICE (outbuf);
143 }
144
145 /** UCSI_Service cannot be called directly within UNICENS context, need to service stack through mainloop */
146 STATIC int OnServiceRequiredCB (sd_event_source *source, uint64_t usec, void *pTag) {
147     ucsContextT *ucsContext = (ucsContextT*) pTag;
148
149     sd_event_source_unref(source);
150     UCSI_Service(&ucsContext->ucsiData);
151     return (0);
152 }
153
154 /* UCS Callback fire when ever UNICENS needs to be serviced */
155 PUBLIC void UCSI_CB_OnServiceRequired(void *pTag) {
156
157    /* push an asynchronous request for loopback to call UCSI_Service */
158    sd_event_add_time(afb_daemon_get_event_loop(), NULL, CLOCK_MONOTONIC, 0, 0, OnServiceRequiredCB, pTag);
159 }
160
161 /* Callback when ever this UNICENS wants to send a message to INIC. */
162 PUBLIC void UCSI_CB_OnTxRequest(void *pTag, const uint8_t *pData, uint32_t len) {
163     ucsContextT *ucsContext = (ucsContextT*) pTag;
164     CdevData_t *cdevTx = &ucsContext->tx;
165     uint32_t total = 0;
166
167     if (NULL == pData || 0 == len) return;
168
169     if (O_RDONLY == cdevTx->fileFlags) return;
170     if (-1 == cdevTx->fileHandle)
171         cdevTx->fileHandle = open(cdevTx->fileName, cdevTx->fileFlags);
172     if (-1 == cdevTx->fileHandle)
173         return;
174
175     while(total < len) {
176         ssize_t written = write(cdevTx->fileHandle, &pData[total], (len - total));
177         if (0 >= written)
178         {
179             /* Silently ignore write error (only occur in non-blocking mode) */
180             break;
181         }
182         total += (uint32_t) written;
183     }
184 }
185
186 /**
187  * \brief Callback when UNICENS instance has been stopped.
188  * \note This event can be used to free memory holding the resources
189  *       passed with UCSI_NewConfig
190  * \note This function must be implemented by the integrator
191  * \param pTag - Pointer given by the integrator by UCSI_Init
192  */
193 void UCSI_CB_OnStop(void *pTag) {
194     AFB_NOTICE ("UNICENS stopped");
195
196 }
197
198 /** This callback will be raised, when ever an applicative message on the control channel arrived */
199 void UCSI_CB_OnAmsMessageReceived(void *pTag)
200 {
201         /* If not interested, just ignore this event.
202            Otherwise UCSI_GetAmsMessage may now be called asynchronous (mainloop) to get the content. 
203            Don't forget to call UCSI_ReleaseAmsMessage after that */
204 }
205
206 void UCSI_CB_OnRouteResult(void *pTag, uint16_t routeId, bool isActive, uint16_t connectionLabel)
207 {
208 }
209
210 void UCSI_CB_OnGpioStateChange(void *pTag, uint16_t nodeAddress, uint8_t gpioPinId, bool isHighState)
211 {
212 }
213
214 PUBLIC void UCSI_CB_OnMgrReport(void *pTag, Ucs_MgrReport_t code, uint16_t nodeAddress, Ucs_Rm_Node_t *pNode){
215
216     bool available;
217     
218     if (code == UCS_MGR_REP_AVAILABLE) {
219         available = true;
220     }
221     else if (code == UCS_MGR_REP_NOT_AVAILABLE) {
222         available = false;
223     }
224     else {
225         /*untracked event - just exit*/
226         return;
227     }
228     
229     if (eventData) {
230         
231         json_object *j_event_info = json_object_new_object();
232         json_object_object_add(j_event_info, "node", json_object_new_int(nodeAddress));
233         json_object_object_add(j_event_info, "available", json_object_new_boolean(available));
234         
235         afb_event_push(eventData->node_event, j_event_info);
236     }     
237 }
238
239 bool Cdev_Init(CdevData_t *d, const char *fileName, bool read, bool write)
240 {
241     if (NULL == d || NULL == fileName)  goto OnErrorExit;
242
243     memset(d, 0, sizeof(CdevData_t));
244     strncpy(d->fileName, fileName, MAX_FILENAME_LEN);
245     d->fileHandle = -1;
246
247     if (read && write)
248         d->fileFlags = O_RDWR | O_NONBLOCK;
249     else if (read)
250         d->fileFlags = O_RDONLY | O_NONBLOCK;
251     else if (write)
252         d->fileFlags = O_WRONLY | O_NONBLOCK;
253
254     /* open file to enable event loop */
255     d->fileHandle = open(d->fileName, d->fileFlags);
256     if (d->fileHandle  <= 0) goto OnErrorExit;
257
258     return true;
259
260  OnErrorExit:
261     return false;
262 }
263
264 static bool InitializeCdevs(ucsContextT *ucsContext)
265 {
266     if(!Cdev_Init(&ucsContext->tx, CONTROL_CDEV_TX, false, true))
267         return false;
268     if(!Cdev_Init(&ucsContext->rx, CONTROL_CDEV_RX, true, false))
269         return false;
270     return true;
271 }
272
273 /* Callback fire when something is avaliable on MOST cdev */
274 int onReadCB (sd_event_source* src, int fileFd, uint32_t revents, void* pTag) {
275     ucsContextT *ucsContext =( ucsContextT*) pTag;
276     ssize_t len;
277     uint8_t pBuffer[RX_BUFFER];
278     int ok;
279
280     len = read (ucsContext->rx.fileHandle, &pBuffer, sizeof(pBuffer));
281     if (0 == len)
282         return 0;
283     ok= UCSI_ProcessRxData(&ucsContext->ucsiData, pBuffer, (uint16_t)len);
284     if (!ok) {
285         AFB_DEBUG ("Buffer overrun (not handle)");
286         /* Buffer overrun could replay pBuffer */
287     }
288     return 0;
289 }
290
291
292 STATIC char* GetDefaultConfig(void) {
293     
294     char const *data_path = getenv("AFM_APP_INSTALL_DIR");
295
296     if (!data_path) {
297         AFB_ERROR("AFM_APP_INSTALL_DIR is not defined");
298     }
299     else {
300         size_t size;
301         char * config_path;
302         
303         AFB_NOTICE("AFM_APP_INSTALL_DIR is: %s", data_path);
304         size = strlen(data_path) + strlen(XML_CONFIG_FOLDER) + strlen(XML_CONFIG_FILE) + 2;
305         config_path = malloc(size);
306         if (config_path != NULL) {
307             snprintf(config_path, size, "%s%s%s", data_path, XML_CONFIG_FOLDER, XML_CONFIG_FILE);
308             if(access(config_path, R_OK ) == 0) {
309                 AFB_NOTICE("Default configuration: %s", config_path);
310                 return config_path;
311             }
312         }
313     }
314     
315     return NULL;
316 }
317
318 STATIC UcsXmlVal_t* ParseFile(struct afb_req request) {
319     char *xmlBuffer;
320     ssize_t readSize;
321     int fdHandle ;
322     struct stat fdStat;
323     UcsXmlVal_t* ucsConfig;
324
325     const char *filename = afb_req_value(request, "filename");
326     if (!filename) {
327         afb_req_fail_f (request, "filename-missing", "No filename given");
328         goto OnErrorExit;
329     }
330
331     fdHandle = open(filename, O_RDONLY);
332     if (fdHandle <= 0) {
333         afb_req_fail_f (request, "fileread-error", "File not accessible: '%s' err=%s", filename, strerror(fdHandle));
334         goto OnErrorExit;
335     }
336
337     /* read file into buffer as a \0 terminated string */
338     fstat(fdHandle, &fdStat);
339     xmlBuffer = (char*)alloca(fdStat.st_size + 1);
340     readSize = read(fdHandle, xmlBuffer, fdStat.st_size);
341     close(fdHandle);
342     xmlBuffer[readSize] = '\0'; /* In any case, terminate it. */
343
344     if (readSize != fdStat.st_size)  {
345         afb_req_fail_f (request, "fileread-fail", "File to read fullfile '%s' size(%d!=%d)", filename, (int)readSize, (int)fdStat.st_size);
346         goto OnErrorExit;
347     }
348
349     ucsConfig = UcsXml_Parse(xmlBuffer);
350     if (!ucsConfig)  {
351         afb_req_fail_f (request, "filexml-error", "File XML invalid: '%s'", filename);
352         goto OnErrorExit;
353     }
354
355     return (ucsConfig);
356
357  OnErrorExit:
358     return NULL;
359 }
360
361 PUBLIC void ucs2_initialise (struct afb_req request) {
362     static UcsXmlVal_t *ucsConfig;
363     static ucsContextT ucsContext;
364
365     sd_event_source *evtSource;
366     int err;
367
368     /* Read and parse XML file */
369     ucsConfig = ParseFile (request);
370     if (NULL == ucsConfig) goto OnErrorExit;
371
372     /* When ucsContextS is set, do not initalize UNICENS, CDEVs or system hooks, just load new XML */
373     if (!ucsContextS)
374     {
375         if (!ucsContextS && !InitializeCdevs(&ucsContext))  {
376             afb_req_fail_f (request, "devnit-error", "Fail to initialise device [rx=%s tx=%s]", CONTROL_CDEV_RX, CONTROL_CDEV_TX);
377             goto OnErrorExit;
378         }
379
380         /* Initialise UNICENS Config Data Structure */
381         UCSI_Init(&ucsContext.ucsiData, &ucsContext);
382
383         /* register aplayHandle file fd into binder mainloop */
384         err = sd_event_add_io(afb_daemon_get_event_loop(), &evtSource, ucsContext.rx.fileHandle, EPOLLIN, onReadCB, &ucsContext);
385         if (err < 0) {
386             afb_req_fail_f (request, "register-mainloop", "Cannot hook events to mainloop");
387             goto OnErrorExit;
388         }
389
390         /* save this in a statical variable until ucs2vol move to C */
391         ucsContextS = &ucsContext;
392     }
393     /* Initialise UNICENS with parsed config */
394     if (!UCSI_NewConfig(&ucsContext.ucsiData, ucsConfig))   {
395         afb_req_fail_f (request, "UNICENS-init", "Fail to initialize UNICENS");
396         goto OnErrorExit;
397     }
398     
399     afb_req_success(request,NULL,"UNICENS-active");
400
401  OnErrorExit:
402     return;
403 }
404
405
406 // List Avaliable Configuration Files
407 PUBLIC void ucs2_listconfig (struct afb_req request) {
408     struct json_object *queryJ, *tmpJ, *responseJ;
409     DIR  *dirHandle;
410     char *dirPath, *dirList;
411     int error=0;
412
413     queryJ = afb_req_json(request);
414     if (queryJ && json_object_object_get_ex (queryJ, "cfgpath" , &tmpJ)) {
415         dirList = strdup (json_object_get_string(tmpJ));
416     } else {    
417         dirList = strdup (UCS2_CFG_PATH); 
418         AFB_NOTICE ("fgpath:missing uses UCS2_CFG_PATH=%s", UCS2_CFG_PATH);
419     }
420
421     responseJ = json_object_new_array();
422     for (dirPath= strtok(dirList, ":"); dirPath && *dirPath; dirPath=strtok(NULL,":")) {
423          struct dirent *dirEnt;
424          
425         dirHandle = opendir (dirPath);
426         if (!dirHandle) {
427             AFB_NOTICE ("ucs2_listconfig dir=%s not readable", dirPath);
428             error++;
429             continue;
430         } 
431         
432         AFB_NOTICE ("ucs2_listconfig scanning: %s", dirPath);
433         while ((dirEnt = readdir(dirHandle)) != NULL) {
434             // Unknown type is accepted to support dump filesystems
435             if (dirEnt->d_type == DT_REG || dirEnt->d_type == DT_UNKNOWN) {
436                 struct json_object *pathJ = json_object_new_object();
437                 json_object_object_add(pathJ, "dirpath", json_object_new_string(dirPath));
438                 json_object_object_add(pathJ, "basename", json_object_new_string(dirEnt->d_name));
439                 json_object_array_add(responseJ, pathJ);
440             }
441         }
442     }
443     
444     free (dirList);
445    
446     if (!error)  afb_req_success(request,responseJ,NULL);
447     else {
448         char info[40];
449         snprintf (info, sizeof(info), "[%d] where not scanned", error); 
450          afb_req_success(request,responseJ, info);
451     } 
452     
453     return;
454 }
455
456 PUBLIC void ucs2_subscribe (struct afb_req request) {
457     
458     if (!eventData) {
459         
460         eventData = malloc(sizeof(EventData_t));
461         if (eventData) {
462             eventData->node_event = afb_daemon_make_event ("node-availibility");
463         }
464         
465         if (!eventData || !afb_event_is_valid(eventData->node_event)) {
466             afb_req_fail_f (request, "create-event", "Cannot create or register event");
467             goto OnExitError;
468         }
469     }
470     
471     if (afb_req_subscribe(request, eventData->node_event) != 0) {
472         
473         afb_req_fail_f (request, "subscribe-event", "Cannot subscribe to event");
474         goto OnExitError;
475     }
476     
477     afb_req_success(request,NULL,"event subscription successful"); 
478     
479 OnExitError:
480     return;
481 }
482
483 STATIC void ucs2_writei2c_CB (void *result_ptr, void *request_ptr) {
484     
485     if (request_ptr){
486         afb_req *req = (afb_req *)request_ptr;
487         Ucs_I2c_ResultCode_t *res = (Ucs_I2c_ResultCode_t *)result_ptr;
488         
489         if (!res) {
490             afb_req_fail(*req, "processing","busy or lost initialization");
491         }
492         else if (*res != UCS_I2C_RES_SUCCESS){
493             afb_req_fail_f(*req, "error-result", "result code: %d", *res);
494         }
495         else {
496             afb_req_success(*req, NULL, "success");
497         }
498         
499         afb_req_unref(*req);
500         free(request_ptr);
501     } 
502     else {
503         AFB_NOTICE("write_i2c: ambiguous response data");
504     }
505 }
506
507 /* write a single i2c command */
508 STATIC void ucs2_writei2c_cmd(struct afb_req request, json_object *j_obj) {
509     
510     static uint8_t i2c_data[I2C_MAX_DATA_SZ];
511     uint8_t i2c_data_sz = 0;
512     uint16_t node_addr = 0;
513     struct afb_req *async_req_ptr = NULL;
514     
515     node_addr = (uint16_t)json_object_get_int(json_object_object_get(j_obj, "node"));
516     AFB_NOTICE("node_address: 0x%02X", node_addr);
517     
518     if (node_addr == 0) {
519         afb_req_fail_f(request, "query-params","params wrong or missing");
520         goto OnErrorExit;
521     }
522        
523     if (json_object_get_type(json_object_object_get(j_obj, "data"))==json_type_array) {
524         int size = json_object_array_length(json_object_object_get(j_obj, "data"));
525         if ((size > 0) && (size <= I2C_MAX_DATA_SZ)) {
526             
527             int32_t i;
528             int32_t val;
529             struct json_object *j_elem;
530             struct json_object *j_arr = json_object_object_get(j_obj, "data");
531
532             for (i = 0; i < size; i++) {
533                 
534                 
535                 j_elem = json_object_array_get_idx(j_arr, i);
536                 val = json_object_get_int(j_elem);
537                 if ((val < 0) && (val > 0xFF)){
538                     i = 0;
539                     break;
540                 }
541                 i2c_data[i] = (uint8_t)json_object_get_int(j_elem);
542             }
543             
544             i2c_data_sz = (uint8_t)i;
545         }
546     }
547     
548     if (i2c_data_sz == 0) {
549         AFB_NOTICE("data: invalid or not found");
550         afb_req_fail_f(request, "query-params","params wrong or missing");
551         goto OnErrorExit;
552     }
553    
554     async_req_ptr = malloc(sizeof(afb_req));
555     *async_req_ptr = request;
556     
557     if (UCSI_I2CWrite(  &ucsContextS->ucsiData,   /* UCSI_Data_t *pPriv*/
558                         node_addr,                /* uint16_t targetAddress*/
559                         false,                    /* bool isBurst*/
560                         0u,                       /* block count */
561                         0x2Au,                    /* i2c slave address */
562                         0x03E8u,                  /* timeout 1000 milliseconds */
563                         i2c_data_sz,              /* uint8_t dataLen */
564                         &i2c_data[0],             /* uint8_t *pData */
565                         &ucs2_writei2c_CB,        /* callback*/
566                         (void*)async_req_ptr      /* callback argument */
567                   )) {
568         /* asynchronous command is running */
569         afb_req_addref(request);
570     }
571     else {
572         AFB_NOTICE("i2c write: scheduling command failed");
573         afb_req_fail_f(request, "query-command-queue","command queue overload");
574         free(async_req_ptr);
575         async_req_ptr = NULL;
576         goto OnErrorExit;
577     }
578     
579 OnErrorExit:
580     return;
581 }
582
583 /* parse array or single command */
584 PUBLIC void ucs2_writei2c (struct afb_req request) {
585     
586     struct json_object *j_obj;
587     
588     /* check UNICENS is initialised */
589     if (!ucsContextS) {
590         afb_req_fail_f(request, "unicens-init","Should Load Config before using setvol");
591         goto OnErrorExit;
592     }
593
594     j_obj = afb_req_json(request);
595     if (!j_obj) {
596         afb_req_fail_f(request, "query-notjson","query=%s not a valid json entry", afb_req_value(request,""));
597         goto OnErrorExit;
598     };
599     
600     AFB_DEBUG("request: %s", json_object_to_json_string(j_obj));
601     
602     if (json_object_get_type(j_obj)==json_type_array) {
603         
604         int cnt;
605         int len = json_object_array_length(j_obj);
606         
607         if (len != 1) {
608             afb_req_fail_f(request, "query-array","query of multiple commands is not supported");
609             goto OnErrorExit;
610         }
611         
612         for (cnt = 0; cnt < len; cnt++) {
613             
614             json_object *j_cmd = json_object_array_get_idx(j_obj, cnt);
615             ucs2_writei2c_cmd(request, j_cmd);
616         }
617     }
618     else {
619         ucs2_writei2c_cmd(request, j_obj);
620     }
621     
622  OnErrorExit:
623     return;
624 }
625
626 PUBLIC int ucs2_initbinding(void) {
627     char *config_file = GetDefaultConfig();
628     if (config_file != NULL) {
629         
630         free(config_file);
631     }
632     
633     return 0;
634 }