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