cbb2d579507373e47e462d816724a000a1be143e
[AGL/documentation.git] / docs / 3_Developer_Guides / 5_Controller_Guides / 3.6.2_Controller_Configuration.md
1 ---
2 edit_link: ''
3 title: Controller Configuration
4 origin_url: >-
5   https://git.automotivelinux.org/src/libappcontroller/plain/docs/controllerConfig.md?h=master
6 ---
7
8 <!-- WARNING: This file is generated by fetch_docs.js using /home/boron/Documents/AGL/docs-webtemplate/site/_data/tocs/devguides/master/libappcontroller-guides-devguides-book.yml -->
9
10 # Controller binding configuration
11
12 By default the controller searches for a config filename with the same 'middlename' as the daemon process. As an example if your process name is afb-daemon then middle name is 'daemon'. In addition, if your process name is afb-daemon-audio the middle name is also 'daemon'. Moreover the prefix is chosen when you call the [CtlConfigSearch](<#4)_Do_controller_config_parsing_at_binding_pre-init>) function, see below:
13
14 ```bash
15 CtlConfigSearch(AFB_ApiT apiHandle, const char *dirList, const char *prefix)
16 ```
17
18 ```bash
19 # Middlename is taken from process middlename.
20 (prefix-)middlename*.json
21 ```
22
23 You may overload the config search path with environment variables
24
25 * **CONTROL_CONFIG_PATH**: change default reserch path for configuration. You may provide multiple directories separated by ':'.
26 * **CONTROL_LUA_PATH**: same as CONTROL_CONFIG_PATH but for Lua script files.
27
28 Example: to load a config named '(prefix-)myconfig-test.json' do
29
30 ```bash
31 afb-daemon --name myconfig --verbose ...'
32 ```
33
34 The configuration is loaded dynamically during startup time. The controller scans **CONTROL_CONFIG_PATH** for a file corresponding to the pattern
35 "(prefix-)bindermiddlename*.json". The first file found in the path is loaded,
36 any other file corresponding to the same path is ignored and only generates a warning.
37
38 Each block in the configuration file is defined with
39
40 * **uid**: mandatory, it is used either for debugging or as input for the action (eg: signal name, control name, ...)
41 * **info**:  optional, it is used for documentation purpose only
42
43 > **Note**: by default the controller config search path is defined at compilation time, but the path might be overloaded with the **CONTROL_CONFIG_PATH**
44 > environment variable.
45
46 ## Config is organised in sections
47
48 * **metadata**: describes the configuration
49 * **plugins or resources**: defines the set of functions provided by the plugins allowing to load additionnal resources (compiled C or lua)
50 * **onload**: a collection of actions meant to be executed at startup time
51 * **control**: sets the controls with a collection of actions, in dynamic api it could also specify the verbs of the api
52 * **event**: a collection of actions meant to be executed when receiving a given signal
53 * **personnal sections**: personnal section
54
55 Callbacks to parse sections are documented in [Declare your controller config section in your binding](./Usage.html#declare-your-controller-config-section-in-your-binding) section. You can use the callback defined in controller or define your own callback.
56
57 ## Metadata
58
59 As today matadata is only used for documentation purpose.
60
61 * **uid**: mandatory
62 * **version**: mandatory
63 * **api**: mandatory
64 * **info**: optional
65 * **require**: optional
66 * **author**: optional
67 * **date**: optional
68
69 ## OnLoad section
70
71 Onload section defines startup time configuration. Onload may provide multiple initialisation
72 profiles, each with a different uid.
73
74 You can define the following keys or arrays of the following keys:
75
76 * **uid**: mandatory.
77 * **info**: optional
78 * **action**: mandatory
79 * **args**: optionnal
80
81 ## Control section
82
83 Control section defines a list of controls that are accessible.
84
85 You can define the following keys or arrays of the following keys, moreover
86 this section could be verb api:
87
88 * **uid**: mandatory
89 * **info**: optional
90 * **action**: the list of actions is mandatory
91
92 ## Event section
93
94 Event section defines a list of actions to be executed on event reception. Event can do
95 anything a controller can (change state, send back signal, ...)
96 eg: if a controller subscribes to vehicle speed, then speed-event may adjust
97 master-volume to speed.
98
99 You can define the following keys or arrays of the following keys, moreover you can define an event from an another API with the following syntax "API/event".
100
101 * **uid**: mandatory
102 * **info**: optional
103 * **action**: the list of actions  is mandatory
104
105 ## Plugin section
106
107 Plugin section defines plugins used with this controller. A plugin is a C/C++ program meant to
108 execute some tasks after an event or on demand. This easily extends intrinsec
109 binding logic for ad-hoc needs.
110
111 You can define the following keys or arrays of the following keys:
112
113 * **uid**: mandatory
114 * **info**: optionnal
115 * **spath**: optionnal, semicolon separated paths where to find the plugin. This could be a compiled shared library or LUA scripts. Could be specified using CONTROL_PLUGIN_PATH environment variable also.
116 * **libs**: mandatory, Plugin file or LUA scripts to load
117 * **lua**: optionnal, C functions that could be called from a LUA script
118
119 ## Personnal sections
120
121 * **uid**: mandatory
122 * **info**: optionnal
123 * **action**: mandatory
124 * **any keys wanted**: optionnal
125
126 You can define your own sections and add your own callbacks into the
127 CtlSectionT structure, see
128 [Declare your controller config section in your binding](<#3_Declare_your_controller_config_section_in_your_binding>) section.
129
130 ## Actions Categories
131
132 Controller supports three categories of actions. Each action returns a status
133 where 0=success and 1=failure.
134
135 * **AppFw API** provides a generic model to request other bindings. Requested bindings can be local (eg: ALSA/UCM) or external (eg: vehicle signalling).
136   * `"action": "api://API_NAME#verb_name"`
137 * C-API, when defined in the onload section, the plugin may provide C native API with `CTLP-CAPI(apiname, uid, args, query, context)`. Plugin may also create Lua command with `CTLP-LUA2C(LuaFuncName, uid, args, query, context)`. Where `args`+`query` are JSON-C object and context is the returned value from `CTLP_ONLOAD` function. Any missing value is set to NULL.
138   * `"action": "plugin://plugin_name#function_name"`
139 * Lua-API, when compiled with Lua option, the controller supports action defined directly in Lua script. During "*onload*" phase, the controller searches in `CONTROL_LUA_PATH` file with pattern "(prefix-)bindermiddlename*.lua". Any file corresponding to this pattern is automatically loaded. Any function defined in those Lua scripts can be called through a controller action. Lua functions receive three parameters (uid, args, query).
140   * `"action": "lua://plugin_name#function_name"`
141
142 You also can add the **privileges** property that handles AGL permission
143 needed to be able to call this action.
144
145 > **Note**: Lua added functions are systematically prefixed. AGL standard AppFw
146 functions are prefixed with AGL: (eg: AFB:notice(), AFB:success(), ...).
147 > User Lua functions added through the plugin and CTLP_LUA2C are prefixed with
148 the plugin uid or the one you defined in your config (eg: MyPlug:HelloWorld1).
149
150 ## Available Application Framework Commands
151
152 Each Lua AppFw commands should be prefixed by AFB:
153
154 * `AFB:notice ("format", arg1,... argn)` directly printed LUA tables as json string with '%s'.
155    `AFB:error`, `AFB:warning`, `AFB:info`, `AFB:debug` work on the same model. Printed messages are limited to 512 characters.
156
157 * `AFB:service ('API', 'VERB', {query}, "Lua_Callback_Name", {context})` is an asynchronous call to another binding. When empty, query/context should be set to '{}'
158    and not to 'nil'. When 'nil', Lua does not send 'NULL' value but removes arguments to calling stack. WARNING:"Callback"
159    is the name of the callback as a string and not a pointer to the callback. (If someone as a solution to fix this, please
160    let me known). Callback is call as LUA "function Alsa_Get_Hal_CB (error, result, context)" where:
161   * error is a Boolean
162   * result is the full answer from AppFw (do not forget to extract the response)
163   * context is a copy of the Lua table pass as an argument (warning it's a copy not a pointer to original table)
164
165 * `error,result=AFB:servsync('API', 'VERB', {query})` is saved as previous but for synchronous call. Note that Lua accepts multiple
166    returns. AFB:servsync returns both the error message and the response as a Lua table. Like for AFB:service, the user should not
167    forget to extract response from result.
168
169 * `AFB:success(request, response)` is the success request. request is the opaque handle passes when Lua is called from (api="control", verb="docall").
170    Response is a Lua table that will be returned to the client.
171
172 * `AFB:fail(request, response)` is the same as for success. Note that LUA generates automatically the error code from Lua function name.
173    The response is transformed into a json string before being returned to the client.
174
175 * `EventHandle=AFB:evtmake("MyEventName")` creates an event and returns the handle as an opaque handle. Note that due to a limitation
176    of json_object, this opaque handle cannot be passed as an argument in a callback context.
177
178 * `AFB:subscribe(request, MyEventHandle)` subscribes a given client to a previously created event.
179
180 * `AFB:evtpush (MyEventHandle, MyEventData)` pushes an event to every subscribed client. MyEventData is a Lua table that will be
181    sent as a json object to the corresponding clients.
182
183 * `timerHandle=AFB:timerset (MyTimer, "Timer_Test_CB", context)` initialises a timer from MyTimer Lua table. This table should contains 3 elements:
184    MyTimer={[l"abel"]="MyTimerName", ["delay"]=timeoutInMs, ["count"]=nBOfCycles}. Note that if count==0 then timer is cycled
185    infinitely. Context is a standard Lua table. This function returns an opaque handle to be used to further control the timer.
186
187 * `AFB:timerclear(timerHandle)` kills an existing timer. Returns an error when timer does not exit.
188
189 * `MyTimer=AFB:timerget(timerHandle)` returns uid, delay and count of an active timer. Returns an error when timerHandle does not
190    point on an active timer.
191
192 * `AFB:GetEventLoop()` retrieves the common systemd's event loop of AFB.
193
194 * `AFB:RootDirGetFD()` gets the root directory file descriptor. This file descriptor can be used with functions 'openat', 'fstatat', ...
195
196 > **Note**: Except for functions call during binding initialisation period. Lua calls are protected and should returned clean messages
197 > even when they are improperly used. If you find bug please report.
198
199 ## Adding Lua command from User Plugin
200
201 User Plugin is optional and may provide either native C-action accessible directly from controller actions as defined in
202 JSON config file, or alternatively may provide a set of Lua commands usable inside any script (onload, control,event). A simple
203 plugin that provides both notice C API and Lua commands is provided as example (see ctl-plugin-sample.c). Technically a
204 plugin is a simple sharelibrary and any code fitting in sharelib might be used as a plugin. Developer should nevertheless
205 not forget that except when no-concurrency flag was at binding construction time, any binding should to be thread safe.
206
207 A plugin must be declared with `CTLP_REGISTER("MyCtlSamplePlugin")`. This entry point defines a special structure that is checked
208 at plugin load time by the controller. Then you have an optional init routine declare with `CTLP_ONLOAD(plugin, handle)`.
209  The init routine may create
210 a plugin context that is later presented to every plugin API, this for both LUA and native C ones. Then each:
211
212 * C API declare with `CTLP_CAPI(MyCFunction, source, argsJ, queryJ) {your code}`. Where:
213   * **MyFunction** is your function
214   * **source** is the structure config
215   * **argsJ** a json_object containing the argument attaches to this control in JSON config file
216   * **queryJ** a json_object
217
218 * Lua API declare with `CTLP_LUA2C(MyLuaCFunction, source, argsJ, responseJ) {your code}`. Where
219   * **MyLuaCFunction** is both the name of your C function and Lua command
220   * **source** is the structure config
221   * **argsJ** the arguments passed this time from Lua script and not from Json config file.
222   * **responseJ** if success the argument is passed into the request.
223
224 > **Warning**: Lua samples use with controller enforce strict mode. As a result every variable should be declared either as
225 > local or as global. Unfortunately "luac" is not smart enough to handle strict mode at build time and errors only appear
226 > at run time. Because of this strict mode every global variables (which include functions) should be prefixed by '_'.
227 > Note that LUA requires an initialisation value for every variables and declaring something like "local myvar" will not
228 > allocate "myvar".
229
230 ## Debugging Facilities
231
232 Controller Lua scripts are checked for syntax from CMAKE template with Luac. When needed to go further, a developer API should be allowed to
233 execute directly Lua commands within the controller context from Rest/Ws (api=control, verb=lua_doscript). DoScript API takes two
234 other optional arguments func=xxxx where xxxx is the function to execute within Lua script and args, a JSON object to provide
235 input parameters. When funcname is not given by default, the controller tries to execute middle filename doscript-xxxx-????.lua.
236
237 When executed from the controller, Lua script may use any AppFw Apis as well as any L2C user defines commands in plugin.
238
239 ## Running as Standalone Controller
240
241 The controller is a standard binding. It can be started with the following command:
242
243 ```bash
244 afb-daemon --name=yourname --port=1234 --workdir=. --roothttp=./htdocs --tracereq=common --token= --verbose --binding=pathtoyourbinding.so --monitoring
245 ```
246
247 Afb-Daemon only loads controller bindings without searching for the other
248 binding. In this case, the controller binding will search for a configuration file
249 name '(prefix-)bindermiddlename*.json'. This model can be used to implement for testing
250 purpose or simply to act as the glue between a UI and other binder/services.