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