bf0fd8e8957cff48d3cc2a953630c6cb107e00b1
[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 #define CTRL_MAX_DATA_SZ   45 /* max. number of bytes to be written to control
28                                * channel */
29
30 #include <systemd/sd-event.h>
31 #include <sys/types.h>
32 #include <sys/stat.h>
33 #include <stdio.h>
34 #include <fcntl.h>
35 #include <string.h>
36 #include <unistd.h>
37 #include <time.h>
38 #include <assert.h>
39 #include <errno.h>
40 #include <dirent.h>
41
42 #include "ucs_binding.h"
43 #include "ucs_interface.h"
44 #include <wrap-json.h>
45
46 #define MAX_FILENAME_LEN (100)
47 #define RX_BUFFER (64)
48 #define XML_CONFIG_FOLDER "/var/"
49 #define XML_CONFIG_FILE "config_multichannel_audio_kit.xml"
50
51 /** Internal structure, enabling multiple instances of this component.
52  * \note Do not access any of this variables.
53  *  */
54 typedef struct {
55     int fileHandle;
56     int fileFlags;
57     char fileName[MAX_FILENAME_LEN];
58     uint8_t rxBuffer[RX_BUFFER];
59     uint32_t rxLen;
60 } CdevData_t;
61
62
63 typedef struct {
64   CdevData_t rx;
65   CdevData_t tx;
66   UCSI_Data_t ucsiData;
67   UcsXmlVal_t* ucsConfig;
68 } ucsContextT;
69
70 typedef struct {
71     struct afb_event node_event;
72 } EventData_t;
73
74 typedef struct {
75     struct afb_event rx_event;
76 } EventDataRx_t;
77
78 static ucsContextT *ucsContextS = NULL;
79 static EventData_t *eventData = NULL;
80 static EventDataRx_t *eventDataRx = NULL;
81
82 PUBLIC void UcsXml_CB_OnError(const char format[], uint16_t vargsCnt, ...) {
83     /*AFB_DEBUG (afbIface, format, args); */
84     va_list args;
85     va_start (args, vargsCnt);
86     vfprintf (stderr, format, args);
87     va_end(args);
88
89     va_list argptr;
90     char outbuf[300];
91     va_start(argptr, vargsCnt);
92     vsprintf(outbuf, format, argptr);
93     va_end(argptr);
94     AFB_WARNING ("%s", outbuf);
95 }
96
97 PUBLIC uint16_t UCSI_CB_OnGetTime(void *pTag) {
98     struct timespec currentTime;
99     uint16_t timer;
100     pTag = pTag;
101
102     if (clock_gettime(CLOCK_MONOTONIC_RAW, &currentTime))   {
103         assert(false);
104         return 0;
105     }
106
107     timer = (uint16_t) ((currentTime.tv_sec * 1000 ) + ( currentTime.tv_nsec / 1000000 ));
108     return(timer);
109 }
110
111 STATIC int onTimerCB (sd_event_source* source,uint64_t timer, void* pTag) {
112     ucsContextT *ucsContext = (ucsContextT*) pTag;
113
114     sd_event_source_unref(source);
115     UCSI_Timeout(&ucsContext->ucsiData);
116
117     return 0;
118 }
119
120 void UCSI_CB_OnNetworkState(void *pTag, bool isAvailable, uint16_t packetBandwidth, uint8_t amountOfNodes)
121 {
122     AFB_NOTICE ("Network is available=%d, bw=%d, nodeCnt=%d", isAvailable, packetBandwidth, amountOfNodes);
123 }
124
125 /* UCS2 Interface Timer Callback */
126 PUBLIC void UCSI_CB_OnSetServiceTimer(void *pTag, uint16_t timeout) {
127   uint64_t usec;
128   /* set a timer with  250ms accuracy */
129   sd_event_now(afb_daemon_get_event_loop(), CLOCK_BOOTTIME, &usec);
130   sd_event_add_time(afb_daemon_get_event_loop(), NULL, CLOCK_MONOTONIC, usec + (timeout*1000), 250, onTimerCB, pTag);
131
132 }
133
134 /**
135  * \brief Callback when ever an Unicens forms a human readable message.
136  *        This can be error events or when enabled also debug messages.
137  * \note This function must be implemented by the integrator
138  * \param pTag - Pointer given by the integrator by UCSI_Init
139  * \param format - Zero terminated format string (following printf rules)
140  * \param vargsCnt - Amount of parameters stored in "..."
141  */
142 void UCSI_CB_OnUserMessage(void *pTag, bool isError, const char format[],
143     uint16_t vargsCnt, ...) {
144     va_list argptr;
145     char outbuf[300];
146     pTag = pTag;
147     va_start(argptr, vargsCnt);
148     vsprintf(outbuf, format, argptr);
149     va_end(argptr);
150     AFB_NOTICE ("%s",outbuf);
151 }
152
153 /** UCSI_Service cannot be called directly within UNICENS context, need to service stack through mainloop */
154 STATIC int OnServiceRequiredCB (sd_event_source *source, uint64_t usec, void *pTag) {
155     ucsContextT *ucsContext = (ucsContextT*) pTag;
156
157     sd_event_source_unref(source);
158     UCSI_Service(&ucsContext->ucsiData);
159     return (0);
160 }
161
162 /* UCS Callback fire when ever UNICENS needs to be serviced */
163 PUBLIC void UCSI_CB_OnServiceRequired(void *pTag) {
164
165    /* push an asynchronous request for loopback to call UCSI_Service */
166    sd_event_add_time(afb_daemon_get_event_loop(), NULL, CLOCK_MONOTONIC, 0, 0, OnServiceRequiredCB, pTag);
167 }
168
169 /* Callback when ever this UNICENS wants to send a message to INIC. */
170 PUBLIC void UCSI_CB_OnTxRequest(void *pTag, const uint8_t *pData, uint32_t len) {
171     ucsContextT *ucsContext = (ucsContextT*) pTag;
172     CdevData_t *cdevTx = &ucsContext->tx;
173     uint32_t total = 0;
174
175     if (NULL == pData || 0 == len) return;
176
177     if (O_RDONLY == cdevTx->fileFlags) return;
178     if (-1 == cdevTx->fileHandle)
179         cdevTx->fileHandle = open(cdevTx->fileName, cdevTx->fileFlags);
180     if (-1 == cdevTx->fileHandle)
181         return;
182
183     while(total < len) {
184         ssize_t written = write(cdevTx->fileHandle, &pData[total], (len - total));
185         if (0 >= written)
186         {
187             /* Silently ignore write error (only occur in non-blocking mode) */
188             break;
189         }
190         total += (uint32_t) written;
191     }
192 }
193
194 /** UcsXml_FreeVal be called directly within UNICENS context, need to service stack through mainloop */
195 STATIC int OnStopCB (sd_event_source *source, uint64_t usec, void *pTag) {
196     if (NULL != ucsContextS && NULL != ucsContextS->ucsConfig) {
197         UcsXml_FreeVal(ucsContextS->ucsConfig);
198         ucsContextS->ucsConfig = NULL;
199     }
200     return 0;
201 }
202
203 /**
204  * \brief Callback when UNICENS instance has been stopped.
205  * \note This event can be used to free memory holding the resources
206  *       passed with UCSI_NewConfig
207  * \note This function must be implemented by the integrator
208  * \param pTag - Pointer given by the integrator by UCSI_Init
209  */
210 void UCSI_CB_OnStop(void *pTag) {
211    AFB_NOTICE ("UNICENS stopped");
212    /* push an asynchronous request for loopback to call UcsXml_FreeVal */
213    sd_event_add_time(afb_daemon_get_event_loop(), NULL, CLOCK_MONOTONIC, 0, 0, OnStopCB, pTag);
214 }
215
216 /* helper function: wraps Rx message in json and triggers notification */
217 STATIC void NotifyEventRxMsg(uint16_t src_addr, uint16_t msg_id, uint8_t *data_ptr, uint32_t data_sz) {
218
219     if (!eventDataRx)
220         return;
221
222     if (data_sz > CTRL_MAX_DATA_SZ) {
223         AFB_NOTICE("RX-MSG: discarded, payload exceeds %d bytes", CTRL_MAX_DATA_SZ);
224         return;
225     }
226
227     json_object *j_query = NULL;
228     int node = (int)src_addr;
229     int msgid = (int)msg_id;
230     size_t data_size = (size_t)data_sz;
231
232     /* skip data attribute if possible, wrap_json_unpack may fail to deal with
233      * an empty Base64 string */
234     if (data_size > 0)
235         wrap_json_pack(&j_query, "{s:i, s:i, s:Y*}", "node", node, "msgid", msgid, "data", data_ptr, data_size);
236     else
237         wrap_json_pack(&j_query, "{s:i, s:i}", "node", node, "msgid", msgid);
238
239     afb_event_push(eventDataRx->rx_event, j_query);
240 }
241
242 /** Asynchronous processing of Rx messages in mainloop is recommended */
243 STATIC int OnAmsMessageReceivedCB (sd_event_source *source, void *pTag) {
244     ucsContextT *ucsContext = (ucsContextT*) pTag;
245     uint32_t data_sz = 0U;
246     uint8_t *data_ptr = NULL;
247     uint16_t msg_id = 0U;
248     uint16_t src_addr = 0U;
249
250     while (UCSI_GetAmsMessage(&ucsContext->ucsiData, &msg_id, &src_addr, &data_ptr, &data_sz)) {
251         NotifyEventRxMsg(src_addr, msg_id, data_ptr, data_sz);
252         AFB_DEBUG("RX-MSG: src=0x%04X, msg_id=0x%04X, size=%d", src_addr, msg_id, data_sz);
253         UCSI_ReleaseAmsMessage(&ucsContext->ucsiData);
254     }
255
256     return 0;
257 }
258
259 /** This callback will be raised, when ever an applicative message on the control channel arrived */
260 void UCSI_CB_OnAmsMessageReceived(void *pTag)
261 {
262     static sd_event_source *src_ptr = NULL;
263
264     if (!src_ptr)
265     {
266         /* first time usage: create and trigger event source */
267         sd_event_add_defer(afb_daemon_get_event_loop(), &src_ptr, &OnAmsMessageReceivedCB, pTag);
268     }
269     else
270     {
271         sd_event_source_set_enabled(src_ptr, SD_EVENT_ONESHOT);
272     }
273 }
274
275 void UCSI_CB_OnRouteResult(void *pTag, uint16_t routeId, bool isActive, uint16_t connectionLabel)
276 {
277     AFB_NOTICE ("Route 0x%X is active=%d, connection label=0x%X", routeId, isActive, connectionLabel);
278 }
279
280 void UCSI_CB_OnGpioStateChange(void *pTag, uint16_t nodeAddress, uint8_t gpioPinId, bool isHighState)
281 {
282     AFB_NOTICE ("GPIO state of node 0x%X changed, pin=%d isHigh=%d", nodeAddress, gpioPinId, isHighState);
283 }
284
285 PUBLIC void UCSI_CB_OnMgrReport(void *pTag, Ucs_MgrReport_t code, uint16_t nodeAddress, Ucs_Rm_Node_t *pNode){
286
287     bool available;
288
289     if (code == UCS_MGR_REP_AVAILABLE) {
290         available = true;
291     }
292     else if (code == UCS_MGR_REP_NOT_AVAILABLE) {
293         available = false;
294     }
295     else {
296         /*untracked event - just exit*/
297         return;
298     }
299
300     if (eventData) {
301
302         json_object *j_event_info = json_object_new_object();
303         json_object_object_add(j_event_info, "node", json_object_new_int(nodeAddress));
304         json_object_object_add(j_event_info, "available", json_object_new_boolean(available));
305
306         afb_event_push(eventData->node_event, j_event_info);
307     }
308 }
309
310 bool Cdev_Init(CdevData_t *d, const char *fileName, bool read, bool write)
311 {
312     if (NULL == d || NULL == fileName)  goto OnErrorExit;
313
314     memset(d, 0, sizeof(CdevData_t));
315     strncpy(d->fileName, fileName, MAX_FILENAME_LEN);
316     d->fileHandle = -1;
317
318     if (read && write)
319         d->fileFlags = O_RDWR | O_NONBLOCK;
320     else if (read)
321         d->fileFlags = O_RDONLY | O_NONBLOCK;
322     else if (write)
323         d->fileFlags = O_WRONLY | O_NONBLOCK;
324
325     /* open file to enable event loop */
326     d->fileHandle = open(d->fileName, d->fileFlags);
327     if (d->fileHandle  <= 0) goto OnErrorExit;
328
329     return true;
330
331  OnErrorExit:
332     return false;
333 }
334
335 static bool InitializeCdevs(ucsContextT *ucsContext)
336 {
337     if(!Cdev_Init(&ucsContext->tx, CONTROL_CDEV_TX, false, true))
338         return false;
339     if(!Cdev_Init(&ucsContext->rx, CONTROL_CDEV_RX, true, false))
340         return false;
341     return true;
342 }
343
344 /* Callback fire when something is avaliable on MOST cdev */
345 int onReadCB (sd_event_source* src, int fileFd, uint32_t revents, void* pTag) {
346     ucsContextT *ucsContext =( ucsContextT*) pTag;
347     ssize_t len;
348     uint8_t pBuffer[RX_BUFFER];
349     int ok;
350
351     len = read (ucsContext->rx.fileHandle, &pBuffer, sizeof(pBuffer));
352     if (0 == len)
353         return 0;
354     ok= UCSI_ProcessRxData(&ucsContext->ucsiData, pBuffer, (uint16_t)len);
355     if (!ok) {
356         AFB_DEBUG ("Buffer overrun (not handle)");
357         /* Buffer overrun could replay pBuffer */
358     }
359     return 0;
360 }
361
362
363 STATIC char* GetDefaultConfig(void) {
364
365     char const *data_path = getenv("AFM_APP_INSTALL_DIR");
366
367     if (!data_path) {
368         AFB_ERROR("AFM_APP_INSTALL_DIR is not defined");
369     }
370     else {
371         size_t size;
372         char * config_path;
373
374         AFB_NOTICE("AFM_APP_INSTALL_DIR is: %s", data_path);
375         size = strlen(data_path) + strlen(XML_CONFIG_FOLDER) + strlen(XML_CONFIG_FILE) + 2;
376         config_path = malloc(size);
377         if (config_path != NULL) {
378             snprintf(config_path, size, "%s%s%s", data_path, XML_CONFIG_FOLDER, XML_CONFIG_FILE);
379             if(access(config_path, R_OK ) == 0) {
380                 AFB_NOTICE("Default configuration: %s", config_path);
381                 return config_path;
382             }
383         }
384     }
385
386     return NULL;
387 }
388
389 STATIC UcsXmlVal_t* ParseFile(const char *filename) {
390     char *xmlBuffer;
391     ssize_t readSize;
392     int fdHandle ;
393     struct stat fdStat;
394     UcsXmlVal_t *ucsConfig = NULL;
395
396     fdHandle = open(filename, O_RDONLY);
397     if (fdHandle <= 0) {
398         AFB_ERROR("File not accessible: '%s' err=%s", filename, strerror(fdHandle));
399         goto OnErrorExit;
400     }
401
402     /* read file into buffer as a \0 terminated string */
403     fstat(fdHandle, &fdStat);
404     xmlBuffer = (char*)alloca(fdStat.st_size + 1);
405     readSize = read(fdHandle, xmlBuffer, fdStat.st_size);
406     close(fdHandle);
407     xmlBuffer[readSize] = '\0'; /* In any case, terminate it. */
408
409     if (readSize != fdStat.st_size)  {
410         AFB_ERROR("File to read fullfile '%s' size(%d!=%d)", filename, (int)readSize, (int)fdStat.st_size);
411         goto OnErrorExit;
412     }
413
414     ucsConfig = UcsXml_Parse(xmlBuffer);
415     if (!ucsConfig)  {
416         AFB_ERROR("File XML invalid: '%s'", filename);
417         goto OnErrorExit;
418     }
419     AFB_NOTICE ("Parsing result: %d Nodes, %d Scripts, Ethernet Bandwith %d bytes = %.2f MBit/s", ucsConfig->nodSize, ucsConfig->routesSize, ucsConfig->packetBw, (48 * 8 * ucsConfig->packetBw / 1000.0));
420
421     return (ucsConfig);
422
423  OnErrorExit:
424     return NULL;
425 }
426
427 PUBLIC int StartConfiguration(const char *filename) {
428     static ucsContextT ucsContext = { 0 };
429
430     sd_event_source *evtSource;
431     int err;
432
433     /* Read and parse XML file */
434     ucsContext.ucsConfig = ParseFile(filename);
435     if (NULL == ucsContext.ucsConfig) {
436         AFB_ERROR ("Cannot access or load file: '%s'", filename);
437         goto OnErrorExit;
438     }
439
440     /* When ucsContextS is set, do not initalize UNICENS, CDEVs or system hooks, just load new XML */
441     if (!ucsContextS)
442     {
443         if (!ucsContextS && !InitializeCdevs(&ucsContext))  {
444             AFB_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         /* register aplayHandle file fd into binder mainloop */
452         err = sd_event_add_io(afb_daemon_get_event_loop(), &evtSource, ucsContext.rx.fileHandle, EPOLLIN, onReadCB, &ucsContext);
453         if (err < 0) {
454             AFB_ERROR ("Cannot hook events to mainloop");
455             goto OnErrorExit;
456         }
457
458         /* save this in a statical variable until ucs2vol move to C */
459         ucsContextS = &ucsContext;
460     }
461     /* Initialise UNICENS with parsed config */
462     if (!UCSI_NewConfig(&ucsContext.ucsiData, ucsContext.ucsConfig))   {
463         AFB_ERROR ("Fail to initialize UNICENS");
464         goto OnErrorExit;
465     }
466
467     return 0;
468
469  OnErrorExit:
470     return -1;
471 }
472
473 PUBLIC void ucs2_initialise (struct afb_req request) {
474     const char *filename = afb_req_value(request, "filename");
475
476     if (!filename) {
477         afb_req_fail_f (request, "filename-missing", "No filename given");
478         goto OnErrorExit;
479     }
480
481     if (StartConfiguration(filename) != 0) {
482         afb_req_fail_f (request, "load-failed", "Cannot parse file and start UNICENS");
483         goto OnErrorExit;
484     }
485
486     afb_req_success(request,NULL,"UNICENS-active");
487
488  OnErrorExit:
489     return;
490 }
491
492
493 // List Avaliable Configuration Files
494 PUBLIC void ucs2_listconfig (struct afb_req request) {
495     struct json_object *queryJ, *tmpJ, *responseJ;
496     DIR  *dirHandle;
497     char *dirPath, *dirList;
498     int error=0;
499
500     queryJ = afb_req_json(request);
501     if (queryJ && json_object_object_get_ex (queryJ, "cfgpath" , &tmpJ)) {
502         dirList = strdup (json_object_get_string(tmpJ));
503     } else {
504         dirList = strdup (UCS2_CFG_PATH);
505         AFB_NOTICE ("fgpath:missing uses UCS2_CFG_PATH=%s", UCS2_CFG_PATH);
506     }
507
508     responseJ = json_object_new_array();
509     for (dirPath= strtok(dirList, ":"); dirPath && *dirPath; dirPath=strtok(NULL,":")) {
510          struct dirent *dirEnt;
511
512         dirHandle = opendir (dirPath);
513         if (!dirHandle) {
514             AFB_NOTICE ("ucs2_listconfig dir=%s not readable", dirPath);
515             error++;
516             continue;
517         }
518
519         AFB_NOTICE ("ucs2_listconfig scanning: %s", dirPath);
520         while ((dirEnt = readdir(dirHandle)) != NULL) {
521             // Unknown type is accepted to support dump filesystems
522             if (dirEnt->d_type == DT_REG || dirEnt->d_type == DT_UNKNOWN) {
523                 struct json_object *pathJ = json_object_new_object();
524                 json_object_object_add(pathJ, "dirpath", json_object_new_string(dirPath));
525                 json_object_object_add(pathJ, "basename", json_object_new_string(dirEnt->d_name));
526                 json_object_array_add(responseJ, pathJ);
527             }
528         }
529     }
530
531     free (dirList);
532
533     if (!error)  afb_req_success(request,responseJ,NULL);
534     else {
535         char info[40];
536         snprintf (info, sizeof(info), "[%d] where not scanned", error);
537          afb_req_success(request,responseJ, info);
538     }
539
540     return;
541 }
542
543 PUBLIC void ucs2_subscribe (struct afb_req request) {
544
545     if (!eventData) {
546
547         eventData = malloc(sizeof(EventData_t));
548         if (eventData) {
549             eventData->node_event = afb_daemon_make_event ("node-availibility");
550         }
551
552         if (!eventData || !afb_event_is_valid(eventData->node_event)) {
553             afb_req_fail_f (request, "create-event", "Cannot create or register event");
554             goto OnExitError;
555         }
556     }
557
558     if (afb_req_subscribe(request, eventData->node_event) != 0) {
559
560         afb_req_fail_f (request, "subscribe-event", "Cannot subscribe to event");
561         goto OnExitError;
562     }
563
564     afb_req_success(request,NULL,"event subscription successful");
565
566 OnExitError:
567     return;
568 }
569
570 PUBLIC void ucs2_subscriberx (struct afb_req request) {
571
572     if (!eventDataRx) {
573
574         eventDataRx = malloc(sizeof(EventDataRx_t));
575         if (eventDataRx) {
576             eventDataRx->rx_event = afb_daemon_make_event("rx-message");
577         }
578
579         if (!eventDataRx || !afb_event_is_valid(eventDataRx->rx_event)) {
580             afb_req_fail_f(request, "create-event", "Cannot create or register event");
581             goto OnExitError;
582         }
583     }
584
585     if (afb_req_subscribe(request, eventDataRx->rx_event) != 0) {
586
587         afb_req_fail_f (request, "subscribe-event", "Cannot subscribe to event");
588         goto OnExitError;
589     }
590
591     afb_req_success(request,NULL,"event subscription successful");
592
593 OnExitError:
594     return;
595 }
596
597 static json_object * ucs2_validate_command (struct afb_req request,
598         const char* func_name) {
599
600     struct json_object *j_obj = NULL;
601
602     if (!ucsContextS) {                     /* check UNICENS is initialized */
603         afb_req_fail_f(request, "unicens-init",
604                 "Load a configuration before calling %s.",
605                 func_name);
606         goto OnErrorExit;
607     }
608
609     j_obj = afb_req_json(request);
610     if (!j_obj) {
611         afb_req_fail_f(request,
612                 "query-notjson","query=%s not a valid json entry",
613                 afb_req_value(request,""));
614         goto OnErrorExit;
615     }
616
617     AFB_DEBUG("request: %s", json_object_to_json_string(j_obj));
618
619     if (json_object_get_type(j_obj)==json_type_array) {
620         int len = json_object_array_length(j_obj);
621
622         if (len == 1) {             /* only support 1 command in array */
623             j_obj = json_object_array_get_idx(j_obj, 0);
624         }
625         else {
626             afb_req_fail_f(request,
627                     "query-array",
628                     "query of multiple %s commands is not supported",
629                     func_name);
630             j_obj = NULL;
631             goto OnErrorExit;
632         }
633     }
634
635  OnErrorExit:
636     return j_obj;
637 }
638
639 STATIC void ucs2_writei2c_CB (void *result_ptr, void *request_ptr) {
640
641     if (request_ptr){
642         afb_req *req = (afb_req *)request_ptr;
643         Ucs_I2c_ResultCode_t *res = (Ucs_I2c_ResultCode_t *)result_ptr;
644
645         if (!res) {
646             afb_req_fail(*req, "processing","busy or lost initialization");
647         }
648         else if (*res != UCS_I2C_RES_SUCCESS){
649             afb_req_fail_f(*req, "error-result", "result code: %d", *res);
650         }
651         else {
652             afb_req_success(*req, NULL, "success");
653         }
654
655         afb_req_unref(*req);
656         free(request_ptr);
657     }
658     else {
659         AFB_NOTICE("write_i2c: ambiguous response data");
660     }
661 }
662
663 /* write a single i2c command */
664 STATIC void ucs2_writei2c_cmd(struct afb_req request, json_object *j_obj) {
665
666     static uint8_t i2c_data[I2C_MAX_DATA_SZ];
667     uint8_t i2c_data_sz = 0;
668     uint16_t node_addr = 0;
669     struct afb_req *async_req_ptr = NULL;
670     json_object *j_tmp;
671     json_bool key_found;
672
673     if (json_object_object_get_ex(j_obj, "node", &j_tmp)) {
674         node_addr = (uint16_t)json_object_get_int(j_tmp);
675         AFB_NOTICE("node_address: 0x%02X", node_addr);
676         if (node_addr == 0) {
677             afb_req_fail_f(request, "query-params","param node invalid type");
678             goto OnErrorExit;
679         }
680     }
681     else {
682         afb_req_fail_f(request, "query-params","param node missing");
683         goto OnErrorExit;
684     }
685
686     key_found = json_object_object_get_ex(j_obj, "data", &j_tmp);
687     if (key_found && (json_object_get_type(j_tmp)==json_type_array)) {
688         int size = json_object_array_length(j_tmp);
689         if ((size > 0) && (size <= I2C_MAX_DATA_SZ)) {
690
691             int32_t i;
692             int32_t val;
693             struct json_object *j_elem;
694
695             for (i = 0; i < size; i++) {
696
697                 j_elem = json_object_array_get_idx(j_tmp, i);
698                 val = json_object_get_int(j_elem);
699                 if ((val < 0) && (val > 0xFF)){
700                     i = 0;
701                     break;
702                 }
703                 i2c_data[i] = (uint8_t)json_object_get_int(j_elem);
704             }
705
706             i2c_data_sz = (uint8_t)i;
707         }
708     }
709
710     if (i2c_data_sz == 0) {
711         AFB_NOTICE("data: invalid or not found");
712         afb_req_fail_f(request, "query-params","params wrong or missing");
713         goto OnErrorExit;
714     }
715
716     async_req_ptr = malloc(sizeof(afb_req));
717     *async_req_ptr = request;
718
719     if (UCSI_I2CWrite(  &ucsContextS->ucsiData,   /* UCSI_Data_t *pPriv*/
720                         node_addr,                /* uint16_t targetAddress*/
721                         false,                    /* bool isBurst*/
722                         0u,                       /* block count */
723                         0x2Au,                    /* i2c slave address */
724                         0x03E8u,                  /* timeout 1000 milliseconds */
725                         i2c_data_sz,              /* uint8_t dataLen */
726                         &i2c_data[0],             /* uint8_t *pData */
727                         &ucs2_writei2c_CB,        /* callback*/
728                         (void*)async_req_ptr      /* callback argument */
729                   )) {
730         /* asynchronous command is running */
731         afb_req_addref(request);
732     }
733     else {
734         AFB_NOTICE("i2c write: scheduling command failed");
735         afb_req_fail_f(request, "query-command-queue","command queue overload");
736         free(async_req_ptr);
737         async_req_ptr = NULL;
738         goto OnErrorExit;
739     }
740
741 OnErrorExit:
742     return;
743 }
744
745 /* parse array or single command */
746 PUBLIC void ucs2_writei2c (struct afb_req request) {
747
748     struct json_object *j_obj;
749
750     j_obj = ucs2_validate_command(request, "writei2c");
751
752     if (j_obj) {
753         ucs2_writei2c_cmd(request, j_obj);
754     }
755 }
756
757 PUBLIC void ucs2_sendmessage(struct afb_req req) {
758     uint8_t *data_ptr = NULL;
759     size_t data_sz = 0;
760     int ret, node_addr, msg_id  = 0;
761     struct json_object *j_obj;
762
763     j_obj = ucs2_validate_command(req, "sendmessageb64");
764
765     if (!j_obj) {
766         AFB_NOTICE("validation of command failed");
767         goto OnErrorExit;
768     }
769
770     ret = wrap_json_unpack(j_obj, "{s:i, s:i, s?Y}", "node", &node_addr, "msgid", &msg_id, "data", &data_ptr, &data_sz);
771
772     if ((ret==0) &&
773         UCSI_SendAmsMessage(&ucsContextS->ucsiData, msg_id, node_addr, &data_ptr[0], data_sz)
774             ) {
775         afb_req_success(req, NULL, "sendmessageb64 started successful");
776     }
777     else {
778         AFB_ERROR("sendmessageb64: scheduling command failed. ret: %d", ret);
779         afb_req_fail_f(req, "query-command-queue","ambiguous command or queue overload");
780         goto OnErrorExit;
781     }
782
783 OnErrorExit:
784     if (data_ptr) {
785         free(data_ptr);
786     }
787     return;
788 }
789
790 PUBLIC int ucs2_initbinding(void) {
791 #ifndef DISABLE_AUTOSTART
792     char *filename = GetDefaultConfig();
793     if (filename != NULL) {
794
795         AFB_NOTICE("AUTO-LOAD configuration: %s", filename);
796         if (StartConfiguration(filename) == 0) {
797             AFB_NOTICE("AUTO-LOAD successful");
798         } else {
799             AFB_NOTICE("AUTO-LOAD failed");
800         }
801         free(filename);
802     }
803 #endif
804     return 0;
805 }