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