Change all UNICENS words to upper case
[apps/agl-service-unicens.git] / ucs2-afb / ucs_binding.c
index 133a946..ee1bce6 100644 (file)
@@ -23,6 +23,7 @@
 
 #define BUFFER_FRAME_COUNT 10 /* max frames in buffer */
 #define WAIT_TIMER_US 1000000 /* default waiting timer 1s */
+#define I2C_MAX_DATA_SZ    32 /* max. number of bytes to be written to i2c */
 
 #include <systemd/sd-event.h>
 #include <sys/types.h>
@@ -39,8 +40,6 @@
 #include "ucs_binding.h"
 #include "ucs_interface.h"
 
-
-
 #define MAX_FILENAME_LEN (100)
 #define RX_BUFFER (64)
 
@@ -60,10 +59,15 @@ typedef struct {
   CdevData_t rx;
   CdevData_t tx;
   UCSI_Data_t ucsiData;
-  UCSI_channelsT *channels;
 } ucsContextT;
 
+typedef struct {
+    struct afb_event node_event;
+    
+} EventData_t;
+
 static ucsContextT *ucsContextS;
+static EventData_t *eventData = NULL;
 
 PUBLIC void UcsXml_CB_OnError(const char format[], uint16_t vargsCnt, ...) {
     /*AFB_DEBUG (afbIface, format, args); */
@@ -201,6 +205,31 @@ void UCSI_CB_OnGpioStateChange(void *pTag, uint16_t nodeAddress, uint8_t gpioPin
 {
 }
 
+PUBLIC void UCSI_CB_OnMgrReport(void *pTag, Ucs_MgrReport_t code, uint16_t nodeAddress, Ucs_Rm_Node_t *pNode){
+
+    bool available;
+    
+    if (code == UCS_MGR_REP_AVAILABLE) {
+        available = true;
+    }
+    else if (code == UCS_MGR_REP_NOT_AVAILABLE) {
+        available = false;
+    }
+    else {
+        /*untracked event - just exit*/
+        return;
+    }
+    
+    if (eventData) {
+        
+        json_object *j_event_info = json_object_new_object();
+        json_object_object_add(j_event_info, "node", json_object_new_int(nodeAddress));
+        json_object_object_add(j_event_info, "available", json_object_new_boolean(available));
+        
+        afb_event_push(eventData->node_event, j_event_info);
+    }     
+}
+
 bool Cdev_Init(CdevData_t *d, const char *fileName, bool read, bool write)
 {
     if (NULL == d || NULL == fileName)  goto OnErrorExit;
@@ -296,141 +325,6 @@ STATIC UcsXmlVal_t* ParseFile(struct afb_req request) {
     return NULL;
 }
 
-STATIC int volOnSvcCB (sd_event_source* source,uint64_t timer, void* pTag) {
-    ucsContextT *ucsContext = (ucsContextT*) pTag;
-
-    sd_event_source_unref(source);
-    UCSI_Vol_Service(&ucsContext->ucsiData);
-
-    return 0;
-}
-
-/* This callback is fire each time an volume event wait in the queue */
-void volumeCB (uint16_t timeout) {
-    uint64_t usec;
-    sd_event_now(afb_daemon_get_event_loop(), CLOCK_BOOTTIME, &usec);
-    sd_event_add_time(afb_daemon_get_event_loop(), NULL, CLOCK_MONOTONIC, usec + (timeout*1000), 250, volOnSvcCB, ucsContextS);
-}
-
-STATIC int volSndCmd (struct afb_req request, struct json_object *commandJ, ucsContextT *ucsContext) {
-    int numid, vol, err;
-    struct json_object *nameJ, *channelJ, *volJ;
-
-    enum json_type jtype= json_object_get_type(commandJ);
-    switch (jtype) {
-        case json_type_array:
-            if (!sscanf (json_object_get_string (json_object_array_get_idx(commandJ, 0)), "%d", &numid)) {
-                afb_req_fail_f (request, "channel-invalid","command=%s channel is not an integer", json_object_get_string (channelJ));
-                goto OnErrorExit;
-            }
-            if (!sscanf (json_object_get_string (json_object_array_get_idx(commandJ, 1)), "%d", &vol)) {
-                afb_req_fail_f (request, "vol-invalid","command=%s vol is not an integer", json_object_get_string (channelJ));
-                goto OnErrorExit;
-            }
-            break;
-
-        case json_type_object:
-            if (json_object_object_get_ex (commandJ, "numid", &channelJ)) {
-                if (!sscanf (json_object_get_string (channelJ), "%d", &numid)) {
-                    afb_req_fail_f (request, "channel-invalid","command=%s numid is not an integer", json_object_get_string (channelJ));
-                    goto OnErrorExit;
-                }
-            } else {
-                if (json_object_object_get_ex (commandJ, "channel", &nameJ)) {
-                    int idx;
-                    const char *name = json_object_get_string(nameJ);
-
-                    for (idx =0; ucsContext->channels[idx].name != NULL; idx++) {
-                        if (!strcasecmp(ucsContext->channels[idx].name, name)) {
-                            numid = ucsContext->channels[idx].numid;
-                            break;
-                        }
-                    }
-                    if (ucsContext->channels[idx].name == NULL) {
-                        afb_req_fail_f (request, "channel-invalid","command=%s channel name does not exist", name);
-                        goto OnErrorExit;
-                    }
-                } else {
-                    afb_req_fail_f (request, "channel-invalid","command=%s no valid channel name or channel", json_object_get_string(commandJ));
-                    goto OnErrorExit;
-                };
-            }
-
-            if (!json_object_object_get_ex (commandJ, "volume", &volJ)) {
-                afb_req_fail_f (request, "vol-missing","command=%s vol not present", json_object_get_string (commandJ));
-                goto OnErrorExit;
-            }
-
-            if (!sscanf (json_object_get_string (volJ), "%d", &vol)) {
-                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));
-                goto OnErrorExit;
-            }
-
-            break;
-
-        default:
-            afb_req_fail_f (request, "setvol-invalid","command=%s not valid JSON Volume Command", json_object_get_string(commandJ));
-            goto OnErrorExit;
-    }
-
-
-    /* Fulup what's append when channel or vol are invalid ??? */
-    err = UCSI_Vol_Set  (&ucsContext->ucsiData, numid, (uint8_t) vol);
-    if (err) {
-        /* Fulup this might only be a warning (not sure about it) */
-        afb_req_fail_f (request, "vol-refused","command=%s vol was refused by UNICENS", json_object_get_string (volJ));
-        goto OnErrorExit;
-    }
-
-    return 0;
-
-  OnErrorExit:
-    return 1;
-}
-
-PUBLIC void ucs2_volume (struct afb_req request) {
-    struct json_object *queryJ;
-    int err;
-
-    /* check UNICENS is initialised */
-    if (!ucsContextS) {
-        afb_req_fail_f (request, "UNICENS-init","Should Load Config before using setvol");
-        goto OnErrorExit;
-    }
-
-    queryJ = afb_req_json(request);
-    if (!queryJ) {
-        afb_req_fail_f (request, "query-notjson","query=%s not a valid json entry", afb_req_value(request,""));
-        goto OnErrorExit;
-    };
-
-    enum json_type jtype= json_object_get_type(queryJ);
-    switch (jtype) {
-        case json_type_array:
-            for (int idx=0; idx < json_object_array_length (queryJ); idx ++) {
-               err= volSndCmd (request, json_object_array_get_idx (queryJ, idx), ucsContextS);
-               if (err) goto OnErrorExit;
-            }
-            break;
-
-        case json_type_object:
-            err = volSndCmd (request, queryJ, ucsContextS);
-            if (err) goto OnErrorExit;
-            break;
-
-        default:
-            afb_req_fail_f (request, "query-notarray","query=%s not valid JSON Volume Command Array", afb_req_value(request,""));
-            goto OnErrorExit;
-    }
-
-
-    afb_req_success(request,NULL,NULL);
-
- OnErrorExit:
-    return;
-}
-
-
 PUBLIC void ucs2_initialise (struct afb_req request) {
     static UcsXmlVal_t *ucsConfig;
     static ucsContextT ucsContext;
@@ -460,12 +354,6 @@ PUBLIC void ucs2_initialise (struct afb_req request) {
             goto OnErrorExit;
         }
 
-        /* init UNICENS Volume Library */
-        ucsContext.channels = UCSI_Vol_Init (&ucsContext.ucsiData, volumeCB);
-        if (!ucsContext.channels) {
-            afb_req_fail_f (request, "register-volume", "Could not enqueue new Unicens config");
-            goto OnErrorExit;
-        }
         /* save this in a statical variable until ucs2vol move to C */
         ucsContextS = &ucsContext;
     }
@@ -491,7 +379,7 @@ PUBLIC void ucs2_listconfig (struct afb_req request) {
 
     queryJ = afb_req_json(request);
     if (queryJ && json_object_object_get_ex (queryJ, "cfgpath" , &tmpJ)) {
-        strdup (json_object_get_string(tmpJ));
+        dirList = strdup (json_object_get_string(tmpJ));
     } else {    
         dirList = strdup (UCS2_CFG_PATH); 
         AFB_NOTICE ("fgpath:missing uses UCS2_CFG_PATH=%s", UCS2_CFG_PATH);
@@ -532,41 +420,66 @@ PUBLIC void ucs2_listconfig (struct afb_req request) {
     return;
 }
 
-PUBLIC void ucs2_monitor (struct afb_req request) {
+PUBLIC void ucs2_subscribe (struct afb_req request) {
+    
+    if (!eventData) {
+        
+        eventData = malloc(sizeof(EventData_t));
+        if (eventData) {
+            eventData->node_event = afb_daemon_make_event ("node-availibility");
+        }
+        
+        if (!eventData || !afb_event_is_valid(eventData->node_event)) {
+            afb_req_fail_f (request, "create-event", "Cannot create or register event");
+            goto OnExitError;
+        }
+    }
     
-   afb_req_success(request,NULL,"UNICENS-to_be_done"); 
+    if (afb_req_subscribe(request, eventData->node_event) != 0) {
+        
+        afb_req_fail_f (request, "subscribe-event", "Cannot subscribe to event");
+        goto OnExitError;
+    }
+    
+    afb_req_success(request,NULL,"event subscription successful"); 
+    
+OnExitError:
+    return;
 }
 
-#define MUTE_VALUE      0x03FFU
-#define MUTE_VALUE_HB   0x03U
-#define MUTE_VALUE_LB   0xFFU
-
-#define CONTROL_MASTER  0x07U
-#define CONTROL_CH_1    0x08U
-#define CONTROL_CH_2    0x09U
-
-#define UCSB_I2C_MAX_PAYLOAD     32
-
-PUBLIC void ucs2_write_i2c (struct afb_req request) {
-    
-    struct json_object *j_obj;
-    static uint8_t tx_payload[UCSB_I2C_MAX_PAYLOAD];
-    uint8_t tx_payload_sz = 0;
-    uint16_t node_addr = 0;
+STATIC void ucs2_writei2c_CB (void *result_ptr, void *request_ptr) {
     
-    /* check UNICENS is initialised */
-    if (!ucsContextS) {
-        afb_req_fail_f(request, "unicens-init","Should Load Config before using setvol");
-        goto OnErrorExit;
+    if (request_ptr){
+        afb_req *req = (afb_req *)request_ptr;
+        Ucs_I2c_ResultCode_t *res = (Ucs_I2c_ResultCode_t *)result_ptr;
+        
+        if (!res) {
+            afb_req_fail(*req, "processing","busy or lost initialization");
+        }
+        else if (*res != UCS_I2C_RES_SUCCESS){
+            afb_req_fail_f(*req, "error-result", "result code: %d", *res);
+        }
+        else {
+            afb_req_success(*req, NULL, "success");
+        }
+        
+        afb_req_unref(*req);
+        free(request_ptr);
+    } 
+    else {
+        AFB_NOTICE("write_i2c: ambiguous response data");
     }
+}
 
-    j_obj = afb_req_json(request);
-    if (!j_obj) {
-        afb_req_fail_f(request, "query-notjson","query=%s not a valid json entry", afb_req_value(request,""));
-        goto OnErrorExit;
-    };
+/* write a single i2c command */
+STATIC void ucs2_writei2c_cmd(struct afb_req request, json_object *j_obj) {
     
-    node_addr = (uint16_t)json_object_get_int(json_object_object_get(j_obj, "node_address"));
+    static uint8_t i2c_data[I2C_MAX_DATA_SZ];
+    uint8_t i2c_data_sz = 0;
+    uint16_t node_addr = 0;
+    struct afb_req *async_req_ptr = NULL;
+    
+    node_addr = (uint16_t)json_object_get_int(json_object_object_get(j_obj, "node"));
     AFB_NOTICE("node_address: 0x%02X", node_addr);
     
     if (node_addr == 0) {
@@ -574,14 +487,14 @@ PUBLIC void ucs2_write_i2c (struct afb_req request) {
         goto OnErrorExit;
     }
        
-    if (json_object_get_type(json_object_object_get(j_obj, "i2c_data"))==json_type_array) {
-        int size = json_object_array_length(json_object_object_get(j_obj, "i2c_data"));
-        if ((size > 0) && (size <= UCSB_I2C_MAX_PAYLOAD)) {
+    if (json_object_get_type(json_object_object_get(j_obj, "data"))==json_type_array) {
+        int size = json_object_array_length(json_object_object_get(j_obj, "data"));
+        if ((size > 0) && (size <= I2C_MAX_DATA_SZ)) {
             
             int32_t i;
             int32_t val;
             struct json_object *j_elem;
-            struct json_object *j_arr = json_object_object_get(j_obj, "i2c_data");
+            struct json_object *j_arr = json_object_object_get(j_obj, "data");
 
             for (i = 0; i < size; i++) {
                 
@@ -592,30 +505,86 @@ PUBLIC void ucs2_write_i2c (struct afb_req request) {
                     i = 0;
                     break;
                 }
-                tx_payload[i] = (uint8_t)json_object_get_int(j_elem);
+                i2c_data[i] = (uint8_t)json_object_get_int(j_elem);
             }
             
-            tx_payload_sz = (uint8_t)i;
+            i2c_data_sz = (uint8_t)i;
         }
     }
     
-    if (tx_payload_sz == 0) {
-        AFB_NOTICE("i2c_data: invalid or not found");
+    if (i2c_data_sz == 0) {
+        AFB_NOTICE("data: invalid or not found");
         afb_req_fail_f(request, "query-params","params wrong or missing");
         goto OnErrorExit;
     }
-        
-    UCSI_I2CWrite(&ucsContextS->ucsiData,/*UCSI_Data_t *pPriv*/
-                  node_addr,            /*uint16_t targetAddress*/
-                  false,                /*bool isBurst*/
-                  0u,                   /* block count */
-                  0x2Au,                /* i2c slave address */
-                  0x03E8u,              /* timeout 1000 milliseconds */
-                  tx_payload_sz,        /* uint8_t dataLen */
-                  &tx_payload[0]        /* uint8_t *pData */
-                );  
+   
+    async_req_ptr = malloc(sizeof(afb_req));
+    *async_req_ptr = request;
+    
+    if (UCSI_I2CWrite(  &ucsContextS->ucsiData,   /* UCSI_Data_t *pPriv*/
+                        node_addr,                /* uint16_t targetAddress*/
+                        false,                    /* bool isBurst*/
+                        0u,                       /* block count */
+                        0x2Au,                    /* i2c slave address */
+                        0x03E8u,                  /* timeout 1000 milliseconds */
+                        i2c_data_sz,              /* uint8_t dataLen */
+                        &i2c_data[0],             /* uint8_t *pData */
+                        &ucs2_writei2c_CB,        /* callback*/
+                        (void*)async_req_ptr      /* callback argument */
+                  )) {
+        /* asynchronous command is running */
+        afb_req_addref(request);
+    }
+    else {
+        AFB_NOTICE("i2c write: scheduling command failed");
+        afb_req_fail_f(request, "query-command-queue","command queue overload");
+        free(async_req_ptr);
+        async_req_ptr = NULL;
+        goto OnErrorExit;
+    }
     
-    afb_req_success(request,NULL,"done!!!");
+OnErrorExit:
+    return;
+}
+
+/* parse array or single command */
+PUBLIC void ucs2_writei2c (struct afb_req request) {
+    
+    struct json_object *j_obj;
+    
+    /* check UNICENS is initialised */
+    if (!ucsContextS) {
+        afb_req_fail_f(request, "unicens-init","Should Load Config before using setvol");
+        goto OnErrorExit;
+    }
+
+    j_obj = afb_req_json(request);
+    if (!j_obj) {
+        afb_req_fail_f(request, "query-notjson","query=%s not a valid json entry", afb_req_value(request,""));
+        goto OnErrorExit;
+    };
+    
+    AFB_DEBUG("request: %s", json_object_to_json_string(j_obj));
+    
+    if (json_object_get_type(j_obj)==json_type_array) {
+        
+        int cnt;
+        int len = json_object_array_length(j_obj);
+        
+        if (len != 1) {
+            afb_req_fail_f(request, "query-array","query of multiple commands is not supported");
+            goto OnErrorExit;
+        }
+        
+        for (cnt = 0; cnt < len; cnt++) {
+            
+            json_object *j_cmd = json_object_array_get_idx(j_obj, cnt);
+            ucs2_writei2c_cmd(request, j_cmd);
+        }
+    }
+    else {
+        ucs2_writei2c_cmd(request, j_obj);
+    }
     
  OnErrorExit:
     return;