aboutsummaryrefslogtreecommitdiffstats
path: root/app/images/HEB_project_flow_icon_04_checkered_flag.svg
blob: 0ece29fe2def847de4180624b82ba20d7b470149 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->

<svg
   xmlns:dc="http://purl.org/dc/elements/1.1/"
   xmlns:cc="http://creativecommons.org/ns#"
   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
   xmlns:svg="http://www.w3.org/2000/svg"
   xmlns="http://www.w3.org/2000/svg"
   xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
   xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
   width="93.543304"
   height="93.543304"
   id="svg4806"
   version="1.1"
   inkscape:version="0.48.2 r9819"
   sodipodi:docname="HEB_project_flow_icon_03_wrench_and_nuts.svg">
  <defs
     id="defs3" />
  <sodipodi:namedview
     inkscape:document-units="mm"
     id="base"
     pagecolor="#ffffff"
     bordercolor="#666666"
     borderopacity="1.0"
     inkscape:pageopacity="0.0"
     inkscape:pageshadow="2"
     inkscape:zoom="1.979899"
     inkscape:cx="65.177509"
     inkscape:cy="-10.893685"
     inkscape:current-layer="layer1"
     showgrid="true"
     units="mm"
     fit-margin-top="0.5"
     fit-margin-left="0.5"
     fit-margin-right="0.5"
     fit-margin-bottom="0.5"
     inkscape:window-width="1280"
     inkscape:window-height="1002"
     inkscape:window-x="1272"
     inkscape:window-y="-8"
     inkscape:window-maximized="1">
    <inkscape:grid
       type="xygrid"
       id="grid4812"
       empspacing="5"
       visible="true"
       enabled="true"
       snapvisiblegridlinesonly="true" />
  </sodipodi:namedview>
  <metadata
     id="metadata4">
    <rdf:RDF>
      <cc:Work
         rdf:about="">
        <dc:format>image/svg+xml</dc:format>
        <dc:type
           rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
        <dc:title></dc:title>
      </cc:Work>
    </rdf:RDF>
  </metadata>
  <g
     inkscape:label="Layer 1"
     inkscape:groupmode="layer"
     id="layer1"
     transform="translate(-268.22835,-230.59053)">
    <rect
       style="fill:#55d400;fill-opacity:1;stroke:none"
       id="rect4814"
       width="90"
       height="90"
       x="270"
       y="232.36218"
       rx="14.173228"
       ry="14.173228" />
    <g
       id="g3349-1"
       transform="matrix(0.51768837,0.13871419,-0.13871419,0.51768837,257.89183,-114.17755)"
       style="fill:#ffffff">
      <path
         inkscape:connector-curvature="0"
         id="path3317-4"
         d="m 330.73493,650.19583 0,-6.77018 1.43265,-0.70264 c 0.78795,-0.38645 2.71987,-1.48363 4.29315,-2.43819 l 2.86049,-1.73555 -1.5e-4,6.74187 -1.5e-4,6.74186 -2.96717,1.80395 c -1.63194,0.99218 -3.56379,2.1021 -4.293,2.4665 l -1.32582,0.66255 0,-6.77017 z"
         style="fill:#ffffff;fill-opacity:1;stroke:none" />
      <path
         inkscape:connector-curvature="0"
         id="path3319-3"
         d="m 319.62325,669.38246 0,-6.76792 2.44177,-0.68631 c 1.34298,-0.37747 3.50114,-1.13892 4.7959,-1.6921 1.29477,-0.55319 2.41199,-1.00579 2.48272,-1.00579 0.0707,0 0.1286,3.01886 0.1286,6.70857 l 0,6.70858 -2.08344,0.96213 c -2.07778,0.95952 -6.6768,2.54077 -7.38976,2.54077 -0.32335,0 -0.37579,-0.94452 -0.37579,-6.76793 z"
         style="fill:#ffffff;fill-opacity:1;stroke:none" />
      <path
         inkscape:connector-curvature="0"
         id="path3321-9"
         d="m 330.73518,680.27824 2.5e-4,-6.7795 2.08319,-1.11977 c 1.89919,-1.02086 4.49057,-2.54515 5.93439,-3.4907 l 0.56821,-0.37211 -0.007,6.78444 -0.007,6.78444 -2.83381,1.68356 c -1.5586,0.92597 -3.48726,2.04483 -4.28591,2.48636 l -1.45209,0.80278 2.5e-4,-6.7795 z"
         style="fill:#ffffff;fill-opacity:1;stroke:none" />
      <path
         inkscape:connector-curvature="0"
         id="path3323-8"
         d="m 319.62325,699.39363 0,-6.80879 1.07329,-0.27602 c 2.16455,-0.55665 5.16031,-1.59658 6.9448,-2.41076 l 1.8309,-0.83536 0,6.80847 0,6.80848 -1.90702,0.86905 c -1.78475,0.81334 -7.11422,2.65373 -7.68476,2.65373 -0.16823,0 -0.25721,-2.35556 -0.25721,-6.8088 z"
         style="fill:#ffffff;fill-opacity:1;stroke:none" />
      <path
         inkscape:connector-curvature="0"
         id="path3325-8"
         d="m 311.16322,691.435 c -0.83337,-0.18293 -1.99821,-0.52717 -2.58851,-0.76496 l -1.07329,-0.43235 0,-6.77751 0,-6.77751 1.40653,0.48392 c 1.74719,0.60112 5.7759,1.02528 7.87425,0.82903 l 1.57836,-0.14761 0,6.81928 0,6.81928 -1.17167,0.16059 c -1.79547,0.2461 -4.34733,0.15625 -6.02567,-0.21216 z"
         style="fill:#ffffff;fill-opacity:1;stroke:none" />
      <path
         inkscape:connector-curvature="0"
         id="path3327-0"
         d="m 311.41576,661.48931 c -0.55558,-0.11608 -1.63518,-0.41615 -2.39911,-0.66681 l -1.38896,-0.45574 -0.0672,-6.86945 -0.0672,-6.86945 1.32986,0.45484 c 2.41723,0.82676 4.62928,1.11322 7.16115,0.92737 l 2.3762,-0.17442 0,6.80219 0,6.8022 -0.78918,0.15784 c -1.08298,0.2166 -4.92358,0.14886 -6.15562,-0.10857 z"
         style="fill:#ffffff;fill-opacity:1;stroke:none" />
      <path
         inkscape:connector-curvature="0"
         id="path3329-8"
         d="m 304.04556,673.1792 c -1.13679,-0.79652 -3.4919,-2.52783 -5.23358,-3.84734 l -3.16669,-2.39911 -0.007,-6.65817 -0.007,-6.65817 0.68919,0.45158 c 0.37906,0.24837 1.88932,1.38488 3.35614,2.52559 2.82782,2.19913 5.53936,4.03407 6.33392,4.28625 0.45584,0.14468 0.47989,0.49313 0.47989,6.95382 0,3.74083 -0.0852,6.79977 -0.18941,6.79765 -0.10417,-0.002 -1.1195,-0.65557 -2.2563,-1.4521 z"
         style="fill:#ffffff;fill-opacity:1;stroke:none" />
      <path
         inkscape:connector-curvature="0"
         id="path3331-7"
         d="m 304.69952,703.64277 c -0.88964,-0.57444 -2.81076,-1.97715 -4.26917,-3.11713 -1.45841,-1.13999 -3.13463,-2.38973 -3.72494,-2.7772 l -1.07328,-0.7045 0,-6.6587 c 0,-3.66229 0.0592,-6.6587 0.13156,-6.6587 0.0724,0 1.97735,1.39211 4.23332,3.09359 2.25597,1.70147 4.64007,3.3775 5.29801,3.7245 l 1.19625,0.63091 0,6.75583 c 0,3.71571 -0.0392,6.75583 -0.0871,6.75583 -0.0479,0 -0.815,-0.46999 -1.70463,-1.04443 z"
         style="fill:#ffffff;fill-opacity:1;stroke:none" />
      <path
         inkscape:connector-curvature="0"
         id="path3333-7"
         d="m 291.84405,679.6717 c -1.31951,-0.8178 -3.7344,-2.17878 -5.36643,-3.0244 l -2.96732,-1.5375 0,-6.67704 c 0,-3.67237 0.0597,-6.67704 0.13257,-6.67704 0.34313,0 4.1222,2.01985 7.25243,3.87629 l 3.47065,2.05835 0.002,6.7554 c 9.5e-4,3.71547 -0.0267,6.74582 -0.0614,6.73412 -0.0347,-0.0117 -1.14273,-0.69038 -2.46225,-1.50818 z"
         style="fill:#ffffff;fill-opacity:1;stroke:none" />
      <path
         inkscape:connector-curvature="0"
         id="path3335-8"
         d="m 292.63511,650.121 c -1.76718,-1.11753 -7.91151,-4.42921 -8.65633,-4.66561 -0.44101,-0.13997 -0.46848,-0.54758 -0.46848,-6.9502 0,-3.74083 0.0754,-6.80151 0.16758,-6.80151 0.53834,0 9.60074,5.15624 10.38017,5.90601 0.24577,0.23641 0.30433,1.84073 0.25254,6.918 l -0.0674,6.61021 -1.60806,-1.0169 z"
         style="fill:#ffffff;fill-opacity:1;stroke:none" />
      <path
         inkscape:connector-curvature="0"
         id="path3339-3"
         d="m 280.35357,658.80685 c -1.11117,-0.48335 -3.49765,-1.36849 -5.3033,-1.96697 l -3.283,-1.08815 -0.0672,-6.83458 -0.0672,-6.83458 1.32986,0.39052 c 1.81784,0.53382 5.7677,2.01299 7.83272,2.93324 l 1.70463,0.75965 0,6.78471 c 0,3.7316 -0.0284,6.77353 -0.0631,6.75985 -0.0347,-0.0137 -0.97227,-0.42034 -2.08344,-0.90369 z"
         style="fill:#ffffff;fill-opacity:1;stroke:none" />
      <path
         inkscape:connector-curvature="0"
         id="path3341-8"
         d="m 280.47984,688.84958 c -1.04172,-0.45156 -3.45662,-1.34383 -5.36644,-1.98282 l -3.4724,-1.1618 0,-6.79759 c 0,-3.73867 0.0478,-6.79759 0.10612,-6.79759 0.0584,0 1.39366,0.44024 2.96732,0.9783 4.03528,1.37974 7.55667,2.82973 7.68512,3.16446 0.0601,0.15651 0.0788,3.2396 0.0418,6.85131 l -0.0675,6.56675 -1.89403,-0.82102 z"
         style="fill:#ffffff;fill-opacity:1;stroke:none" />
      <path
         inkscape:connector-curvature="0"
         id="path3343-3"
         d="m 266.46397,669.56009 c -1.80565,-0.39391 -4.27736,-0.84857 -5.4927,-1.01033 l -2.20971,-0.29413 0,-6.89588 0,-6.89588 0.94702,0.13766 c 1.50604,0.21892 8.68097,1.60274 9.72271,1.8752 l 0.94702,0.24769 0,6.8088 c 0,5.2962 -0.0701,6.8015 -0.31567,6.77594 -0.17362,-0.0181 -1.79302,-0.35515 -3.59867,-0.74907 z"
         style="fill:#ffffff;fill-opacity:1;stroke:none" />
      <path
         inkscape:connector-curvature="0"
         id="path3345-7"
         d="m 266.84278,639.63727 c -1.45841,-0.32387 -3.8733,-0.77983 -5.36644,-1.01326 l -2.71478,-0.42441 0,-6.81826 0,-6.81827 1.45209,0.16441 c 1.62182,0.18362 5.86083,0.97653 8.46003,1.58246 l 1.70463,0.39738 0,6.79133 c 0,6.31173 -0.0312,6.78907 -0.44194,6.75939 -0.24307,-0.0176 -1.63518,-0.29691 -3.09359,-0.62077 z"
         style="fill:#ffffff;fill-opacity:1;stroke:none" />
      <rect
         y="623.36218"
         x="254"
         height="129"
         width="3"
         id="rect3347-1"
         style="fill:#ffffff;fill-opacity:1;stroke:none" />
    </g>
  </g>
</svg>
>793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
/*
 * Copyright (C) 2016 "IoT.bzh"
 * Author Fulup Ar Foll <fulup@iot.bzh>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ref: 
 *  (manual) https://www.lua.org/manual/5.3/manual.html 
 *  (lua->C) http://www.troubleshooters.com/codecorn/lua/lua_c_calls_lua.htm#_Anatomy_of_a_Lua_Call
 *  (lua/C Var) http://acamara.es/blog/2012/08/passing-variables-from-lua-5-2-to-c-and-vice-versa/
 *  (Lua/C Lib)https://john.nachtimwald.com/2014/07/12/wrapping-a-c-library-in-lua/
 *  (Lua/C Table) https://gist.github.com/SONIC3D/10388137
 *  (Lua/C Nested table) https://stackoverflow.com/questions/45699144/lua-nested-table-from-lua-to-c
 *  (Lua/C Wrapper) https://stackoverflow.com/questions/45699950/lua-passing-handle-to-function-created-with-newlib
 *  
 */

#define _GNU_SOURCE
#include <stdio.h>
#include <string.h>


#include "ctl-binding.h"
#include "wrap-json.h"

#define LUA_FIST_ARG 2  // when using luaL_newlib calllback receive libtable as 1st arg
#define LUA_MSG_MAX_LENGTH 512
#define JSON_ERROR (json_object*)-1
static afb_req NULL_AFBREQ = {};


static  lua_State* luaState;

#define CTX_MAGIC 123456789
#define CTX_TOKEN "AFB_ctx"

typedef struct {
    char *name;
    int  count;
    afb_event event;
} LuaAfbEvent;
static LuaAfbEvent *luaDefaultEvt;

typedef struct {
    int ctxMagic;
    afb_req request;
    void *handle;
    char *info;
} LuaAfbContextT;

typedef struct {
  const char *callback; 
  json_object *context;  
  void *handle;  
} LuaCallServiceT;

typedef enum {
    AFB_MSG_INFO,
    AFB_MSG_WARNING,
    AFB_MSG_NOTICE,      
    AFB_MSG_DEBUG,      
    AFB_MSG_ERROR,      
} LuaAfbMessageT;

/*
 * Note(Fulup): I fail to use luaL_setmetatable and replaced it with a simple opaque
 * handle while waiting for someone smarter than me to find a better solution
 *  https://stackoverflow.com/questions/45596493/lua-using-lua-newuserdata-from-lua-pcall
 */

STATIC LuaAfbContextT *LuaCtxCheck (lua_State *luaState, int index) {
  LuaAfbContextT *afbContext;
  //luaL_checktype(luaState, index, LUA_TUSERDATA);
  //afbContext = (LuaAfbContextT *)luaL_checkudata(luaState, index, CTX_TOKEN);
  luaL_checktype(luaState, index, LUA_TLIGHTUSERDATA);
  afbContext = (LuaAfbContextT *) lua_touserdata(luaState, index);
  if (afbContext == NULL && afbContext->ctxMagic != CTX_MAGIC) {
      luaL_error(luaState, "Fail to retrieve user data context=%s", CTX_TOKEN);
      AFB_ERROR ("afbContextCheck error retrieving afbContext");
      return NULL;
  }
  return afbContext;
}

STATIC LuaAfbContextT *LuaCtxPush (lua_State *luaState, afb_req request, void *handle, const char* info) {
  // LuaAfbContextT *afbContext = (LuaAfbContextT *)lua_newuserdata(luaState, sizeof(LuaAfbContextT));
  // luaL_setmetatable(luaState, CTX_TOKEN);
  LuaAfbContextT *afbContext = (LuaAfbContextT *)calloc(1, sizeof(LuaAfbContextT));
  lua_pushlightuserdata(luaState, afbContext);
  if (!afbContext) {
      AFB_ERROR ("LuaCtxPush fail to allocate user data context");
      return NULL;
  }
  afbContext->ctxMagic=CTX_MAGIC;
  afbContext->info=strdup(info);
  afbContext->request= request;
  afbContext->handle= handle;
  return afbContext;
}

STATIC void LuaCtxFree (LuaAfbContextT *afbContext) {   
    free(afbContext->info);
    free(afbContext);
}

// Push a json structure on the stack as a LUA table
STATIC int LuaPushArgument (json_object *argsJ) {
    
    //AFB_NOTICE("LuaPushArgument argsJ=%s", json_object_get_string(argsJ));
  
    json_type jtype= json_object_get_type(argsJ);
    switch (jtype) {
        case json_type_object: {
            lua_newtable (luaState);
            json_object_object_foreach (argsJ, key, val) {
                int done = LuaPushArgument (val);
                if (done) {
                    lua_setfield(luaState,-2, key);  
                }
            }
            break;
        }
        case json_type_array: {
            int length= json_object_array_length(argsJ);
            lua_newtable (luaState);
            for (int idx=0; idx < length; idx ++) {
                json_object *val=json_object_array_get_idx(argsJ, idx);
                LuaPushArgument (val);
                lua_seti (luaState,-2, idx);
            }
            break;
        }
        case json_type_int:
            lua_pushinteger(luaState, json_object_get_int(argsJ));
            break;
        case json_type_string:
            lua_pushstring(luaState, json_object_get_string(argsJ));
            break;
        case json_type_boolean:
            lua_pushboolean(luaState, json_object_get_boolean(argsJ));
            break;
        case json_type_double:
            lua_pushnumber(luaState, json_object_get_double(argsJ));
            break;
        case json_type_null:
            AFB_WARNING("LuaPushArgument: NULL object type %s", json_object_get_string(argsJ));
            return 0;
            break;
            
        default:
            AFB_ERROR("LuaPushArgument: unsupported Json object type %s", json_object_get_string(argsJ));
            return 0;
    }   
    return 1;
}

STATIC  json_object *LuaPopOneArg (lua_State* luaState, int idx);

STATIC json_object *LuaTableToJson (lua_State* luaState, int index) {
    int idx;
    #define LUA_KEY_INDEX -2
    #define LUA_VALUE_INDEX -1
    
    json_object *tableJ= json_object_new_object();
    const char *key;
    char number[3];
    lua_pushnil(luaState); // 1st key
    if (index < 0) index--; 
    for (idx=1; lua_next(luaState, index) != 0; idx++) {

        // uses 'key' (at index -2) and 'value' (at index -1)
        if (lua_type(luaState,LUA_KEY_INDEX) == LUA_TSTRING) key= lua_tostring(luaState, LUA_KEY_INDEX);
        else {
            snprintf(number, sizeof(number),"%d", idx);
            key=number;
        } 
        json_object *argJ= LuaPopOneArg(luaState, LUA_VALUE_INDEX);
        json_object_object_add(tableJ, key, argJ);
        lua_pop(luaState, 1); // removes 'value'; keeps 'key' for next iteration 
    } 
    
    // Query is empty free empty json object
    if (idx == 1) {
        json_object_put(tableJ);
        return NULL;
    }
    return tableJ;
}

STATIC  json_object *LuaPopOneArg (lua_State* luaState, int idx) {
    json_object *value=NULL;

    int luaType = lua_type(luaState, idx);
    switch(luaType)  {
        case LUA_TNUMBER: {
            lua_Number number= lua_tonumber(luaState, idx);;
            int nombre = (int)number; // evil trick to determine wether n fits in an integer. (stolen from ltcl.c)
            if (number == nombre) {
                value= json_object_new_int((int)number);
            } else {
                value= json_object_new_double(number);
            }
            break;
        }
        case LUA_TBOOLEAN:
            value=  json_object_new_boolean(lua_toboolean(luaState, idx));
            break;
        case LUA_TSTRING:
           value=  json_object_new_string(lua_tostring(luaState, idx)); 
            break;
        case LUA_TTABLE: 
            value= LuaTableToJson(luaState, idx);
            break;                
        case LUA_TNIL:
            value=json_object_new_string("nil") ;
            break;
        case LUA_TUSERDATA:
            value=json_object_new_int64((int64_t)lua_touserdata(luaState, idx)); // store userdata as int !!!
            break;
            
        default:
            AFB_NOTICE ("LuaPopOneArg: script returned Unknown/Unsupported idx=%d type:%d/%s", idx, luaType, lua_typename(luaState, luaType));
            value=NULL;
    }

    return value;    
}
    
static json_object *LuaPopArgs (lua_State* luaState, int start) {    
    json_object *responseJ;
    
    int stop = lua_gettop(luaState);
    if(stop-start <0) return NULL;
    
    // start at 2 because we are using a function array lib
    if (start == stop) {
        responseJ=LuaPopOneArg (luaState, start);
    } else {
        // loop on remaining return arguments
        responseJ= json_object_new_array();
        for (int idx=start; idx <= stop; idx++) {
            json_object *argJ=LuaPopOneArg (luaState, idx);
            if (!argJ) goto OnErrorExit;
            json_object_array_add(responseJ, argJ);     
       }
    }
    
    return responseJ;
    
  OnErrorExit:
    return NULL;
}   


STATIC int LuaFormatMessage(lua_State* luaState, LuaAfbMessageT action) {
    char *message;

    json_object *responseJ= LuaPopArgs(luaState, LUA_FIST_ARG);
    
    if (!responseJ) {
        luaL_error(luaState,"LuaFormatMessage empty message");
        goto OnErrorExit;
    }
        
    // if we have only on argument just return the value.
    if (json_object_get_type(responseJ)!=json_type_array || json_object_array_length(responseJ) <2) {
        message= (char*)json_object_get_string(responseJ);
        goto PrintMessage;
    }
    
    // extract format and push all other parameter on the stack
    message = alloca (LUA_MSG_MAX_LENGTH);
    const char *format = json_object_get_string(json_object_array_get_idx(responseJ, 0));
    
    int arrayIdx=1;
    int targetIdx=0;
    
    for (int idx=0; format[idx] !='\0'; idx++) {
        
        if (format[idx]=='%' && format[idx] !='\0') {
            json_object *slotJ= json_object_array_get_idx(responseJ, arrayIdx);
            //if (slotJ) AFB_NOTICE("**** idx=%d slotJ=%s", arrayIdx, json_object_get_string(slotJ));
            

            switch (format[++idx]) {
                case 'd':
                    if (slotJ) targetIdx += snprintf (&message[targetIdx], LUA_MSG_MAX_LENGTH-targetIdx,"%d", json_object_get_int(slotJ)); 
                    else  targetIdx += snprintf (&message[targetIdx], LUA_MSG_MAX_LENGTH-targetIdx,"nil");
                    arrayIdx++;
                    break;
                case 'f':
                    if (slotJ) targetIdx += snprintf (&message[targetIdx], LUA_MSG_MAX_LENGTH-targetIdx,"%f", json_object_get_double(slotJ)); 
                    else  targetIdx += snprintf (&message[targetIdx], LUA_MSG_MAX_LENGTH-targetIdx,"nil");
                    arrayIdx++;
                    break;
                    
                case'%':
                    message[targetIdx]='%';
                    targetIdx++;
                    break;
                    
                case 's':
                default:
                    if (slotJ) targetIdx += snprintf (&message[targetIdx], LUA_MSG_MAX_LENGTH-targetIdx,"%s", json_object_get_string(slotJ));                     
                    else  targetIdx += snprintf (&message[targetIdx], LUA_MSG_MAX_LENGTH-targetIdx,"nil");
                    arrayIdx++;
                }
            
        } else {
            if (targetIdx >= LUA_MSG_MAX_LENGTH) {
                AFB_WARNING ("LuaFormatMessage: message[%s] owerverflow LUA_MSG_MAX_LENGTH=%d", format, LUA_MSG_MAX_LENGTH);
                targetIdx --; // move backward for EOL
                break;
            } else {
                message[targetIdx++] = format[idx];
            }
        }
    }
    message[targetIdx]='\0';

PrintMessage:    
    switch (action) {
        case  AFB_MSG_WARNING:
            AFB_WARNING (message);
            break;
        case AFB_MSG_NOTICE:
            AFB_NOTICE (message);
            break;
        case AFB_MSG_DEBUG:
            AFB_DEBUG (message);
            break;
        case AFB_MSG_INFO:
            AFB_INFO (message);
            break;
        case AFB_MSG_ERROR:       
        default:
            AFB_ERROR (message);            
    }
    return 0;  // nothing return to lua
    
  OnErrorExit: // on argument to return (the error message)
    return 1;
}

STATIC int LuaPrintInfo(lua_State* luaState) { 
    int err=LuaFormatMessage (luaState, AFB_MSG_INFO);
    return err; 
}

STATIC int LuaPrintError(lua_State* luaState) { 
    int err=LuaFormatMessage (luaState, AFB_MSG_ERROR);
    return err; // no value return
}

STATIC int LuaPrintWarning(lua_State* luaState) { 
    int err=LuaFormatMessage (luaState, AFB_MSG_WARNING);
    return err;
}

STATIC int LuaPrintNotice(lua_State* luaState) { 
    int err=LuaFormatMessage (luaState, AFB_MSG_NOTICE);
    return err;
}

STATIC int LuaPrintDebug(lua_State* luaState) {
    int err=LuaFormatMessage (luaState, AFB_MSG_DEBUG);
    return err;
}

STATIC int LuaAfbSuccess(lua_State* luaState) {
    LuaAfbContextT *afbContext= LuaCtxCheck(luaState, LUA_FIST_ARG);
    if (!afbContext) goto OnErrorExit;
    
    // ignore context argument
    json_object *responseJ= LuaPopArgs(luaState, LUA_FIST_ARG+1);
    if (responseJ == JSON_ERROR) return 1;
        
    afb_req_success(afbContext->request, responseJ, NULL);

    LuaCtxFree(afbContext);
    return 0;
 
 OnErrorExit:  
        lua_error(luaState);
        return 1;
}

STATIC int LuaAfbFail(lua_State* luaState) {
    LuaAfbContextT *afbContext= LuaCtxCheck(luaState, LUA_FIST_ARG);
    if (!afbContext) goto OnErrorExit;
    
    json_object *responseJ= LuaPopArgs(luaState, LUA_FIST_ARG+1);
    if (responseJ == JSON_ERROR) return 1;

    afb_req_fail(afbContext->request, afbContext->info, json_object_get_string(responseJ));
    
    LuaCtxFree(afbContext);    
    return 0;   

 OnErrorExit:  
        lua_error(luaState);
        return 1;
}

STATIC void LuaAfbServiceCB(void *handle, int iserror, struct json_object *responseJ) { 
    LuaCallServiceT *contextCB= (LuaCallServiceT*)handle;
    int count=1;
    
    lua_getglobal(luaState, contextCB->callback);
    
    // push error status & response
    lua_pushboolean(luaState, iserror);
    count+= LuaPushArgument(responseJ);
    count+= LuaPushArgument(contextCB->context);

    int err=lua_pcall(luaState, count, LUA_MULTRET, 0);
    if (err) {
        AFB_ERROR ("LUA-SERICE-CB:FAIL response=%s err=%s", json_object_get_string(responseJ), lua_tostring(luaState,-1) );
    }
    
    free (contextCB);
}


STATIC int LuaAfbService(lua_State* luaState) {
    int count = lua_gettop(luaState);
    
    // note: argument start at 2 because of AFB: table
    if (count <5 || !lua_isstring(luaState, 2) || !lua_isstring(luaState, 3) || !lua_istable(luaState, 4) || !lua_isstring(luaState, 5)) {
        lua_pushliteral (luaState, "LuaAfbServiceCall-Syntax is AFB:service_call (api, verb, query, callback, handle ....");
        goto OnErrorExit;        
    }
    
    // get api/verb+query
    const char *api = lua_tostring(luaState,2);
    const char *verb= lua_tostring(luaState,3);
    json_object *queryJ= LuaTableToJson(luaState, 4);
    if (queryJ == JSON_ERROR) return 1;
    
    LuaCallServiceT *contextCB = calloc (1, sizeof(LuaCallServiceT));  
    contextCB->callback= lua_tostring(luaState, 5);
    contextCB->context =  LuaPopArgs(luaState, 6);
    
    afb_service_call(api, verb, queryJ, LuaAfbServiceCB, contextCB);
    
    return 0; // no value return
 
  OnErrorExit:  
        lua_error(luaState);
        return 1;
}

STATIC int LuaAfbServiceSync(lua_State* luaState) {
    int count = lua_gettop(luaState);
    json_object *responseJ;
    
    // note: argument start at 2 because of AFB: table
    if (count <3 || !lua_isstring(luaState, 2) || !lua_isstring(luaState, 3) || !lua_istable(luaState, 4)) {
        lua_pushliteral (luaState, "LuaAfbServiceSync-Syntax is error,data=AFB:service_call (api, verb, query)");
        goto OnErrorExit;        
    }
    
    // get api/verb+query
    const char *api = lua_tostring(luaState,2);
    const char *verb= lua_tostring(luaState,3);
    json_object *queryJ= LuaTableToJson(luaState, 4);
    
    int iserror=afb_service_call_sync (api, verb, queryJ, &responseJ);
    
    // push error status & response
    count=1; lua_pushboolean(luaState, iserror);
    count+= LuaPushArgument(responseJ);

    return count; // return count values
 
  OnErrorExit:  
        lua_error(luaState);
        return 1;
}

STATIC int LuaAfbEventPush(lua_State* luaState) {
    LuaAfbEvent *afbevt;
    int index;
    
    // if no private event handle then use default binding event
    if (lua_islightuserdata(luaState, LUA_FIST_ARG)) {
        afbevt = (LuaAfbEvent*) lua_touserdata(luaState, LUA_FIST_ARG);
        index=LUA_FIST_ARG+1;
    } else {
        index=LUA_FIST_ARG;
        afbevt=luaDefaultEvt;
    }

    if (!afb_event_is_valid(afbevt->event)) {
        lua_pushliteral (luaState, "LuaAfbMakePush-Fail invalid event");
        goto OnErrorExit;
    }
    
    json_object *ctlEventJ= LuaTableToJson(luaState, index);
    if (!ctlEventJ) {
        lua_pushliteral (luaState, "LuaAfbEventPush-Syntax is AFB:signal ([evtHandle], {lua table})");
        goto OnErrorExit;        
    }
    
    int done = afb_event_push(afbevt->event, ctlEventJ);
    if (!done) {
        lua_pushliteral (luaState, "LuaAfbEventPush-Fail No Subscriber to event");
        AFB_ERROR ("LuaAfbEventPush-Fail name subscriber event=%s count=%d", afbevt->name, afbevt->count);
        goto OnErrorExit;
    }
    afbevt->count++;
    return 0; 
 
  OnErrorExit:  
        lua_error(luaState);
        return 1;
}

STATIC int LuaAfbEventSubscribe(lua_State* luaState) {
    LuaAfbEvent *afbevt;
    
    LuaAfbContextT *afbContext= LuaCtxCheck(luaState, LUA_FIST_ARG);
    if (!afbContext) {
        lua_pushliteral (luaState, "LuaAfbEventSubscribe-Fail Invalid request handle");
        goto OnErrorExit;
    }
    
    // if no private event handle then use default binding event
    if (lua_islightuserdata(luaState, LUA_FIST_ARG+1)) {
        afbevt = (LuaAfbEvent*) lua_touserdata(luaState, LUA_FIST_ARG+1);
    } else {
        afbevt=luaDefaultEvt;
    }

    if (!afb_event_is_valid(afbevt->event)) {
        lua_pushliteral (luaState, "LuaAfbMakePush-Fail invalid event handle");
        goto OnErrorExit;
    }
       
    int err = afb_req_subscribe(afbContext->request, afbevt->event);
    if (err) {
        lua_pushliteral (luaState, "LuaAfbEventSubscribe-Fail No Subscriber to event");
        AFB_ERROR ("LuaAfbEventPush-Fail name subscriber event=%s count=%d", afbevt->name, afbevt->count);
        goto OnErrorExit;
    }
    afbevt->count++;
    return 0; 
 
  OnErrorExit:  
        lua_error(luaState);
        return 1;
}

STATIC int LuaAfbEventMake(lua_State* luaState) {
    int count = lua_gettop(luaState);
    LuaAfbEvent *afbevt=calloc(1,sizeof(LuaAfbEvent));
    
    if (count != LUA_FIST_ARG || !lua_isstring(luaState, LUA_FIST_ARG)) {
        lua_pushliteral (luaState, "LuaAfbEventMake-Syntax is evtHandle= AFB:event ('myEventName')");
        goto OnErrorExit;        
    }
    
    // event name should be the only argument
    afbevt->name= strdup (lua_tostring(luaState,LUA_FIST_ARG));

    // create a new binder event
    afbevt->event = afb_daemon_make_event(afbevt->name);
    if (!afb_event_is_valid(afbevt->event)) {
        lua_pushliteral (luaState, "LuaAfbEventMake-Fail to Create Binder event");
        goto OnErrorExit;
    }

    // push event handler as a LUA opaque handle
    lua_pushlightuserdata(luaState, afbevt);
    return 1; 
 
  OnErrorExit:  
        lua_error(luaState);
        return 1;
}

// Function call from LUA when lua2c plugin L2C is used 
PUBLIC int Lua2cWrapper(lua_State* luaState, char *funcname, Lua2cFunctionT callback, void *context) {
    
    json_object *argsJ= LuaPopArgs(luaState, LUA_FIST_ARG+1);
    int response = (*callback) (funcname, argsJ, context);
    
    // push response to LUA
    lua_pushinteger(luaState, response);
    return 1; 
}

// Generated some fake event based on watchdog/counter
PUBLIC int LuaCallFunc (DispatchSourceT source, DispatchActionT *action, json_object *queryJ) {
    
    int err, count;

    json_object* argsJ  = action->argsJ;
    const char*  func   = action->call;
    
    // load function (should exist in CONTROL_PATH_LUA
    lua_getglobal(luaState, func);

    // push source on the stack
    count=1;
    lua_pushinteger(luaState, source);    
    
    // push argsJ on the stack
    if (!argsJ) {
        lua_pushnil(luaState);
        count++;
    } else { 
        count+= LuaPushArgument (argsJ);
    }
    
    // push queryJ on the stack
    if (!queryJ) {
        lua_pushnil(luaState);
        count++;
    } else { 
        count+= LuaPushArgument (queryJ);
    } 

    // effectively exec LUA script code 
    err=lua_pcall(luaState, count, 1, 0);
    if (err)  {
        AFB_ERROR("LuaCallFunc Fail calling %s error=%s", func, lua_tostring(luaState,-1));
        goto OnErrorExit;
    }
    
    // return LUA script value
    int rc= (int)lua_tointeger(luaState, -1); 
    return rc;

  OnErrorExit:
    return -1;
}


// Execute LUA code from received API request 
STATIC void LuaDoAction (LuaDoActionT action, afb_req request) {
    
    int err, count=0;
        
    json_object* queryJ = afb_req_json(request);  
    
    switch (action) {
        
        case LUA_DOSTRING: {
            const char *script = json_object_get_string(queryJ);
            err=luaL_loadstring(luaState, script);
            if (err) {
                AFB_ERROR ("LUA-DO-COMPILE:FAIL String=%s err=%s", script, lua_tostring(luaState,-1) );
                goto OnErrorExit;
            }
            // Push AFB client context on the stack
            LuaAfbContextT *afbContext= LuaCtxPush(luaState, request,NULL,script);
            if (!afbContext) goto OnErrorExit;
            
            break;
        }
    
        case LUA_DOCALL: {
            const char *func;
            json_object *argsJ=NULL;
            
            err= wrap_json_unpack (queryJ, "{s:s, s?o !}", "func", &func, "args", &argsJ);
            if (err) {
                AFB_ERROR ("LUA-DOCALL-SYNTAX missing func|args query=%s", json_object_get_string(queryJ));
                goto OnErrorExit;
            }

            // load function (should exist in CONTROL_PATH_LUA
            lua_getglobal(luaState, func);
                          
            // Push AFB client context on the stack
            LuaAfbContextT *afbContext= LuaCtxPush(luaState, request, NULL, func);
            if (!afbContext) goto OnErrorExit;

            // push query on the stack
            if (!argsJ) {
                lua_pushnil(luaState);
                count++;
            } else { 
                count+= LuaPushArgument (argsJ);
            }
            
            break;
        }
            
        case LUA_DOSCRIPT: {   // Fulup need to fix argument passing
            const char *script;
            char*func=NULL;
            char *filename; char*fullpath;
            char luaScriptPath[CONTROL_MAXPATH_LEN];
            json_object *argsJ=NULL;
            int index;
            
            // scan luascript search path once
            static json_object *luaScriptPathJ =NULL;

            err= wrap_json_unpack (queryJ, "{s:s, s?s s?o !}", "script", &script,"func", &func, "args", &argsJ);
            if (err) {
                AFB_ERROR ("LUA-DOSCRIPT-SYNTAX:missing script|(args,arg) query=%s", json_object_get_string(queryJ));
                goto OnErrorExit;
            }

            // search for filename=script in CONTROL_LUA_PATH
            if (!luaScriptPathJ)  luaScriptPathJ= ScanForConfig(CONTROL_LUA_PATH , CTL_SCAN_RECURSIVE,CONTROL_DOSCRIPT_PRE "-", script);
            for (index=0; index < json_object_array_length(luaScriptPathJ); index++) {
                json_object *entryJ=json_object_array_get_idx(luaScriptPathJ, index);  
                
                err= wrap_json_unpack (entryJ, "{s:s, s:s !}", "fullpath",  &fullpath,"filename", &filename);
                if (err) {
                    AFB_ERROR ("LUA-DOSCRIPT-SCAN:HOOPs invalid config file path = %s", json_object_get_string(entryJ));
                    goto OnErrorExit;
                }
                
                if (index > 0) AFB_WARNING("LUA-DOSCRIPT-SCAN:Ignore second script=%s path=%s", filename, fullpath);
                else {
                    strncpy (luaScriptPath, fullpath, sizeof(luaScriptPath));
                    strncat (luaScriptPath, "/", sizeof(luaScriptPath));
                    strncat (luaScriptPath, filename, sizeof(luaScriptPath)); 
                }               
            }
            
            err= luaL_loadfile(luaState, luaScriptPath);   
            if (err) {
                AFB_ERROR ("LUA-DOSCRIPT HOOPs Error in LUA loading scripts=%s err=%s", luaScriptPath, lua_tostring(luaState,-1));
                goto OnErrorExit;
            }
        
            // script was loaded we need to parse to make it executable
            err=lua_pcall(luaState, 0, 0, 0);
            if (err) {
                AFB_ERROR ("LUA-DOSCRIPT:FAIL to load %s", luaScriptPath);
                goto OnErrorExit;
            }
            
            // if no func name given try to deduct from filename
            if (!func) func= (char*)GetMidleName(filename);
            if (!func) {
                AFB_ERROR ("LUA-DOSCRIPT:FAIL to deduct funcname from %s", filename);
                goto OnErrorExit;                
            }
            
            // load function (should exist in CONTROL_PATH_LUA
            lua_getglobal(luaState, func);
                          
            // Push AFB client context on the stack
            LuaAfbContextT *afbContext= LuaCtxPush(luaState, request, NULL, func);
            if (!afbContext) goto OnErrorExit;
            
            // push function arguments
            if (!argsJ) {
                lua_pushnil(luaState);
                count++;
            } else { 
                count+= LuaPushArgument(argsJ);
            }
            
            break;
        }
                
        default: 
            AFB_ERROR ("LUA-DOSCRIPT-ACTION unknown query=%s", json_object_get_string(queryJ));
            goto OnErrorExit;
    }
       
    // effectively exec LUA code (afb_reply/fail done later from callback) 
    err=lua_pcall(luaState, count+1, 0, 0);
    if (err) {
        AFB_ERROR ("LUA-DO-EXEC:FAIL query=%s err=%s", json_object_get_string(queryJ), lua_tostring(luaState,-1));
        goto OnErrorExit;
    }
    return;
    
 OnErrorExit:
    afb_req_fail(request,"LUA:ERROR", lua_tostring(luaState,-1));
    return;
}

PUBLIC void ctlapi_lua_dostring (afb_req request) {       
    LuaDoAction (LUA_DOSTRING, request);
}

PUBLIC void ctlapi_lua_docall (afb_req request) {
    LuaDoAction (LUA_DOCALL, request);
}

PUBLIC void ctlapi_lua_doscript (afb_req request) {
    LuaDoAction (LUA_DOSCRIPT, request);
}

STATIC int LuaTimerClear (lua_State* luaState) {
    
    // Get Timer Handle
    LuaAfbContextT *afbContext= LuaCtxCheck(luaState, LUA_FIST_ARG);
    if (!afbContext) goto OnErrorExit;
    
    // retrieve useful information opaque handle 
    TimerHandleT *timerHandle = (TimerHandleT*)afbContext->handle;
    
    AFB_NOTICE ("LuaTimerClear timer=%s", timerHandle->label);
    TimerEvtStop(timerHandle);
    
    return 0; //happy end
   
OnErrorExit:
    return 1;
}
STATIC int LuaTimerGet (lua_State* luaState) {
    
    // Get Timer Handle
    LuaAfbContextT *afbContext= LuaCtxCheck(luaState, LUA_FIST_ARG);
    if (!afbContext) goto OnErrorExit;
    
    // retrieve useful information opaque handle 
    TimerHandleT *timerHandle = (TimerHandleT*)afbContext->handle;
    
    // create response as a JSON object
    json_object *responseJ= json_object_new_object();
    json_object_object_add(responseJ,"label", json_object_new_string(timerHandle->label));   
    json_object_object_add(responseJ,"delay", json_object_new_int(timerHandle->delay));   
    json_object_object_add(responseJ,"count", json_object_new_int(timerHandle->count));   
    
    // return JSON object as Lua table
    int count=LuaPushArgument(responseJ);
    
    // free json object
    json_object_put(responseJ);
    
    return count; // return argument
   
OnErrorExit:
    return 0;
}

// Timer Callback

// Set timer 
STATIC int LuaTimerSetCB (void *handle) {
    LuaCallServiceT *contextCB =(LuaCallServiceT*) handle;
    TimerHandleT *timerHandle = (TimerHandleT*) contextCB->handle;
    int count;
    
    // push timer handle and user context on Lua stack
    lua_getglobal(luaState, contextCB->callback);
    
    // Push timer handle
    LuaAfbContextT *afbContext= LuaCtxPush(luaState, NULL_AFBREQ, contextCB->handle, timerHandle->label);
    if (!afbContext) goto OnErrorExit;
    count=1;
    
    // Push user Context
    count+= LuaPushArgument(contextCB->context);  
    
    int err=lua_pcall(luaState, count, LUA_MULTRET, 0); 
    if (err) {
        AFB_ERROR ("LUA-TIMER-CB:FAIL response=%s err=%s", json_object_get_string(contextCB->context), lua_tostring(luaState,-1));
        goto OnErrorExit;
    }
    
    // get return parameter
    if (!lua_isboolean(luaState, -1)) {
        return (lua_toboolean(luaState, -1)); 
    }

    // timer last run free context resource
    if (timerHandle->count == 1) {
        LuaCtxFree(afbContext);
    }
    return 0;  // By default we are happy
 
 OnErrorExit:
    return 1;  // stop timer
}

STATIC int LuaTimerSet(lua_State* luaState) {
    const char *label=NULL, *info=NULL;
    int delay=0, count=0;

    json_object *timerJ = LuaPopOneArg(luaState, LUA_FIST_ARG);
    const char *callback = lua_tostring(luaState, LUA_FIST_ARG + 1);
    json_object *contextJ = LuaPopOneArg(luaState, LUA_FIST_ARG + 2);

    if (lua_gettop(luaState) != LUA_FIST_ARG+2 || !timerJ || !callback || !contextJ) {
        lua_pushliteral(luaState, "LuaTimerSet-Syntax timerset (timerT, 'callback', contextT)");
        goto OnErrorExit;
    }
    
    int err = wrap_json_unpack(timerJ, "{ss, s?s si, si !}", "label", &label, "info", &info, "delay", &delay, "count", &count);
    if (err) {
        lua_pushliteral(luaState, "LuaTimerSet-Syntax timerT={label:xxx delay:ms, count:xx}");
        goto OnErrorExit;
    }
    
    // everything look fine create timer structure
    TimerHandleT *timerHandle = malloc (sizeof (TimerHandleT));
    timerHandle->delay=delay;
    timerHandle->count=count;
    timerHandle->label=label;

    // Allocate handle to store context and callback
    LuaCallServiceT *contextCB = calloc (1, sizeof(LuaCallServiceT));  
    contextCB->callback= callback;
    contextCB->context = contextJ;
    contextCB->handle  = timerHandle;

    // fire timer
    TimerEvtStart (timerHandle, LuaTimerSetCB, contextCB);
    
    return 0;  // Happy No Return Function

OnErrorExit:
    lua_error(luaState);
    return 1; // return error code
}

// Register a new L2c list of LUA user plugin commands
PUBLIC void LuaL2cNewLib(const char *label, luaL_Reg *l2cFunc, int count) {
    // luaL_newlib(luaState, l2cFunc); macro does not work with pointer :(
    luaL_checkversion(luaState);
    lua_createtable(luaState, 0, count+1);
    luaL_setfuncs(luaState,l2cFunc,0);
    lua_setglobal(luaState, label);
}

static const luaL_Reg afbFunction[] = {
    {"timerclear", LuaTimerClear},
    {"timerget"  , LuaTimerGet},
    {"timerset"  , LuaTimerSet},
    {"notice"    , LuaPrintNotice},
    {"info"      , LuaPrintInfo},
    {"warning"   , LuaPrintWarning},
    {"debug"     , LuaPrintDebug},
    {"error"     , LuaPrintError},
    {"servsync"  , LuaAfbServiceSync},
    {"service"   , LuaAfbService},
    {"success"   , LuaAfbSuccess},
    {"fail"      , LuaAfbFail},
    {"subscribe" , LuaAfbEventSubscribe},
    {"evtmake"   , LuaAfbEventMake},
    {"evtpush"   , LuaAfbEventPush},
    
    {NULL, NULL}  /* sentinel */
};

// Create Binding Event at Init
PUBLIC int LuaLibInit () {
    int err, index;
    
    // search for default policy config file
    char fullprefix[CONTROL_MAXPATH_LEN];
    strncpy (fullprefix, CONTROL_CONFIG_PRE "-", sizeof(fullprefix));
    strncat (fullprefix, GetBinderName(), sizeof(fullprefix));
    strncat (fullprefix, "-", sizeof(fullprefix));
    
    const char *dirList= getenv("CONTROL_LUA_PATH");
    if (!dirList) dirList=CONTROL_LUA_PATH;
  
    json_object *luaScriptPathJ = ScanForConfig(dirList , CTL_SCAN_RECURSIVE, fullprefix, "lua");
    
    // open a new LUA interpretor
    luaState = luaL_newstate();
    if (!luaState)  {
        AFB_ERROR ("LUA_INIT: Fail to open lua interpretor");
        goto OnErrorExit;
    }
    
    // load auxiliary libraries
    luaL_openlibs(luaState);

    // redirect print to AFB_NOTICE    
    luaL_newlib(luaState, afbFunction);
    lua_setglobal(luaState, "AFB");
    
    // create default lua event to send test pause/resume
    luaDefaultEvt=calloc(1,sizeof(LuaAfbEvent));
    luaDefaultEvt->name=CONTROL_LUA_EVENT;
    luaDefaultEvt->event = afb_daemon_make_event(CONTROL_LUA_EVENT);
    if (!afb_event_is_valid(luaDefaultEvt->event)) {
        AFB_ERROR ("POLCTL_INIT: Cannot register lua-events=%s ", CONTROL_LUA_EVENT);
        goto OnErrorExit;;
    }
        
    // load+exec any file found in LUA search path
    for (index=0; index < json_object_array_length(luaScriptPathJ); index++) {
        json_object *entryJ=json_object_array_get_idx(luaScriptPathJ, index);
        
        char *filename; char*fullpath;
        err= wrap_json_unpack (entryJ, "{s:s, s:s !}", "fullpath",  &fullpath,"filename", &filename);
        if (err) {
            AFB_ERROR ("LUA-INIT HOOPs invalid config file path = %s", json_object_get_string(entryJ));
            goto OnErrorExit;
        }
        
        char filepath[CONTROL_MAXPATH_LEN];
        strncpy(filepath, fullpath, sizeof(filepath)); 
        strncat(filepath, "/", sizeof(filepath)); 
        strncat(filepath, filename, sizeof(filepath)); 
        err= luaL_loadfile(luaState, filepath);   
        if (err) {
            AFB_ERROR ("LUA-LOAD HOOPs Error in LUA loading scripts=%s err=%s", filepath, lua_tostring(luaState,-1));
            goto OnErrorExit;
        }
        
        // exec/compil script
        err = lua_pcall(luaState, 0, 0, 0);
        if (err) {
            AFB_ERROR ("LUA-LOAD HOOPs Error in LUA exec scripts=%s err=%s", filepath, lua_tostring(luaState,-1));
            goto OnErrorExit;
        }    
    }
    
    // no policy config found remove control API from binder
    if (index == 0)  {
        AFB_WARNING ("POLICY-INIT:WARNING (setenv CONTROL_LUA_PATH) No LUA '%s*.lua' in '%s'", fullprefix, dirList);
    }
       
    AFB_DEBUG ("Audio control-LUA Init Done");
    return 0;
    
 OnErrorExit:    
    return 1;
}