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