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