From 33c2cd0236823d108cbb21af34b8d7843d117ac1 Mon Sep 17 00:00:00 2001 From: Fulup Ar Foll Date: Thu, 3 Aug 2017 21:56:01 +0200 Subject: Initial version of Policy Control --- Alsa-Plugin/Alsa-Policy-Hook/AlsaHookCb.c | 427 ------------------------ Alsa-Plugin/Alsa-Policy-Hook/CMakeLists.txt | 4 +- Alsa-Plugin/Alsa-Policy-Hook/PolicyHookCb.c | 488 ++++++++++++++++++++++++++++ Alsa-Plugin/Alsa-Policy-Hook/README.md | 34 +- PolicyCtl-afb/CMakeLists.txt | 58 ++++ PolicyCtl-afb/polctl-apidef.h | 90 +++++ PolicyCtl-afb/polctl-apidef.json | 175 ++++++++++ PolicyCtl-afb/polctl-binding.c | 174 ++++++++++ conf.d/alsa/asoundrc.sample | 38 ++- nbproject/configurations.xml | 242 +++++++++----- nbproject/project.xml | 2 +- 11 files changed, 1188 insertions(+), 544 deletions(-) delete mode 100644 Alsa-Plugin/Alsa-Policy-Hook/AlsaHookCb.c create mode 100644 Alsa-Plugin/Alsa-Policy-Hook/PolicyHookCb.c create mode 100644 PolicyCtl-afb/CMakeLists.txt create mode 100644 PolicyCtl-afb/polctl-apidef.h create mode 100644 PolicyCtl-afb/polctl-apidef.json create mode 100644 PolicyCtl-afb/polctl-binding.c diff --git a/Alsa-Plugin/Alsa-Policy-Hook/AlsaHookCb.c b/Alsa-Plugin/Alsa-Policy-Hook/AlsaHookCb.c deleted file mode 100644 index 2675805..0000000 --- a/Alsa-Plugin/Alsa-Policy-Hook/AlsaHookCb.c +++ /dev/null @@ -1,427 +0,0 @@ -/* - * Copyright (C) 2016 "IoT.bzh" - * Author Fulup Ar Foll - * - * 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. - * - * AfbCallBack (snd_ctl_hal_t *handle, int numid, void **response); - * AlsaHookInit is mandatory and called with numid=0 - * - * Syntax in .asoundrc file - * CrlLabel { cb MyFunctionName name "My_Second_Control" } - * - * Testing: - * aplay -DAlsaHook /usr/share/sounds/alsa/test.wav - * - * References: - * https://www.spinics.net/lists/alsa-devel/msg54235.html - * https://github.com/shivdasgujare/utilities/blob/master/nexuss/alsa-scenario-hook/src/alsa-wrapper.c - */ - -#define _GNU_SOURCE -#include -#include -#include -#include - -#include -#include - -#include "afb/afb-wsj1.h" -#include "afb/afb-ws-client.h" -#include -#include - - -#define PLUGIN_ENTRY_POINT AlsaInstallHook - // Fulup Note: What ever you may find on Internet you should use - // SND_CONFIG_DLSYM_VERSION_HOOK and not SND_CONFIG_DLSYM_VERSION_HOOK - SND_DLSYM_BUILD_VERSION(PLUGIN_ENTRY_POINT, SND_PCM_DLSYM_VERSION) - -// this should be more than enough -#define MAX_API_CALL 10 - -// Currently not implemented -#define UNUSED(x) UNUSED_ ## x __attribute__((__unused__)) -#define UNUSED_FUNCTION(x) __attribute__((__unused__)) UNUSED_ ## x -void OnRequestCB(void* UNUSED(handle) , const char* UNUSED(api), const char* UNUSED(verb), struct afb_wsj1_msg*UNUSED(msg)) {} - - typedef struct { - snd_pcm_t *pcm; - const char *uri; - struct afb_wsj1 *wsj1; - sd_event *sdLoop; - int verbose; - sem_t semaphore; - int count; - int error; -} afbClientT; - -typedef struct { - const char *api; - const char *verb; - long timeout; - char *query; - - sd_event_source *evtSource; - char *callIdTag; - afbClientT *afbClient; -} afbRequestT; - -static void *LoopInThread(void *handle) { - afbClientT *afbClient = (afbClientT*) handle; - int count=0; - int watchdog= 60 *1000000; - - /* loop until end */ - for (;;) { - - if (afbClient->verbose) printf("ON-MAINLOOP Active count=%d\n", count++); - sd_event_run(afbClient->sdLoop, watchdog); - } - - return NULL; -} - -// lost connect with the AudioDaemon -static void OnHangupCB(void *handle, struct afb_wsj1 *wsj1) { - - afbClientT *afbClient = (afbClientT*) handle; - snd_pcm_close (afbClient->pcm); - - SNDERR("(Hoops) Lost Connection to %s", afbClient->uri); - exit(0); -} - -void OnEventCB(void *handle, const char *event, struct afb_wsj1_msg *msg) { - afbClientT *afbClient = (afbClientT*) handle; - int err; - - printf("ON-EVENT %s(%s)\n", event, afb_wsj1_msg_object_s(msg)); - - // pause PCM until request call succeed - err = snd_pcm_pause (afbClient->pcm, 1); - if (err < 0) { - fprintf (stderr, "PCM Fail to pause\n"); - goto OnErrorExit; - } - - // wait on a semaphore until request return or timeout - err = snd_pcm_pause (afbClient->pcm, 0); - if (err < 0) { - fprintf (stderr, "PCM Fail to resume\n"); - goto OnErrorExit; - } - -OnErrorExit: - return; - -} - -// callback interface for wsj1 -static struct afb_wsj1_itf itf = { - .on_hangup = OnHangupCB, - .on_call = OnRequestCB, - .on_event = OnEventCB -}; - -void OnAbortPcm (afbClientT *afbClient) { - printf("ON-ABORT-PCM PCM=%s URI=%s\n", snd_pcm_name(afbClient->pcm), afbClient->uri); - snd_pcm_close (afbClient->pcm); -} - -void OnResponseCB(void *handle, struct afb_wsj1_msg *msg) { - afbRequestT *afbRequest= (afbRequestT*)handle; - - if (afbRequest->afbClient->verbose) printf("ON-RESPONSE call=%s response=%s\n", afbRequest->callIdTag, afb_wsj1_msg_object_s(msg)); - - // Cancel timeout for this request - sd_event_source_unref(afbRequest->evtSource); - - if (! afb_wsj1_msg_is_reply_ok(msg)) { - fprintf(stderr, "ON-RESPONSE ERROR call=%s response=%s\n", afbRequest->callIdTag, afb_wsj1_msg_object_s(msg)); - OnAbortPcm (afbRequest->afbClient); - } - - // When not more waiting call release semaphore - afbRequest->afbClient->count--; - if (afbRequest->afbClient->count == 0) { - if (afbRequest->afbClient->verbose) printf("ON-RESPONSE No More Waiting Request\n"); - afbRequest->afbClient->error=0; - sem_post (&afbRequest->afbClient->semaphore); - } -} - -int OnTimeoutCB (sd_event_source* source, uint64_t timer, void* handle) { - afbClientT *afbClient= (afbClientT*)handle; - - fprintf(stderr, "ON-TIMEOUT Call Request Fail URI=%s\n", afbClient->uri); - - // Close PCM and release waiting client - afbClient->error=1; - sem_post (&afbClient->semaphore); - - return 0; -} - -// Call AGL binder asynchronously by with a timeout -static int CallWithTimeout(afbClientT *afbClient, afbRequestT *afbRequest, int count) { - uint64_t usec; - int err; - - // create a unique tag for request - (void) asprintf(&afbRequest->callIdTag, "%d:%s/%s", count, afbRequest->api, afbRequest->verb); - - err = afb_wsj1_call_s(afbClient->wsj1, afbRequest->api, afbRequest->verb, afbRequest->query, OnResponseCB, afbRequest); - if (err) goto OnErrorExit; - - // create a timer with ~250us accuracy - sd_event_now(afbClient->sdLoop, CLOCK_MONOTONIC, &usec); - sd_event_add_time(afbClient->sdLoop, &afbRequest->evtSource, CLOCK_MONOTONIC, usec+afbRequest->timeout*1000, 250, OnTimeoutCB, afbClient); - - // save client handle in request - afbRequest->afbClient = afbClient; - afbClient->count ++; - - return 0; - -OnErrorExit: - return -1; -} - -static int LaunchCallRequest(afbClientT *afbClient, afbRequestT **afbRequest) { - - pthread_t tid; - int err, idx; - - // Create a main loop - err = sd_event_default(&afbClient->sdLoop); - if (err < 0) { - fprintf(stderr, "LaunchCallRequest: Connection to default event loop failed: %s\n", strerror(-err)); - goto OnErrorExit; - } - - // init waiting counting semaphore - if (sem_init(&afbClient->semaphore, 1, 0) == -1) { - fprintf(stderr, "LaunchCallRequest: Fail Semaphore Init: %s\n", afbClient->uri); - } - - // connect the websocket wsj1 to the uri given by the first argument - afbClient->wsj1 = afb_ws_client_connect_wsj1(afbClient->sdLoop, afbClient->uri, &itf, afbClient); - if (afbClient->wsj1 == NULL) { - fprintf(stderr, "LaunchCallRequest: Connection to %s failed\n", afbClient->uri); - goto OnErrorExit; - } - - // send call request to audio-agent asynchronously (respond with thread mainloop context) - for (idx = 0; afbRequest[idx] != NULL; idx++) { - err = CallWithTimeout(afbClient, afbRequest[idx], idx); - if (err) { - fprintf(stderr, "LaunchCallRequest: Fail call %s//%s/%s&%s", afbClient->uri, afbRequest[idx]->api, afbRequest[idx]->verb, afbRequest[idx]->query); - goto OnErrorExit; - } - } - - // launch counter to keep track of waiting request call - afbClient->count=idx; - - // start a thread with a mainloop to monitor Audio-Agent - err = pthread_create(&tid, NULL, &LoopInThread, afbClient); - if (err) goto OnErrorExit; - - return 0; - -OnErrorExit: - return -1; -} - -static int AlsaCloseHook(snd_pcm_hook_t *hook) { - - afbClientT *afbClient = (afbClientT*) snd_pcm_hook_get_private (hook); - - if (afbClient->verbose) fprintf(stdout, "\nAlsaCloseHook pcm=%s uri=%s\n", snd_pcm_name(afbClient->pcm), afbClient->uri); - return 0; -} - -// Function call when Plugin PCM is OPEN -int PLUGIN_ENTRY_POINT (snd_pcm_t *pcm, snd_config_t *conf) { - afbRequestT **afbRequest; - snd_pcm_hook_t *h_close = NULL; - snd_config_iterator_t it, next; - afbClientT *afbClient = malloc(sizeof (afbClientT)); - afbRequest = malloc(MAX_API_CALL * sizeof (afbRequestT)); - int err; - - // start populating client handle - afbClient->pcm = pcm; - afbClient->verbose = 0; - - - // Get PCM arguments from asoundrc - snd_config_for_each(it, next, conf) { - snd_config_t *node = snd_config_iterator_entry(it); - const char *id; - - // ignore comment en empty lines - if (snd_config_get_id(node, &id) < 0) continue; - if (strcmp(id, "comment") == 0 || strcmp(id, "hint") == 0) continue; - - if (strcmp(id, "uri") == 0) { - if (snd_config_get_string(node, &afbClient->uri) < 0) { - SNDERR("Invalid String for %s", id); - goto OnErrorExit; - } - continue; - } - - if (strcmp(id, "verbose") == 0) { - afbClient->verbose= snd_config_get_bool(node); - if (afbClient->verbose < 0) { - SNDERR("Invalid Boolean for %s", id); - goto OnErrorExit; - } - continue; - } - - if (strcmp(id, "request") == 0) { - const char *callConf, *callLabel; - snd_config_type_t ctype; - snd_config_iterator_t currentCall, follow; - snd_config_t *itemConf; - int callCount=0; - - ctype = snd_config_get_type(node); - if (ctype != SND_CONFIG_TYPE_COMPOUND) { - snd_config_get_string(node, &callConf); - SNDERR("Invalid compound type for %s", callConf); - goto OnErrorExit; - } - - - // loop on each call - snd_config_for_each(currentCall, follow, node) { - snd_config_t *ctlconfig = snd_config_iterator_entry(currentCall); - - // ignore empty line - if (snd_config_get_id(ctlconfig, &callLabel) < 0) continue; - - // each clt should be a valid config compound - ctype = snd_config_get_type(ctlconfig); - if (ctype != SND_CONFIG_TYPE_COMPOUND) { - snd_config_get_string(node, &callConf); - SNDERR("Invalid call element for %s", callLabel); - goto OnErrorExit; - } - - // allocate an empty call request - afbRequest[callCount] = malloc(sizeof (afbRequestT)); - afbRequest[callCount]->api=NULL; - afbRequest[callCount]->verb=NULL; - afbRequest[callCount]->query=NULL; - - - err = snd_config_search(ctlconfig, "api", &itemConf); - if (!err) { - if (snd_config_get_string(itemConf, &afbRequest[callCount]->api) < 0) { - SNDERR("Invalid api string for %s", callLabel); - goto OnErrorExit; - } - } - - err = snd_config_search(ctlconfig, "verb", &itemConf); - if (!err) { - if (snd_config_get_string(itemConf, &afbRequest[callCount]->verb) < 0) { - SNDERR("Invalid verb string %s", id); - goto OnErrorExit; - } - } - - err = snd_config_search(ctlconfig, "timeout", &itemConf); - if (!err) { - if (snd_config_get_integer(itemConf, &afbRequest[callCount]->timeout) < 0) { - SNDERR("Invalid timeout Integer %s", id); - goto OnErrorExit; - } - } - - err = snd_config_search(ctlconfig, "query", &itemConf); - if (!err) { - const char *query; - if (snd_config_get_string(itemConf, &query) < 0) { - SNDERR("Invalid query string %s", id); - goto OnErrorExit; - } - // cleanup string for json_tokener - afbRequest[callCount]->query = strdup(query); - for (int idx = 0; query[idx] != '\0'; idx++) { - if (query[idx] == '\'') afbRequest[callCount]->query[idx] = '"'; - else afbRequest[callCount]->query[idx] = query[idx]; - } - json_object *queryJ = json_tokener_parse(query); - if (!queryJ) { - SNDERR("Invalid Json %s query=%s format \"{'tok1':'val1', 'tok2':'val2'}\" ", id, query); - goto OnErrorExit; - } - } - - // Simple check on call request validity - if (!afbRequest[callCount]->query) afbRequest[callCount]->query= ""; - if (!afbRequest[callCount]->timeout) afbRequest[callCount]->timeout=100; - if (!afbRequest[callCount]->verb || !afbRequest[callCount]->api) { - SNDERR("Missing api/verb %s in asoundrc", callLabel); - goto OnErrorExit; - } - - // move to next call if any - callCount ++; - if (callCount == MAX_API_CALL) { - SNDERR("Too Many call MAX_API_CALL=%d", MAX_API_CALL); - goto OnErrorExit; - } - afbRequest[callCount]=NULL; // afbRequest array is NULL terminated - - } - continue; - } - } - - if (afbClient->verbose) fprintf(stdout, "\nAlsaHook Install Start PCM=%s URI=%s\n", snd_pcm_name(afbClient->pcm), afbClient->uri); - - err = snd_pcm_hook_add(&h_close, afbClient->pcm, SND_PCM_HOOK_TYPE_CLOSE, AlsaCloseHook, afbClient); - if (err < 0) goto OnErrorExit; - - // launch call request and create a waiting mainloop thread - err = LaunchCallRequest(afbClient, afbRequest); - if (err < 0) { - fprintf (stderr, "PCM Fail to Enter Mainloop\n"); - goto OnErrorExit; - } - - // wait for all call request to return - sem_wait(&afbClient->semaphore); - if (afbClient->error) { - fprintf (stderr, "PCM Authorisation from Audio Agent Refused\n"); - goto OnErrorExit; - } - - if (afbClient->verbose) fprintf(stdout, "\nAlsaHook Install Success PCM=%s URI=%s\n", snd_pcm_name(afbClient->pcm), afbClient->uri); - return 0; - -OnErrorExit: - fprintf(stderr, "\nAlsaPcmHook Plugin Install Fail PCM=%s\n", snd_pcm_name(afbClient->pcm)); - if (h_close) - snd_pcm_hook_remove(h_close); - - return -EINVAL; -} - diff --git a/Alsa-Plugin/Alsa-Policy-Hook/CMakeLists.txt b/Alsa-Plugin/Alsa-Policy-Hook/CMakeLists.txt index 3780ee5..e8342a1 100644 --- a/Alsa-Plugin/Alsa-Policy-Hook/CMakeLists.txt +++ b/Alsa-Plugin/Alsa-Policy-Hook/CMakeLists.txt @@ -20,10 +20,10 @@ add_compile_options(-DPIC) -PROJECT_TARGET_ADD(alsa_hook_cb) +PROJECT_TARGET_ADD(policy_hook_cb) # Define targets - ADD_LIBRARY(${TARGET_NAME} MODULE AlsaHookCb.c) + ADD_LIBRARY(${TARGET_NAME} MODULE PolicyHookCb.c) # Alsa Plugin properties SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES diff --git a/Alsa-Plugin/Alsa-Policy-Hook/PolicyHookCb.c b/Alsa-Plugin/Alsa-Policy-Hook/PolicyHookCb.c new file mode 100644 index 0000000..ae2a5a3 --- /dev/null +++ b/Alsa-Plugin/Alsa-Policy-Hook/PolicyHookCb.c @@ -0,0 +1,488 @@ +/* + * Copyright (C) 2016 "IoT.bzh" + * Author Fulup Ar Foll + * + * 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. + * + * AfbCallBack (snd_ctl_hal_t *handle, int numid, void **response); + * AlsaHookInit is mandatory and called with numid=0 + * + * Syntax in .asoundrc file + * CrlLabel { cb MyFunctionName name "My_Second_Control" } + * + * Testing: + * aplay -DAlsaHook /usr/share/sounds/alsa/test.wav + * + * References: + * https://www.spinics.net/lists/alsa-devel/msg54235.html + * https://github.com/shivdasgujare/utilities/blob/master/nexuss/alsa-scenario-hook/src/alsa-wrapper.c + */ + +#define _GNU_SOURCE +#include +#include +#include +#include + +#include +#include + +#include "afb/afb-wsj1.h" +#include "afb/afb-ws-client.h" +#include +#include + + +#define PLUGIN_ENTRY_POINT AlsaInstallHook + // Fulup Note: What ever you may find on Internet you should use + // SND_CONFIG_DLSYM_VERSION_HOOK and not SND_CONFIG_DLSYM_VERSION_HOOK + SND_DLSYM_BUILD_VERSION(PLUGIN_ENTRY_POINT, SND_PCM_DLSYM_VERSION) + +// this should be more than enough +#define MAX_API_CALL 10 + +// timeout in ms +#define REQUEST_DEFAULT_TIMEOUT 100 +#ifndef MAINLOOP_WATCHDOG +#define MAINLOOP_WATCHDOG 60000 +#endif + +// Currently not implemented +#define UNUSED(x) UNUSED_ ## x __attribute__((__unused__)) +#define UNUSED_FUNCTION(x) __attribute__((__unused__)) UNUSED_ ## x +void OnRequestCB(void* UNUSED(handle) , const char* UNUSED(api), const char* UNUSED(verb), struct afb_wsj1_msg*UNUSED(msg)) {} + + typedef struct { + snd_pcm_t *pcm; + const char *uri; + struct afb_wsj1 *wsj1; + sd_event *sdLoop; + int verbose; + sem_t semaphore; + int count; + int error; +} afbClientT; + +typedef struct { + const char *api; + const char *verb; + long timeout; + char *query; + + sd_event_source *evtSource; + char *callIdTag; + afbClientT *afbClient; +} afbRequestT; + +static void *LoopInThread(void *handle) { + afbClientT *afbClient = (afbClientT*) handle; + int count=0; + int watchdog= MAINLOOP_WATCHDOG *1000; + + /* loop until end */ + for (;;) { + + if (afbClient->verbose) printf("ON-MAINLOOP Active count=%d\n", count++); + sd_event_run(afbClient->sdLoop, watchdog); + } + + return NULL; +} + +// lost connect with the AudioDaemon +static void OnHangupCB(void *handle, struct afb_wsj1 *wsj1) { + + afbClientT *afbClient = (afbClientT*) handle; + SNDERR("(Hoops) Lost Connection to %s", afbClient->uri); + + // try to close PCM when impossible terminate client + int err = snd_pcm_close (afbClient->pcm); + if (err) exit(1); +} + +// supported action +typedef enum { + ACTION_PAUSE, + ACTION_START, + ACTION_STOP, + ACTION_RESUME, + + ACTION_NONE +} evtActionEnumT; + +// action label/enum map +const char *evtActionLabels[] ={ + [ACTION_PAUSE] = "pause", + [ACTION_START] = "start", + [ACTION_STOP] = "stop", + [ACTION_RESUME]= "resume", + + [ACTION_NONE]=NULL +}; + +static evtActionEnumT getActionEnum (const char *label) { + int idx; + + if (!label) return ACTION_NONE; + + for (idx = 0; evtActionLabels[idx] != NULL; idx++) { + if (! strcmp(evtActionLabels[idx], label)) break; + } + + if (evtActionLabels[idx]) return idx; + else return ACTION_NONE; +} + +void OnEventCB(void *handle, const char *event, struct afb_wsj1_msg *msg) { + afbClientT *afbClient = (afbClientT*) handle; + json_object *eventJ, *tmpJ, *dataJ; + const char *action; + int err, value, done; + + + eventJ = afb_wsj1_msg_object_j(msg); + done= json_object_object_get_ex(eventJ,"data", &dataJ); + if (!done) { + SNDERR ("PCM_HOOK: uri=%s empty event action", afbClient->uri); + goto OnErrorExit; + } + + json_object_object_get_ex(dataJ,"action", &tmpJ); + action=json_object_get_string(tmpJ); + + json_object_object_get_ex(dataJ,"value", &tmpJ); + value=json_object_get_int(tmpJ); + + switch (getActionEnum(action)) { + case ACTION_PAUSE: + err = snd_pcm_pause (afbClient->pcm, value); + if (err < 0) SNDERR ("PCM_HOOK: Fail to pause value=%d\n", value); + break; + + case ACTION_STOP: + err = snd_pcm_drop (afbClient->pcm); + if (err < 0) SNDERR ("PCM_HOOK: Fail to close\n"); + break; + + case ACTION_START: + err = snd_pcm_resume (afbClient->pcm); + if (err < 0) SNDERR ("PCM_HOOK: Fail to start\n"); + break; + + default: + SNDERR ("PCM_HOOK: Unsupported Event uri=%s action=%s", afbClient->uri, action); + goto OnErrorExit; + } + + if (afbClient->verbose) printf("ON-EVENT action=%s value=%d\n", action, value); + return; + +OnErrorExit: + SNDERR("ON-EVENT %s(%s)\n", event, afb_wsj1_msg_object_s(msg)); + return; +} + +// callback interface for wsj1 +static struct afb_wsj1_itf itf = { + .on_hangup = OnHangupCB, + .on_call = OnRequestCB, + .on_event = OnEventCB +}; + +void OnResponseCB(void *handle, struct afb_wsj1_msg *msg) { + afbRequestT *afbRequest= (afbRequestT*)handle; + + if (afbRequest->afbClient->verbose) printf("ON-RESPONSE call=%s response=%s\n", afbRequest->callIdTag, afb_wsj1_msg_object_s(msg)); + + // Cancel timeout for this request + sd_event_source_unref(afbRequest->evtSource); + + if (! afb_wsj1_msg_is_reply_ok(msg)) goto OnErrorExit; + + // When not more waiting call release semaphore + afbRequest->afbClient->count--; + if (afbRequest->afbClient->count == 0) { + if (afbRequest->afbClient->verbose) printf("ON-RESPONSE No More Waiting Request\n"); + afbRequest->afbClient->error=0; + sem_post (&afbRequest->afbClient->semaphore); + } + return; + +OnErrorExit: + fprintf(stderr, "ON-RESPONSE ERROR call=%s response=%s\n", afbRequest->callIdTag, afb_wsj1_msg_object_s(msg)); + afbRequest->afbClient->error=1; + sem_post (&afbRequest->afbClient->semaphore); +} + +int OnTimeoutCB (sd_event_source* source, uint64_t timer, void* handle) { + afbClientT *afbClient= (afbClientT*)handle; + + SNDERR("\nON-TIMEOUT Call Request Fail URI=%s\n", afbClient->uri); + + // Close PCM and release waiting client + afbClient->error=1; + sem_post (&afbClient->semaphore); + + return 0; +} + +// Call AGL binder asynchronously by with a timeout +static int CallWithTimeout(afbClientT *afbClient, afbRequestT *afbRequest, int count) { + uint64_t usec; + int err; + + // create a unique tag for request + (void) asprintf(&afbRequest->callIdTag, "%d:%s/%s", count, afbRequest->api, afbRequest->verb); + + // create a timer with ~250us accuracy + sd_event_now(afbClient->sdLoop, CLOCK_MONOTONIC, &usec); + sd_event_add_time(afbClient->sdLoop, &afbRequest->evtSource, CLOCK_MONOTONIC, usec+afbRequest->timeout*1000, 250, OnTimeoutCB, afbClient); + + err = afb_wsj1_call_s(afbClient->wsj1, afbRequest->api, afbRequest->verb, afbRequest->query, OnResponseCB, afbRequest); + if (err) goto OnErrorExit; + + // save client handle in request + afbRequest->afbClient = afbClient; + afbClient->count ++; + + return 0; + +OnErrorExit: + return -1; +} + +static int LaunchCallRequest(afbClientT *afbClient, afbRequestT **afbRequest) { + + pthread_t tid; + int err, idx; + + // init waiting counting semaphore + if (sem_init(&afbClient->semaphore, 1, 0) == -1) { + fprintf(stderr, "LaunchCallRequest: Fail Semaphore Init: %s\n", afbClient->uri); + } + + // Create a main loop + err = sd_event_default(&afbClient->sdLoop); + if (err < 0) { + fprintf(stderr, "LaunchCallRequest: Connection to default event loop failed: %s\n", strerror(-err)); + goto OnErrorExit; + } + + // start a thread with a mainloop to monitor Audio-Agent + err = pthread_create(&tid, NULL, &LoopInThread, afbClient); + if (err) goto OnErrorExit; + + // connect the websocket wsj1 to the uri given by the first argument + afbClient->wsj1 = afb_ws_client_connect_wsj1(afbClient->sdLoop, afbClient->uri, &itf, afbClient); + if (afbClient->wsj1 == NULL) { + fprintf(stderr, "LaunchCallRequest: Connection to %s failed\n", afbClient->uri); + goto OnErrorExit; + } + + // send call request to audio-agent asynchronously (respond with thread mainloop context) + for (idx = 0; afbRequest[idx] != NULL; idx++) { + err = CallWithTimeout(afbClient, afbRequest[idx], idx); + if (err) { + fprintf(stderr, "LaunchCallRequest: Fail call %s//%s/%s&%s", afbClient->uri, afbRequest[idx]->api, afbRequest[idx]->verb, afbRequest[idx]->query); + goto OnErrorExit; + } + } + + // launch counter to keep track of waiting request call + afbClient->count=idx; + + return 0; + +OnErrorExit: + return -1; +} + +static int AlsaCloseHook(snd_pcm_hook_t *hook) { + + afbClientT *afbClient = (afbClientT*) snd_pcm_hook_get_private (hook); + + if (afbClient->verbose) fprintf(stdout, "\nAlsaCloseHook pcm=%s\n", snd_pcm_name(afbClient->pcm)); + return 0; +} + +// Function call when Plugin PCM is OPEN +int PLUGIN_ENTRY_POINT (snd_pcm_t *pcm, snd_config_t *conf) { + afbRequestT **afbRequest; + snd_pcm_hook_t *h_close = NULL; + snd_config_iterator_t it, next; + afbClientT *afbClient = malloc(sizeof (afbClientT)); + afbRequest = malloc(MAX_API_CALL * sizeof (afbRequestT)); + int err; + + // start populating client handle + afbClient->pcm = pcm; + afbClient->verbose = 0; + + + // Get PCM arguments from asoundrc + snd_config_for_each(it, next, conf) { + snd_config_t *node = snd_config_iterator_entry(it); + const char *id; + + // ignore comment en empty lines + if (snd_config_get_id(node, &id) < 0) continue; + if (strcmp(id, "comment") == 0 || strcmp(id, "hint") == 0) continue; + + if (strcmp(id, "uri") == 0) { + const char *uri; + if (snd_config_get_string(node, &uri) < 0) { + SNDERR("Invalid String for %s", id); + goto OnErrorExit; + } + afbClient->uri=strdup(uri); + continue; + } + + if (strcmp(id, "verbose") == 0) { + afbClient->verbose= snd_config_get_bool(node); + if (afbClient->verbose < 0) { + SNDERR("Invalid Boolean for %s", id); + goto OnErrorExit; + } + continue; + } + + if (strcmp(id, "request") == 0) { + const char *callConf, *callLabel; + snd_config_type_t ctype; + snd_config_iterator_t currentCall, follow; + snd_config_t *itemConf; + int callCount=0; + + ctype = snd_config_get_type(node); + if (ctype != SND_CONFIG_TYPE_COMPOUND) { + snd_config_get_string(node, &callConf); + SNDERR("Invalid compound type for %s", callConf); + goto OnErrorExit; + } + + + // loop on each call + snd_config_for_each(currentCall, follow, node) { + snd_config_t *ctlconfig = snd_config_iterator_entry(currentCall); + + // ignore empty line + if (snd_config_get_id(ctlconfig, &callLabel) < 0) continue; + + // each clt should be a valid config compound + ctype = snd_config_get_type(ctlconfig); + if (ctype != SND_CONFIG_TYPE_COMPOUND) { + snd_config_get_string(node, &callConf); + SNDERR("Invalid call element for %s", callLabel); + goto OnErrorExit; + } + + // allocate an empty call request + afbRequest[callCount] = calloc(1, sizeof (afbRequestT)); + + + err = snd_config_search(ctlconfig, "api", &itemConf); + if (!err) { + if (snd_config_get_string(itemConf, &afbRequest[callCount]->api) < 0) { + SNDERR("Invalid api string for %s", callLabel); + goto OnErrorExit; + } + } + + err = snd_config_search(ctlconfig, "verb", &itemConf); + if (!err) { + if (snd_config_get_string(itemConf, &afbRequest[callCount]->verb) < 0) { + SNDERR("Invalid verb string %s", id); + goto OnErrorExit; + } + } + + err = snd_config_search(ctlconfig, "timeout", &itemConf); + if (!err) { + if (snd_config_get_integer(itemConf, &afbRequest[callCount]->timeout) < 0) { + SNDERR("Invalid timeout Integer %s", id); + goto OnErrorExit; + } + } + + err = snd_config_search(ctlconfig, "query", &itemConf); + if (!err) { + const char *query; + if (snd_config_get_string(itemConf, &query) < 0) { + SNDERR("Invalid query string %s", id); + goto OnErrorExit; + } + // cleanup string for json_tokener + afbRequest[callCount]->query = strdup(query); + for (int idx = 0; query[idx] != '\0'; idx++) { + if (query[idx] == '\'') afbRequest[callCount]->query[idx] = '"'; + else afbRequest[callCount]->query[idx] = query[idx]; + } + json_object *queryJ = json_tokener_parse(query); + if (!queryJ) { + SNDERR("Invalid Json %s query=%s format \"{'tok1':'val1', 'tok2':'val2'}\" ", id, query); + goto OnErrorExit; + } + } + + // Simple check on call request validity + if (!afbRequest[callCount]->query) afbRequest[callCount]->query= ""; + if (!afbRequest[callCount]->timeout) afbRequest[callCount]->timeout=REQUEST_DEFAULT_TIMEOUT ; + if (!afbRequest[callCount]->verb || !afbRequest[callCount]->api) { + SNDERR("Missing api/verb %s in asoundrc", callLabel); + goto OnErrorExit; + } + + // move to next call if any + callCount ++; + if (callCount == MAX_API_CALL) { + SNDERR("Too Many call MAX_API_CALL=%d", MAX_API_CALL); + goto OnErrorExit; + } + afbRequest[callCount]=NULL; // afbRequest array is NULL terminated + + } + continue; + } + } + + if (afbClient->verbose) fprintf(stdout, "\nAlsaHook Install Start PCM=%s URI=%s\n", snd_pcm_name(afbClient->pcm), afbClient->uri); + + err = snd_pcm_hook_add(&h_close, afbClient->pcm, SND_PCM_HOOK_TYPE_CLOSE, AlsaCloseHook, afbClient); + if (err < 0) goto OnErrorExit; + + // launch call request and create a waiting mainloop thread + err = LaunchCallRequest(afbClient, afbRequest); + if (err < 0) { + fprintf (stderr, "PCM Fail to Enter Mainloop\n"); + goto OnErrorExit; + } + + // wait for all call request to return + sem_wait(&afbClient->semaphore); + if (afbClient->error) { + fprintf (stderr, "PCM Authorisation from Audio Agent Refused\n"); + goto OnErrorExit; + } + + if (afbClient->verbose) fprintf(stdout, "\nAlsaHook Install Success PCM=%s URI=%s\n", snd_pcm_name(afbClient->pcm), afbClient->uri); + return 0; + +OnErrorExit: + fprintf(stderr, "\nAlsaPcmHook Plugin Install Fail PCM=%s\n", snd_pcm_name(afbClient->pcm)); + if (h_close) + snd_pcm_hook_remove(h_close); + + return -EINVAL; +} + diff --git a/Alsa-Plugin/Alsa-Policy-Hook/README.md b/Alsa-Plugin/Alsa-Policy-Hook/README.md index 108c2b5..ce0553c 100644 --- a/Alsa-Plugin/Alsa-Policy-Hook/README.md +++ b/Alsa-Plugin/Alsa-Policy-Hook/README.md @@ -27,27 +27,33 @@ pcm_hook_type.MyHookPlugin { # -------------------------------------------------------------------- pcm.MyNavigationHook { type hooks - slave.pcm "MyMixerPCM" # Target PCM to effectively play sound + slave.pcm "MyMixerPCM" - # Call request that should succeed before accessing slave PCM + # Defined used hook sharelib and provide arguments/config to install func hooks.0 { - type "MyHookPlugin" # Name=xxxx should match with pcm_hook_type.xxxx + type "MyHookPlugin" hook_args { + verbose true # print few log messages (default false); - # URI to AGL-Advance-Audio-Agent binder + # Every Call should return OK in order PCM to open (default timeout 100ms) uri "ws://localhost:1234/api?token='audio-agent-token'" - - # Call request to send to binder (initial label is free, query is optional) request { - MyFirstCheck { - api "alsacore" - verb "ping" + # Request autorisation to write on navigation + RequestNavigation { + api "polctl" + verb "navigation" } - MySecondCheck { - api "alsacore" - verb "ucmset" - query "{'devid':'hw:v1340','verb':'Navigation','dev':'speakers'}" - } + # subscribe to Audio Agent Event + SubscriveEvents { + api "polctl" + verb "monitor" + } + # force PCM stop after 10s + TestAutoStop { + api "polctl" + verb "event_test" + query "{'label':'stop', 'delay':10000}" + } } } } diff --git a/PolicyCtl-afb/CMakeLists.txt b/PolicyCtl-afb/CMakeLists.txt new file mode 100644 index 0000000..d9776df --- /dev/null +++ b/PolicyCtl-afb/CMakeLists.txt @@ -0,0 +1,58 @@ +########################################################################### +# Copyright 2015, 2016, 2017 IoT.bzh +# +# author: Fulup Ar Foll +# +# 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. +########################################################################### + + +# Generate API-v2 hat from OpenAPI json definition +macro(SET_TARGET_GENSKEL TARGET_NAME API_DEF_NAME) + add_custom_command(OUTPUT ${API_DEF_NAME}.h + WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} + DEPENDS ${API_DEF_NAME}.json + COMMAND afb-genskel ${API_DEF_NAME}.json >${API_DEF_NAME}.h + ) + add_custom_target(${API_DEF_NAME}_OPENAPI DEPENDS ${API_DEF_NAME}.h) + add_dependencies(${TARGET_NAME} ${API_DEF_NAME}_OPENAPI) + +endmacro(SET_TARGET_GENSKEL) + +# Add target to project dependency list +PROJECT_TARGET_ADD(polctl-afb) + + # Define project Targets + ADD_LIBRARY(${TARGET_NAME} MODULE polctl-binding.c ) + + # Generate API-v2 hat from OpenAPI json definition + SET_TARGET_GENSKEL(${TARGET_NAME} polctl-apidef) + + # Binder exposes a unique public entry point + SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES + PREFIX "afb-" + LABELS "BINDING" + LINK_FLAGS ${BINDINGS_LINK_FLAG} + OUTPUT_NAME polctl + + ) + + # Library dependencies (include updates automatically) + TARGET_LINK_LIBRARIES(${TARGET_NAME} + audio-interface + ) + + # installation directory + INSTALL(TARGETS ${TARGET_NAME} + LIBRARY DESTINATION ${BINDINGS_INSTALL_DIR}) + diff --git a/PolicyCtl-afb/polctl-apidef.h b/PolicyCtl-afb/polctl-apidef.h new file mode 100644 index 0000000..9e2b1a7 --- /dev/null +++ b/PolicyCtl-afb/polctl-apidef.h @@ -0,0 +1,90 @@ + +static const char _afb_description_v2_polctl[] = + "{\"openapi\":\"3.0.0\",\"$schema\":\"http:iot.bzh/download/openapi/schem" + "a-3.0/default-schema.json\",\"info\":{\"description\":\"\",\"title\":\"p" + "olctl\",\"version\":\"1.0\",\"x-binding-c-generator\":{\"api\":\"polctl\"" + ",\"version\":2,\"prefix\":\"polctl_\",\"postfix\":\"\",\"start\":null,\"" + "onevent\":null,\"init\":\"polctl_init\",\"scope\":\"\",\"private\":false" + "}},\"servers\":[{\"url\":\"ws://{host}:{port}/api/polctl\",\"description" + "\":\"Unicens2 API.\",\"variables\":{\"host\":{\"default\":\"localhost\"}" + ",\"port\":{\"default\":\"1234\"}},\"x-afb-events\":[{\"$ref\":\"#/compon" + "ents/schemas/afb-event\"}]}],\"components\":{\"schemas\":{\"afb-reply\":" + "{\"$ref\":\"#/components/schemas/afb-reply-v2\"},\"afb-event\":{\"$ref\"" + ":\"#/components/schemas/afb-event-v2\"},\"afb-reply-v2\":{\"title\":\"Ge" + "neric response.\",\"type\":\"object\",\"required\":[\"jtype\",\"request\"" + "],\"properties\":{\"jtype\":{\"type\":\"string\",\"const\":\"afb-reply\"" + "},\"request\":{\"type\":\"object\",\"required\":[\"status\"],\"propertie" + "s\":{\"status\":{\"type\":\"string\"},\"info\":{\"type\":\"string\"},\"t" + "oken\":{\"type\":\"string\"},\"uuid\":{\"type\":\"string\"},\"reqid\":{\"" + "type\":\"string\"}}},\"response\":{\"type\":\"object\"}}},\"afb-event-v2" + "\":{\"type\":\"object\",\"required\":[\"jtype\",\"event\"],\"properties\"" + ":{\"jtype\":{\"type\":\"string\",\"const\":\"afb-event\"},\"event\":{\"t" + "ype\":\"string\"},\"data\":{\"type\":\"object\"}}}},\"x-permissions\":{\"" + "monitor\":{\"permission\":\"urn:AGL:permission:audio:public:monitor\"},\"" + "multimedia\":{\"permission\":\"urn:AGL:permission:audio:public:monitor\"" + "},\"navigation\":{\"permission\":\"urn:AGL:permission:audio:public:monit" + "or\"},\"emergency\":{\"permission\":\"urn:AGL:permission:audio:public:em" + "ergency\"}},\"responses\":{\"200\":{\"description\":\"A complex object a" + "rray response\",\"content\":{\"application/json\":{\"schema\":{\"$ref\":" + "\"#/components/schemas/afb-reply\"}}}}}},\"paths\":{\"/monitor\":{\"desc" + "ription\":\"Subcribe Audio Agent Policy Control End\",\"get\":{\"x-permi" + "ssions\":{\"$ref\":\"#/components/x-permissions/monitor\"},\"parameters\"" + ":[{\"in\":\"query\",\"name\":\"event_patern\",\"required\":true,\"schema" + "\":{\"type\":\"string\"}}],\"responses\":{\"200\":{\"$ref\":\"#/componen" + "ts/responses/200\"}}}},\"/event_test\":{\"description\":\"Pause Resume T" + "est\",\"get\":{\"x-permissions\":{\"$ref\":\"#/components/x-permissions/" + "monitor\"},\"parameters\":[{\"in\":\"query\",\"name\":\"delay\",\"requir" + "ed\":false,\"schema\":{\"type\":\"interger\"}},{\"in\":\"query\",\"name\"" + ":\"count\",\"required\":false,\"schema\":{\"type\":\"interger\"}}],\"res" + "ponses\":{\"200\":{\"$ref\":\"#/components/responses/200\"}}}},\"/naviga" + "tion\":{\"description\":\"Request Access to Navigation Audio Channel.\"," + "\"get\":{\"x-permissions\":{\"$ref\":\"#/components/x-permissions/naviga" + "tion\"},\"parameters\":[{\"in\":\"query\",\"name\":\"zone\",\"required\"" + ":false,\"schema\":{\"type\":\"string\"}}],\"responses\":{\"200\":{\"$ref" + "\":\"#/components/responses/200\"}}}}}}" +; + +static const struct afb_auth _afb_auths_v2_polctl[] = { + { .type = afb_auth_Permission, .text = "urn:AGL:permission:audio:public:monitor" } +}; + + void polctl_monitor(struct afb_req req); + void polctl_event_test(struct afb_req req); + void polctl_navigation(struct afb_req req); + +static const struct afb_verb_v2 _afb_verbs_v2_polctl[] = { + { + .verb = "monitor", + .callback = polctl_monitor, + .auth = &_afb_auths_v2_polctl[0], + .info = NULL, + .session = AFB_SESSION_NONE_V2 + }, + { + .verb = "event_test", + .callback = polctl_event_test, + .auth = &_afb_auths_v2_polctl[0], + .info = NULL, + .session = AFB_SESSION_NONE_V2 + }, + { + .verb = "navigation", + .callback = polctl_navigation, + .auth = &_afb_auths_v2_polctl[0], + .info = NULL, + .session = AFB_SESSION_NONE_V2 + }, + { .verb = NULL } +}; + +const struct afb_binding_v2 afbBindingV2 = { + .api = "polctl", + .specification = _afb_description_v2_polctl, + .info = NULL, + .verbs = _afb_verbs_v2_polctl, + .preinit = NULL, + .init = polctl_init, + .onevent = NULL, + .noconcurrency = 0 +}; + diff --git a/PolicyCtl-afb/polctl-apidef.json b/PolicyCtl-afb/polctl-apidef.json new file mode 100644 index 0000000..65fe0ec --- /dev/null +++ b/PolicyCtl-afb/polctl-apidef.json @@ -0,0 +1,175 @@ +{ + "openapi": "3.0.0", + "$schema": "http:iot.bzh/download/openapi/schema-3.0/default-schema.json", + "info": { + "description": "", + "title": "polctl", + "version": "1.0", + "x-binding-c-generator": { + "api": "polctl", + "version": 2, + "prefix": "polctl_", + "postfix": "", + "start": null , + "onevent": null, + "init": "polctl_init", + "scope": "", + "private": false + } + }, + "servers": [ + { + "url": "ws://{host}:{port}/api/polctl", + "description": "Unicens2 API.", + "variables": { + "host": { + "default": "localhost" + }, + "port": { + "default": "1234" + } + }, + "x-afb-events": [ + { + "$ref": "#/components/schemas/afb-event" + } + ] + } + ], + "components": { + "schemas": { + "afb-reply": { + "$ref": "#/components/schemas/afb-reply-v2" + }, + "afb-event": { + "$ref": "#/components/schemas/afb-event-v2" + }, + "afb-reply-v2": { + "title": "Generic response.", + "type": "object", + "required": [ "jtype", "request" ], + "properties": { + "jtype": { + "type": "string", + "const": "afb-reply" + }, + "request": { + "type": "object", + "required": [ "status" ], + "properties": { + "status": { "type": "string" }, + "info": { "type": "string" }, + "token": { "type": "string" }, + "uuid": { "type": "string" }, + "reqid": { "type": "string" } + } + }, + "response": { "type": "object" } + } + }, + "afb-event-v2": { + "type": "object", + "required": [ "jtype", "event" ], + "properties": { + "jtype": { + "type": "string", + "const": "afb-event" + }, + "event": { "type": "string" }, + "data": { "type": "object" } + } + } + }, + "x-permissions": { + "monitor": { + "permission": "urn:AGL:permission:audio:public:monitor" + }, + "multimedia": { + "permission": "urn:AGL:permission:audio:public:monitor" + }, + "navigation": { + "permission": "urn:AGL:permission:audio:public:monitor" + }, + "emergency": { + "permission": "urn:AGL:permission:audio:public:emergency" + } + }, + "responses": { + "200": { + "description": "A complex object array response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/afb-reply" + } + } + } + } + } + }, + "paths": { + "/monitor": { + "description": "Subcribe Audio Agent Policy Control End", + "get": { + "x-permissions": { + "$ref": "#/components/x-permissions/monitor" + }, + "parameters": [ + { + "in": "query", + "name": "event_patern", + "required": true, + "schema": { "type": "string" } + } + ], + "responses": { + "200": {"$ref": "#/components/responses/200"} + } + } + }, + "/event_test": { + "description": "Pause Resume Test", + "get": { + "x-permissions": { + "$ref": "#/components/x-permissions/monitor" + }, + "parameters": [ + { + "in": "query", + "name": "delay", + "required": false, + "schema": { "type": "interger" } + }, + { + "in": "query", + "name": "count", + "required": false, + "schema": { "type": "interger" } + } + ], + "responses": { + "200": {"$ref": "#/components/responses/200"} + } + } + }, + "/navigation": { + "description": "Request Access to Navigation Audio Channel.", + "get": { + "x-permissions": { + "$ref": "#/components/x-permissions/navigation" + }, + "parameters": [ + { + "in": "query", + "name": "zone", + "required": false, + "schema": { "type": "string" } + } + ], + "responses": { + "200": {"$ref": "#/components/responses/200"} + } + } + } + } +} diff --git a/PolicyCtl-afb/polctl-binding.c b/PolicyCtl-afb/polctl-binding.c new file mode 100644 index 0000000..d24b036 --- /dev/null +++ b/PolicyCtl-afb/polctl-binding.c @@ -0,0 +1,174 @@ +/* + * Copyright (C) 2016 "IoT.bzh" + * Author Fulup Ar Foll + * + * 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. + */ + +#define _GNU_SOURCE +#include +#include +#include +#include + +#include "audio-interface.h" + +STATIC int polctl_init (); + +// Include Binding Stub generated from Json OpenAPI +#include "polctl-apidef.h" + +#define DEFAULT_PAUSE_DELAY 3000 +#define DEFAULT_TEST_COUNT 1 + +typedef int (*timerCallbackT)(void *context); + + +typedef struct { + int value; + const char *label; +} AutoTestCtxT; + +typedef struct TimerHandleS { + int count; + int delay; + AutoTestCtxT *context; + timerCallbackT callback; + sd_event_source *evtSource; +} TimerHandleT; + +static afb_event afbevt; + + +STATIC int TimerNext (sd_event_source* source, uint64_t timer, void* handle) { + TimerHandleT *timerHandle = (TimerHandleT*) handle; + int done; + uint64_t usec; + + // Rearm timer if needed + timerHandle->count --; + if (timerHandle->count == 0) sd_event_source_unref(source); + else { + // otherwise validate timer for a new run + sd_event_now(afb_daemon_get_event_loop(), CLOCK_MONOTONIC, &usec); + sd_event_source_set_enabled(source, SD_EVENT_ONESHOT); + sd_event_source_set_time(source, usec + timerHandle->delay); + } + + done= timerHandle->callback(timerHandle->context); + if (!done) goto OnErrorExit; + + return 0; + +OnErrorExit: + AFB_WARNING("TimerNext Fail tag=%s", timerHandle->context->label); + return -1; +} + +STATIC void TimerStart(TimerHandleT *timerHandle, timerCallbackT callback, void *context) { + uint64_t usec; + + // populate CB handle + timerHandle->callback=callback; + timerHandle->context=context; + + // set a timer with ~250us accuracy + sd_event_now(afb_daemon_get_event_loop(), CLOCK_MONOTONIC, &usec); + sd_event_add_time(afb_daemon_get_event_loop(), &timerHandle->evtSource, CLOCK_MONOTONIC, usec+timerHandle->delay, 250, TimerNext, timerHandle); +} + +STATIC int DoPauseResumeCB (void *context) { + AutoTestCtxT *ctx= (AutoTestCtxT*)context; + json_object *ctlEventJ; + + if (ctx->value) ctx->value =0; + else ctx->value =1; + + ctlEventJ = json_object_new_object(); + json_object_object_add(ctlEventJ,"action", json_object_new_string(ctx->label)); + json_object_object_add(ctlEventJ,"value" , json_object_new_int(ctx->value)); + int done = afb_event_push(afbevt, ctlEventJ); + + AFB_NOTICE ("DoPauseResumeCB {action: '%s', value:%d} status=%d", ctx->label, ctx->value, done); + + return (done); +} + +PUBLIC void polctl_event_test (afb_req request) { + json_object *queryJ, *tmpJ; + TimerHandleT *timerHandle = malloc (sizeof (TimerHandleT)); + AutoTestCtxT *context = calloc (1, sizeof (AutoTestCtxT)); + int done; + + queryJ= afb_req_json(request); + done=json_object_object_get_ex(queryJ, "label", &tmpJ); + if (!done) { + afb_req_fail_f(request, "TEST-LABEL-MISSING", "label is mandatory for event_test"); + goto OnErrorExit; + } + context->label = strdup(json_object_get_string (tmpJ)); + + json_object_object_get_ex(queryJ, "delay", &tmpJ); + timerHandle->delay = json_object_get_int (tmpJ) * 1000; + if (timerHandle->delay == 0) timerHandle->delay=DEFAULT_PAUSE_DELAY * 1000; + + json_object_object_get_ex(queryJ, "count", &tmpJ); + timerHandle->count = json_object_get_int (tmpJ); + if (timerHandle->count == 0) timerHandle->count=DEFAULT_TEST_COUNT; + + // start a lool timer + TimerStart (timerHandle, DoPauseResumeCB, context); + + afb_req_success(request, NULL, NULL); + return; + + OnErrorExit: + return; +} + + +PUBLIC void polctl_navigation (afb_req request) { + + AFB_NOTICE ("Enter polctl_navigation"); + afb_req_success(request, NULL, NULL); +} + +PUBLIC void polctl_monitor (afb_req request) { + + // subscribe Client to event + int err = afb_req_subscribe(request, afbevt); + if (err != 0) { + afb_req_fail_f(request, "register-event", "Fail to subscribe binder event"); + goto OnErrorExit; + } + + afb_req_success(request, NULL, NULL); + + OnErrorExit: + return; +} + +// Create Binding Event at Init +PUBLIC int polctl_init () { + AFB_DEBUG ("Audio Policy Control Binding Init"); + + // create binder event to send test pause/resume + afbevt = afb_daemon_make_event("request"); + if (!afb_event_is_valid(afbevt)) { + AFB_ERROR ("POLCTL_INIT: Cannot register polctl event"); + return (1); + } + + return 0; +} + diff --git a/conf.d/alsa/asoundrc.sample b/conf.d/alsa/asoundrc.sample index 2611478..1786c46 100644 --- a/conf.d/alsa/asoundrc.sample +++ b/conf.d/alsa/asoundrc.sample @@ -46,7 +46,7 @@ pcm.MyMixerPCM { # ------------------------------------------- pcm_hook_type.MyHookPlugin { install "AlsaInstallHook" - lib "/home/fulup/Workspace/AGL-AppFW/audio-bindings-dev/build/Alsa-Plugin/Alsa-Hook-Callback/alsa_hook_cb.so" + lib "/home/fulup/Workspace/AGL-AppFW/audio-bindings-dev/build/Alsa-Plugin/Alsa-Policy-Hook/policy_hook_cb.so" } # Define a HookedPCM that point to Hook_type sharelib @@ -59,19 +59,37 @@ pcm.MyNavigationHook { hooks.0 { type "MyHookPlugin" hook_args { + verbose true # print few log messages (default false); - # Every Call should return OK in order PCM to open + # Every Call should return OK in order PCM to open (default timeout 100ms) uri "ws://localhost:1234/api?token='audio-agent-token'" request { - CallPing { - api "alsacore" - verb "ping" + # Request autorisation to write on navigation + RequestNavigation { + api "polctl" + verb "navigation" + } + # subscribe to Audio Agent Event + SubscriveEvents { + api "polctl" + verb "monitor" + } + TestAutoStop { + api "polctl" + verb "event_test" + query "{'label':'stop', 'delay':10000}" + } + TestAutoStart { + api "polctl" + verb "event_test" + query "{'label':'stop', 'delay':20000}" + } + # start a test pause/resume not supported by every hardware + TestPauseResume { + api "polctl" + verb "event_test" + query "{'label':'pause', 'delay':3000, 'count':10}" } - CallUCM { - api "alsacore" - verb "ping" - query "{'devid':'hw:v1340','verb':'Navigation','dev':'speakers'}" - } } } } diff --git a/nbproject/configurations.xml b/nbproject/configurations.xml index 186abf5..e955bcb 100644 --- a/nbproject/configurations.xml +++ b/nbproject/configurations.xml @@ -18,7 +18,7 @@ AlsaHookPlug.c - AlsaHookCb.c + PolicyHookCb.c @@ -83,6 +83,9 @@ Mediator.cpp libmostvolume.cpp + + polctl-binding.c + audio-interface.c @@ -109,9 +112,10 @@ - - - + + + @@ -123,7 +127,7 @@ ${MAKE} -f Makefile install ${MAKE} -f Makefile clean build/CMakeFiles/feature_tests.bin - + @@ -133,61 +137,30 @@ - - - ../../../opt/include/alsa - /usr/include/json-c - Shared-Interface - ../../../opt/include - build/ALSA-afb - + - - - build/ALSA-afb - + - - - ../../../opt/include/alsa - /usr/include/json-c - Shared-Interface - ../../../opt/include - build/ALSA-afb - + - - - ../../../opt/include/alsa - /usr/include/json-c - Shared-Interface - ../../../opt/include - build/ALSA-afb - + - - - ../../../opt/include/alsa - /usr/include/json-c - Shared-Interface - ../../../opt/include - build/ALSA-afb - + - - + @@ -198,56 +171,44 @@ ex="false" tool="0" flavor2="3"> - - - Shared-Interface - ../../../opt/include - build/HAL-afb/HAL-interface - + - - - Shared-Interface - build/HAL-afb/HAL-interface - + - - - build/HAL-afb/HAL-interface - + - + - + - + - + - + Shared-Interface HAL-afb/HAL-interface @@ -257,7 +218,7 @@ - + HAL-afb/HAL-interface build/HAL-afb/Unicens-USB @@ -265,7 +226,7 @@ - + Shared-Interface ../../../opt/include @@ -274,7 +235,7 @@ - + /usr/include/json-c Shared-Interface @@ -317,36 +278,53 @@ + + + + - + - ../../../opt/include/afb - ALSA-afb + ../../../opt/include + ../../../opt/include/alsa + /usr/include/p11-kit-1 + /usr/include/json-c + Shared-Interface + build/ALSA-afb + + CONTROL_CDEV_RX="/dev/inic-usb-crx" + CONTROL_CDEV_TX="/dev/inic-usb-ctx" + MAX_LINEAR_DB_SCALE=24 + MAX_SND_CARD=16 + NATIVE_LINUX + TLV_BYTE_SIZE=256 + alsa_lowlevel_EXPORTS + - ../../../opt/include/afb - Alsa-Plugin/Alsa-Hook-Callback + ../../../opt/include ../../../opt/include/alsa + /usr/include/p11-kit-1 /usr/include/json-c - ../../../opt/include - build/Alsa-Plugin/Alsa-Hook-Callback + build/Alsa-Plugin/Alsa-Policy-Hook CONTROL_CDEV_RX="/dev/inic-usb-crx" CONTROL_CDEV_TX="/dev/inic-usb-ctx" MAX_LINEAR_DB_SCALE=24 MAX_SND_CARD=16 + NATIVE_LINUX PIC TLV_BYTE_SIZE=256 - alsa_hook_cb_EXPORTS + policy_hook_cb_EXPORTS @@ -382,10 +360,19 @@ - HAL-afb/HAL-interface + ../../../opt/include ../../../opt/include/alsa + /usr/include/p11-kit-1 /usr/include/json-c + HAL-afb/HAL-interface + Shared-Interface + build/HAL-afb/HAL-interface + + MAX_LINEAR_DB_SCALE=24 + NATIVE_LINUX + TLV_BYTE_SIZE=256 + @@ -399,40 +386,58 @@ - HAL-afb/HDA-intel + ../../../opt/include ../../../opt/include/alsa + /usr/include/p11-kit-1 /usr/include/json-c - Shared-Interface HAL-afb/HAL-interface - ../../../opt/include + Shared-Interface build/HAL-afb/HDA-intel + + MAX_LINEAR_DB_SCALE=24 + NATIVE_LINUX + TLV_BYTE_SIZE=256 + hal_intel_hda_EXPORTS + - HAL-afb/Jabra-Solemate + ../../../opt/include ../../../opt/include/alsa + /usr/include/p11-kit-1 /usr/include/json-c - Shared-Interface HAL-afb/HAL-interface - ../../../opt/include + Shared-Interface build/HAL-afb/Jabra-Solemate + + MAX_LINEAR_DB_SCALE=24 + NATIVE_LINUX + TLV_BYTE_SIZE=256 + hal_jabra_usb_EXPORTS + - HAL-afb/Scarlett-Focusrite + ../../../opt/include ../../../opt/include/alsa + /usr/include/p11-kit-1 /usr/include/json-c - Shared-Interface HAL-afb/HAL-interface - ../../../opt/include + Shared-Interface build/HAL-afb/Scarlett-Focusrite + + MAX_LINEAR_DB_SCALE=24 + NATIVE_LINUX + TLV_BYTE_SIZE=256 + hal_scalett_usb_EXPORTS + @@ -459,14 +464,45 @@ - + - ../../../opt/include/afb + ../../../opt/include + ../../../opt/include/alsa + /usr/include/p11-kit-1 + /usr/include/json-c Shared-Interface + build/PolicyCtl-afb + + + CONTROL_CDEV_RX="/dev/inic-usb-crx" + CONTROL_CDEV_TX="/dev/inic-usb-ctx" + MAX_LINEAR_DB_SCALE=24 + MAX_SND_CARD=16 + NATIVE_LINUX + TLV_BYTE_SIZE=256 + polctl_afb_EXPORTS + + + + + + + ../../../opt/include + ../../../opt/include/alsa + /usr/include/p11-kit-1 /usr/include/json-c + Shared-Interface build/Shared-Interface + + CONTROL_CDEV_RX="/dev/inic-usb-crx" + CONTROL_CDEV_TX="/dev/inic-usb-ctx" + MAX_LINEAR_DB_SCALE=24 + MAX_SND_CARD=16 + NATIVE_LINUX + TLV_BYTE_SIZE=256 + @@ -552,7 +588,7 @@ - @@ -831,7 +867,7 @@ - + default false @@ -908,7 +944,7 @@ - @@ -1038,6 +1074,10 @@ + + + + @@ -1078,9 +1118,10 @@ CONTROL_CDEV_TX="/dev/inic-usb-ctx" MAX_LINEAR_DB_SCALE=24 MAX_SND_CARD=16 + NATIVE_LINUX PIC TLV_BYTE_SIZE=256 - alsa_hook_cb_EXPORTS + policy_hook_cb_EXPORTS @@ -1146,6 +1187,27 @@ + + + + ../../../opt/include + ../../../opt/include/alsa + /usr/include/p11-kit-1 + /usr/include/json-c + Shared-Interface + build/PolicyCtl-afb + + + CONTROL_CDEV_RX="/dev/inic-usb-crx" + CONTROL_CDEV_TX="/dev/inic-usb-ctx" + MAX_LINEAR_DB_SCALE=24 + MAX_SND_CARD=16 + NATIVE_LINUX + TLV_BYTE_SIZE=256 + polctl_afb_EXPORTS + + + diff --git a/nbproject/project.xml b/nbproject/project.xml index 859334c..988f845 100644 --- a/nbproject/project.xml +++ b/nbproject/project.xml @@ -22,7 +22,7 @@ 0 - AplayHook + Aplay_Multimedia 0 -- cgit 1.2.3-korg