summaryrefslogtreecommitdiffstats
AgeCommit message (Expand)AuthorFilesLines
2021-04-26recipes-graphics/wayland/weston_8.0_aglcore: Remove unneeded patchMarius Vlad2-31/+0
2021-04-26recipes-graphics/wayland/agl-compositor: SRCREV bumpMarius Vlad1-1/+1
2021-03-31aglsetup: Override templateconf.cfg in case of -f, --force.Vasyl Vavrychuk1-0/+1
2021-03-22[RCAR] Fix sound on ulcb boardRonan Le Martret2-4/+1
2021-03-18Mask patch causing crash in luaJan-Simon Moeller1-0/+4
2021-03-15meta-agl-bsp: add pseudo abort workaround for rcar3 buildsScott Murray1-1/+31
2021-03-15meta-agl-core: remove rng-tools bbappendScott Murray4-110/+0
2021-03-15[RCAR] u-boot: move redundant-yyloc-global patch to u-boot-common.incRonan Le Martret2-0/+30
2021-03-15[RCAR] Update BSP Renesas RCAR gen3 to version 4.7.0Ronan Le Martret2-11/+6
2021-03-15Revert "meta-renesas: workaround recipe incompatibilities with YP 3.1.4"Ronan Le Martret5-189/+0
2021-03-15Revert "meta-renesas: update gstreamer version workaround"Ronan Le Martret3-6/+6
2021-03-09meta-agl-bsp: clean up Raspberry Pi Xen supportScott Murray7-54/+19
2021-03-01meta-agl-core: update poky-agl distro configurationScott Murray1-27/+12
2021-03-01meta-agl-core: update packagegroup-agl-core-bootScott Murray1-5/+2
2021-03-01meta-agl-core: fix connman-ncurses compilationScott Murray2-1/+55
2021-03-01meta-agl-core: remove libsoup bbappendScott Murray2-2/+0
2021-03-01meta-agl-core: update packagegroup-agl-core-connectivityScott Murray1-1/+0
2021-03-01meta-agl-core: fix S definition in waltham-transmitter-pluginScott Murray1-1/+1
2021-02-16meta-agl-bsp: Fix agl-refhw-h3 BBMASK definitionScott Murray1-1/+1
2021-02-16meta-renesas: update gstreamer version workaroundScott Murray3-6/+6
2021-02-05agl-compositor: Bump SRCREVMarius Vlad1-1/+1
2021-02-05meta-agl-bsp: Add reference hardware GPS supportScott Murray5-0/+113
2021-02-05meta-agl-core: Update weston-ini-conf landscape supportScott Murray3-2/+30
2021-02-05RBAModel: Added unknown_app content_idAnusha Gugale1-0/+20
2021-02-04meta-agl-core: fix entropy gathering on rng-tools 6.9Julien Massot4-0/+110
2021-02-04Post Milestone 3 change - open master for Lucky LampreyJan-Simon Möller1-4/+4
2021-02-02glmark2: Fix missing wayland-protocols dependency.Vasyl Vavrychuk1-1/+1
2021-02-02glmark2: Fix bbappend file name.Vasyl Vavrychuk1-0/+0
2021-01-29Prepare Kooky Koi Milestone 3koi_10.93.0koi/10.93.010.93.0Jan-Simon Möller1-3/+3
2021-01-26Allow -nogfx boards to start the homescreenJan-Simon Moeller3-0/+12
2021-01-26qemu[arm,arm64]: enable runqemu in graphic modeJan-Simon Moeller2-16/+19
2021-01-26change SRCREV of librbaAnusha Gugale1-1/+1
2021-01-26raspberrypi: Upgrade to u-boot v2020.10Paul Barker4-0/+11
2021-01-22agl-compositor_git: Enable loading waltham-transmitter-pluginMarius Vlad1-1/+3
2021-01-22waltham-transmitter-plugin: Add waltham-transmitter plug-in recipeMarius Vlad2-34/+17
2021-01-22wayland/weston-ini-conf: Add transmitter-output ini sectionMarius Vlad3-0/+7
2021-01-22agl-weston-waltham-remoting: Add waltham-remoting AGL_FEATURESMarius Vlad3-0/+11
2021-01-21Post Milestone 2 change to distro configJan-Simon Möller1-2/+2
2021-01-19raspberrypi: agl_raspberrypi4.inc: Unpin kernel versionPaul Barker1-3/+0
2021-01-16Prepare KK Milestone 2koi_10.92.0koi/10.92.010.92.0Jan-Simon Moeller1-3/+3
2021-01-16meta-agl-bsp, templates: Add virtio-aarch64 machineVasyl Vavrychuk12-0/+161
2021-01-14meta-agl: move open-vm-tools and vboxguestdrivers to meta-agl-demoJan-Simon Möller1-2/+0
2021-01-13agl-compositor: include runtime dependencies in PACKAGECONFIG for policy-rbaJan-Simon Moeller1-1/+1
2021-01-13Update aglsetup.sh feature/image helpScott Murray1-19/+9
2021-01-13meta-agl-core: remove connman cluster demo supportScott Murray1-7/+2
2021-01-12agl-compositor: Bump SRCREV for agl-compositorMarius Vlad1-1/+1
2021-01-12agl-compositor: added option to build rba policyAnusha Gugale1-0/+2
2021-01-12meta-agl-core: add recipe for librba and rba-configAnusha Gugale3-0/+339
2021-01-12linux-raspberrypi: Tidy patches & config fragmentsPaul Barker5-3/+0
2021-01-12Improve workaround for do_image_wic race conditionPaul Barker2-3/+33
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 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584
/*
 * Copyright (c) 2017 TOYOTA MOTOR CORPORATION
 *
 * 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
#define AFB_BINDING_VERSION 2
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <json-c/json.h>
#include <glib.h>
#include <pthread.h>
#include <afb/afb-binding.h>
#include "sm-error.h"
#include "sm-helper.h"
#include "dbus/audio_manager_interface.h"

#define AM_NAME "org.genivi.audiomanager"
#define AM_CMD_PATH     "/org/genivi/audiomanager/commandinterface"
#define AM_ROUTE_PATH   "/org/genivi/audiomanager/routinginterface"
#define AM_ROUTE_NAME   "org.genivi.audiomanager.routinginterface"
#define SOUND_MANAGER_RETURN_INTERFACE   "org.genivi.audiomanager.routing.soundmanager"
#define SOUND_MANAGER_BUS_NAME "org.genivi.audiomanager.routing.soundmanager"
#define SOUND_MANAGER_PATH "/org/genivi/audiomanager/routing/soundmanager"

#define COMMAND_EVENT_NUM 10
#define ROUTING_EVENT_NUM 10
#define DEFAULT_SINK 1
#define DEFAULT_SOURCE_CLASS_ID 100
#define DYNAMIC_DOMAIN_ID 100
#define DEFAULT_DOMAIN_ID 0
#define DYNAMIC_SOURCE_ID 0
#define DEFAULT_VOLUME 100
#define DEFAULT_AVAILABLES 1
#define DEFAULT_CONNECTION_FORMAT 2
#define DEFAULT_INTERRUPT 0
#define DEFAULT_SOURCE_STATE 2
#define DS_CONTROLLED 1

#define EVENT_SUBSCRIBE_ERROR_CODE 100

const static struct afb_binding_interface *afbitf;
static AudiomanagerCommandinterface *am_cmd_bus;
static AudiomanagerRoutinginterface *am_route_bus;
static AudiomanagerRoutingSoundmanager *sm_adapter;
static AudiomanagerRoutingSoundmanagerIface* sm_itf;
static GDBusConnection* system_conn = NULL;

static GMainLoop *loop = NULL;
static guint16 SOUNDMANAGER_DOMAIN_ID;
/* To Do hash table is better */
struct event{
    char* name;
    struct afb_event* event;
    };
static struct event command_event_list[COMMAND_EVENT_NUM];
static struct event routing_event_list[ROUTING_EVENT_NUM];

static struct afb_event ev_new_connection;
static struct afb_event ev_removed_main_connection;
static struct afb_event ev_volume_changed;
static struct afb_event ev_sink_mute_state_changed;
static struct afb_event ev_main_connection_state_changed;

/* Routing interface event */
static struct afb_event ev_set_routing_ready;
static struct afb_event ev_set_routing_rundown;
static struct afb_event ev_async_connect;
static struct afb_event ev_async_disconnect;
static struct afb_event ev_async_set_source_state;

#define _SOURCE_ID "sourceID"
#define _SINK_ID "sinkID"
#define _SINK_NAME "sinkName"
#define _MAIN_CONNECTION_ID "mainConnectionID"
#define _DELAY "delay"
#define _CONNECTION_STATE "connectionState"
#define _CONNECTION_ID "connectionID"
#define _VOLUME "volume"
#define _VOLUME_STEP "volumeStep"
#define _INTERRUPT "interrupt"
#define _MUTE_STATE "muteState"

#define _DOMAIN_ID "domainID"
#define _HANDLE "handle"
#define _APPNAME "appname"
#define _RAMP "ramp"
#define _TIME "time"
#define _SOURCE_STATE "sourceState"
#define _SOURCE_CLASS_ID "sourceClassID"
#define _SINK_CLASS_ID "sinkClassID"
#define _ERROR "error"
#define _SINK_DATA "sinkData"
#define _SOURCE_DATA "sourceData"
#define _INTERRUPT_STATE "interruptState"
#define _AVAILABILITY "availability"
#define _AVAILABILITY_REASON "availabilityReason"
#define _LIST_VOLUMES "listVolumes"
#define _PAYLOAD "payload"
#define _CONNECTION_FORMAT "connectionFormat"
/*
********** Method of Sound Manager (API) **********
*/

/**
 * Call "connect" function of Audio Manager.
 * Getting resource right to output audio stream.
 * Please input following keys with value into json string object in argument.
 * In case of using libsoundmanager,
 * json_object *jobj = json_object_new_object();
 * json_object_object_add(jobj, "sourceID", json_object_new_int(100));
 * json_object_object_add(jobj, "sinkID", json_object_new_int(100));
 * call("connect", jobj);
 *
 * The order of arguments is not important.
 *
 * #### Parameters
 * Request key
 * - sourceID   : Source ID getting in return value in registerSource or appname.
 * - sinkID     : Sink ID. This should be more than 0. If no request, defalut value is set by sound manager
 *
 * This will be changed in near future because these arguments should be aliased like
 * sinkID:100 -> sinkID:"speaker"
 *
 * This will be modified after integrating
 *
 * #### Rreturn
 * - error      : Error status number. If error is 0, it means the request is accepted, otherwise error message is attached with error code in reply message.
 *
 * #### Note
 * sourceID and sinkID should be more than 0
 *
 */
static void connect (struct afb_req request)
{
    AFB_DEBUG("call %s", __FUNCTION__);
    guint16 source_id = 0, sink_id = 0;
    guint16 main_connectionID = 0;
    gint16 ret = -1;
    REQ_ERROR req_err1 = REQ_FAIL;
    REQ_ERROR req_err2 = REQ_FAIL;
    GError *err = NULL;

    req_err1 = get_value_uint16(request, _SOURCE_ID, &source_id);
    /* ToDo: Hardware abstraction for application user is needed.
    select appname(speaker) or sourceID(sinkID). If appname is desired, it changes to sourceID(sinkID) */

    const char* default_sink = afb_req_value (request, _SINK_ID);
    if(default_sink != NULL){
        if((strlen("default") == strlen(default_sink)) &&
           (0 == strncmp("default", default_sink, strlen("default")))){
            sink_id = DEFAULT_SINK;
            req_err2 = REQ_OK;
        }
        else{
            req_err2 = get_value_uint16(request, _SINK_ID, &sink_id);
        }
    }

    if((req_err1 != REQ_OK) || (req_err2 != REQ_OK))
    {
        AFB_INFO("get_value_uint16 source ret = %d,sink ret = %d", source_id, sink_id);
        AFB_NOTICE("wrong request");
        afb_req_fail(request,"wrong-request",NULL);
        return;
    }

    audiomanager_commandinterface_call_connect_sync(
        am_cmd_bus,
        source_id,
        sink_id,
        &ret,
        &main_connectionID,
        NULL, &err);

    if(err != NULL)
    {
        afb_req_fail_f(request, "failed", "Unable to call %s", __FUNCTION__);
        return;
    }

    /* ToDo Remember appname(key) and tie to sourceID(value) */

    /*create response json object*/
    struct json_object *res = json_object_new_object();
    sm_add_object_to_json_object_func(res, __FUNCTION__, 4,
        "error", ret,
        _MAIN_CONNECTION_ID, main_connectionID);
    char *info = get_response_audiomanager_massage_error(ret);
    afb_req_success(request, res, info);
}

/**
 * Call "disconnect" function of Audio Manager.
 * Release resource right to output audio stream.
 *
 * #### Parameters
 * Request key
 * - sourceID   : Source ID getting in return value in registerSource or appname.
 *
 *
 * #### Rreturn
 * - error      : Error status number. If error is 0, it means the request is accepted, otherwise error message is attached with error code in reply message.
 *
 * #### Note
 * sourceID should be more than 0
 *
 */
static void disconnect (struct afb_req request)
{
    AFB_DEBUG("call %s", __FUNCTION__);

    guint16 id;
    gint16 ret;
    REQ_ERROR req_err;
    GError *err = NULL;

    req_err = get_value_uint16(request, _MAIN_CONNECTION_ID, &id);
    AFB_DEBUG( "requested %s = %d", _MAIN_CONNECTION_ID, id);

    if(req_err != REQ_OK)
    {
        afb_req_fail(request,"wrong-request",afb_req_value (request, _MAIN_CONNECTION_ID));
        return;
    }
    audiomanager_commandinterface_call_disconnect_sync(
        am_cmd_bus,
        id,
        &ret,
        NULL, &err);
    AFB_DEBUG( "ret = %d", ret);

    if(err != NULL)
    {
        afb_req_fail_f(request, "failed", "Unable to call %s", __FUNCTION__);
        return;
    }

    struct json_object* res_obj = json_object_new_object();
    sm_add_object_to_json_object_func(res_obj, __FUNCTION__, 2,
        _ERROR, ret);
    char *info = get_response_audiomanager_massage_error(ret);

    afb_req_success(request, res_obj, info); /* return error num as status */
}

/**
 * Call "setVolume" function of Audio Manager.
 * Set sink volume.
 *
 * #### Parameters
 * Request key
 * - volume   : volume value. The range of value should be [0-100]
 * - sinkID   : sinkID you would like to change volume at
 *
 * #### Rreturn
 * - error      : Error status number. If error is 0, it means the request is accepted, otherwise error message is attached with error code in reply message.
 *
 * #### Note
 *
 */
static void setVolume (struct afb_req request)
{
    AFB_DEBUG("call %s", __FUNCTION__);

    guint16 sink_id, vol;
    gint16 ret;
    REQ_ERROR req_err1, req_err2;
    GError *err = NULL;

    req_err1 = get_value_uint16(request, _SINK_ID, &sink_id);
    req_err2 = get_value_int16(request, _VOLUME, &vol);
    AFB_DEBUG( "requested %s = %d, %s = %d",_SINK_ID, sink_id, _VOLUME, vol);
    if((req_err1 != REQ_OK) || (req_err2 != REQ_OK))
    {
        afb_req_fail(request,"wrong-request", NULL);
        return;
    }

    audiomanager_commandinterface_call_set_volume_sync(
        am_cmd_bus,
        sink_id,
        vol,
        &ret,
        NULL, &err);
    AFB_DEBUG( "ret = %d", ret);

    if(err != NULL)
    {
        afb_req_fail_f(request, "failed", "Unable to call %s", __FUNCTION__);
        return;
    }

    struct json_object* res_obj = json_object_new_object();
    sm_add_object_to_json_object_func(res_obj, __FUNCTION__, 2,
        "error", ret);
    char *info = get_response_audiomanager_massage_error(ret);

    afb_req_success(request, res_obj, info); /* return error num as status */
}

/**
 * Call "volumeStep" function of Audio Manager.
 * Change volume step of sink
 *
 * #### Parameters
 * Request key
 * - sinkID     : sinkID you would to change volume step
 * - volumeStep : Step size of volume
 *
 *
 * #### Rreturn
 * - error      : Error status number. If error is 0, it means the request is accepted, otherwise error message is attached with error code in reply message.
 *
 * #### Note
 *
 */
static void volumeStep (struct afb_req request)
{
    AFB_DEBUG("call %s", __FUNCTION__);

    guint16 sink_id, vol;
    gint16 ret;
    REQ_ERROR req_err1, req_err2;
    GError *err = NULL;

    req_err1 = get_value_uint16(request, _SINK_ID, &sink_id);
    req_err2 = get_value_int16(request, _VOLUME_STEP, &vol);
    AFB_DEBUG( "requested %s = %d, %s = %d",_SINK_ID, sink_id, _VOLUME_STEP, vol);
    if((req_err1 != REQ_OK) || (req_err2 != REQ_OK))
    {
        afb_req_fail(request,"wrong-request", NULL);
        return;
    }

    audiomanager_commandinterface_call_volume_step_sync(
        am_cmd_bus,
        sink_id,
        vol,
        &ret,
        NULL, &err);
    AFB_DEBUG( "ret = %d", ret);

    if(err != NULL)
    {
        afb_req_fail_f(request, "failed", "Unable to call %s", __FUNCTION__);
        return;
    }

    struct json_object* res_obj = json_object_new_object();
    sm_add_object_to_json_object_func(res_obj, __FUNCTION__, 2,
        "error", ret);
    char *info = get_response_audiomanager_massage_error(ret);

    afb_req_success(request, res_obj, info); /* return error num as status */
}

/**
 * Call "volumeStep" function of Audio Manager.
 * Change volume step of sink
 *
 * #### Parameters
 * Request key
 * - sinkID     : sinkID you would like to change mute state
 * - muteState  : muteState, 1 means mute, 2 means unmute. Or you can designate as "mute" or "unmute"
 *
 *
 * #### Rreturn
 * - error      : Error status number. If error is 0, it means the request is accepted, otherwise error message is attached with error code in reply message.
 *
 * #### Note
 *
 */
static void setSinkMuteState(struct afb_req request)
{
    AFB_DEBUG("call %s", __FUNCTION__);

    guint16 sink_id, mute;
    gint16 ret;
    REQ_ERROR req_err1, req_err2;
    GError *err = NULL;

    req_err1 = get_value_uint16(request, _SINK_ID, &sink_id);
    req_err2 = get_value_int16(request, _MUTE_STATE, &mute);
    AFB_DEBUG( "requested %s = %d, %s = %d",_SINK_ID, sink_id, _MUTE_STATE, mute);
    if((req_err1 != REQ_OK) || (req_err2 != REQ_OK))
    {
        afb_req_fail(request,"wrong-request", NULL);
        return;
    }

    audiomanager_commandinterface_call_set_sink_mute_state_sync(
        am_cmd_bus,
        sink_id,
        mute,
        &ret,
        NULL, &err);
    AFB_DEBUG( "ret = %d", ret);

    if(err != NULL)
    {
        afb_req_fail_f(request, "failed", "Unable to call %s", __FUNCTION__);
        return;
    }

    struct json_object* res_obj = json_object_new_object();
    sm_add_object_to_json_object_func(res_obj, __FUNCTION__, 2,
        "error", ret);
    char *info = get_response_audiomanager_massage_error(ret);

    afb_req_success(request, res_obj, info); /* return error num as status */
}

/**
 * Call "getListMainConnections" function of Audio Manager.
 * Get mainc connection list
 *
 * #### Parameters
 * Request key
 * None
 *
 *
 * #### Rreturn
 * - error      : Error status number. If error is 0, it means the request is accepted, otherwise error message is attached with error code in reply message. Even if there is no connection list,
 *   Sound Manager return success.
 *
 * #### Note
 *
 */
static void getListMainConnections(struct afb_req request)
{
    AFB_DEBUG("call getListMainConnections");
    guint16 ret;
    GVariant* mainConnectionList;
    GError *err = NULL;

    audiomanager_commandinterface_call_get_list_main_connections_sync(
        am_cmd_bus,
        &ret,
        &mainConnectionList,
        NULL,
        &err
    );

    if(err != NULL)
    {
        afb_req_fail_f(request, "failed", "Unable to call %s", __FUNCTION__);
        return;
    }

    /* create response */
    struct json_object *array_res = json_object_new_array();
    gsize size = g_variant_n_children(mainConnectionList);
    AFB_DEBUG("mainConnectionList size is %u",(uint16_t)size);
    struct json_object *verb_obj = json_object_new_object();
    sm_add_object_to_json_object_func(verb_obj, __FUNCTION__, 0);
    json_object_array_add(array_res, verb_obj);
    if(size <= 0)
    {
        AFB_NOTICE( "mainConnectionList size is 0");
    }
    else{
        for(int i = 0; i < size; ++i)
        {
            guint16 mcid, srcid, sinkid;
            gint16 delay, constate;
            g_variant_get_child(
                mainConnectionList,i,"(qqqnn)",
                &mcid, &srcid, &sinkid, &delay, &constate
                );

            struct json_object* res_obj = json_object_new_object();
            sm_add_object_to_json_object(res_obj,10,
                _MAIN_CONNECTION_ID, mcid,
                _SOURCE_ID, srcid,
                _SINK_ID, sinkid,
                _DELAY, delay,
                _CONNECTION_STATE, constate
            );
            json_object_array_add(array_res,res_obj);
        }
    }
    AFB_DEBUG("json object :%s:",json_object_to_json_string(array_res));
    afb_req_success(request, array_res, "Success to get main connection list");
}

/**
 * Call "getListMainSinks" function of Audio Manager.
 * Get main sink list
 *
 * #### Parameters
 * Request key
 * None
 *
 *
 * #### Rreturn
 * - error      : Error status number. If error is 0, it means the request is accepted, otherwise error message is attached with error code in reply message. Even if there is no connection list,
 *   Sound Manager return success.
 *
 * #### Note
 *
 */
static void getListMainSinks(struct afb_req request)
{
    AFB_DEBUG("call %s", __FUNCTION__);
    guint16 ret;
    GVariant* mainSinkList;
    GError *err = NULL;

    audiomanager_commandinterface_call_get_list_main_sinks_sync(
        am_cmd_bus,
        &ret,
        &mainSinkList,
        NULL,
        &err
    );

    if(err != NULL)
    {
        afb_req_fail_f(request, "failed", "Unable to call %s", __FUNCTION__);
        return;
    }

    /* create response */
    struct json_object *response = json_object_new_object();
    gsize size = g_variant_n_children(mainSinkList);
    AFB_DEBUG( "%s size is %u",__FUNCTION__, (uint16_t)size);
    sm_add_object_to_json_object_func(response, __FUNCTION__, 0);
    if(size <= 0)
    {
        AFB_NOTICE("%s size is 0", __FUNCTION__);
    }
    else{
        struct json_object *array_res = json_object_new_array();
        for(int i = 0; i < size; ++i)
        {
            guint16 sinkid, sinkclassid;
            gchar* sinkname;

            gint16 av;
            gint16 avr;
            gint16 volume, mutestate;
            GVariant* child = g_variant_get_child_value(mainSinkList, i);
            g_variant_get(
                child,"(qs(nn)nnq)",
                &sinkid, &sinkname, &av, &avr, &volume, &mutestate, &sinkclassid);
            AFB_DEBUG( "sinkID: %d, sinkName: %s, availability: %d, available_reason: %d, volume: %d, muteState: %d, sinkClassID: %d",
                sinkid, sinkname, av, avr, volume, mutestate, sinkclassid);

            struct json_object* res_obj = json_object_new_object();
            sm_add_object_to_json_object(res_obj,2,_SINK_ID, sinkid);
            json_object_object_add(res_obj, _SINK_NAME, json_object_new_string(sinkname));
            sm_add_object_to_json_object(res_obj,10,
                _AVAILABILITY, av,
                _AVAILABILITY_REASON, avr,
                _VOLUME, volume,
                _MUTE_STATE, mutestate,
                _SINK_CLASS_ID, sinkclassid);
            json_object_array_add(array_res,res_obj);
            g_variant_unref(child);
        }
        json_object_object_add(response, "sinks", array_res);
    }
    afb_req_success(request, response, "Success to get main sink list");
    g_variant_unref(mainSinkList);
}

/*
*
****** Routing Interface method(API) ***********
*
*/

/**
 * Call "ackConnect" function of Audio Manager.
 * Return acknowledge of connect against asyncConnect
 *
 * #### Parameters
 *  - handle  : Handle id when you get on asyncConnect
 *  - connectionID : connection id when you got on connect return value
 *  - error   : Error Number you would like to send. If error is 0, it means OK.
 *              If an application has some error, send error number in function then AM release
 *              resources the application got in connect.
 *
 *
 * #### Rreturn
 * - error      : Error status number. If error is 0, it means the request is accepted, otherwise error message is attached with error code in reply message. Even if there is no connection list,
 *   Sound Manager return success. So you should check the contents size of return json object
 *
 * #### Note
 *
 */
static void ackConnect(struct afb_req request)
{
    /* This function will be deprecated */
    AFB_DEBUG("call %s", __FUNCTION__);
    guint16 handle, connection_id, error;
    guint16 ret = 0;
    REQ_ERROR req_err1, req_err2 , req_err3;
    GError *err = NULL;

    req_err1 = get_value_uint16(request, _HANDLE, &handle);
    req_err2 = get_value_uint16(request, _CONNECTION_ID, &connection_id);
    req_err3 = get_value_uint16(request, _ERROR, &error);

    if((req_err1 != REQ_OK) || (req_err2 != REQ_OK) || (req_err3 != REQ_OK))
    {
        afb_req_fail(request,"wrong-request", NULL);
        return;
    }
    if(connection_id == 0)
    {
        afb_req_fail(request,"wrong-request", "connectionID is more than 0");
        return;
    }

    audiomanager_routinginterface_call_ack_connect_sync(
        am_route_bus,
        handle,
        connection_id,
        error,
        NULL, &err);

    if(err != NULL)
    {
        afb_req_fail_f(request, "failed", "Unable to call %s", __FUNCTION__);
        return;
    }
    /*create response json object*/
    struct json_object *res = json_object_new_object();
    sm_add_object_to_json_object_func(res, __FUNCTION__, 2,
        _ERROR, ret);
    char *info = get_response_audiomanager_massage_error(ret);
    afb_req_success(request, res, info);
}

/**
 * Call "ackDisconnect" function of Audio Manager.
 * Return acknowledge of disconnect against asyncDisconnect
 *
 * #### Parameters
 *  - handle  : Handle id when you get on asyncDisconnect
 *  - connectionID : connection id when you got on connect return value
 *  - error   : Error Number you would like to send. If error is 0, it means OK.
 *              If an application has some error, send error number in function then AM
 *
 *
 * #### Rreturn
 * - error      : Error status number. If error is 0, it means the request is accepted, otherwise error message is attached with error code in reply message. Even if there is no connection list,
 *   Sound Manager return success. So you should check the contents size of return json object
 *
 * #### Note
 *
 */
static void ackDisconnect(struct afb_req request)
{
    /* This function will be deprecated */
    AFB_DEBUG("call %s", __FUNCTION__);
    guint16 handle, connection_id, error;
    guint16 ret = 0;
    REQ_ERROR req_err1, req_err2 , req_err3;
    GError *err = NULL;

    req_err1 = get_value_uint16(request, _HANDLE, &handle);
    req_err2 = get_value_uint16(request, _CONNECTION_ID, &connection_id);
    req_err3 = get_value_uint16(request, _ERROR, &error);

    if((req_err1 != REQ_OK) || (req_err2 != REQ_OK) || (req_err3 != REQ_OK))
    {
        afb_req_fail(request,"wrong-request", "connectionID is more than 0");
        return;
    }
    if(connection_id == 0)
    {
        afb_req_fail(request,"wrong-request", "connectionID is more than 0");
        return;
    }

    audiomanager_routinginterface_call_ack_disconnect_sync(
        am_route_bus,
        handle,
        connection_id,
        error,
        NULL, &err);

    if(err != NULL)
    {
        afb_req_fail_f(request, "failed", "Unable to call %s", __FUNCTION__);
        return;
    }
    /*create response json object*/
    struct json_object *res = json_object_new_object();
    sm_add_object_to_json_object_func(res, __FUNCTION__, 2,
        _ERROR, ret);
    char *info = get_response_audiomanager_massage_error(ret);
    afb_req_success(request, res, info);
}

/**
 * Call "ackSetSourceState" function of Audio Manager.
 * Return acknowledge of setSourceState against asyncSetSourceState.
 *
 * #### Parameters
 *  - handle  : Handle id when you get on asyncSetSourceState
 *  - error   : Error Number you would like to send. If error is 0, it means OK.
 *              If an application has some errors, send error number in function
 *
 * #### Rreturn
 * - error      : Error status number. If error is 0, it means the request is accepted, otherwise error message is attached with error code in reply message.
 *
 * #### Note
 * This function is very important for applications to realise the sequence of Audio Management.
 * An Application which matches with sourceID in the parameter of asyncSetSourceState has to return ack to use this function
 *
 */
static void ackSetSourceState(struct afb_req request)
{
    AFB_DEBUG("call %s", __FUNCTION__);
    guint16 handle, error;
    guint16 ret = 0;
    REQ_ERROR req_err1, req_err2;
    GError *err = NULL;

    req_err1 = get_value_uint16(request, _HANDLE, &handle);
    req_err2 = get_value_uint16(request, _ERROR, &error);

    if((req_err1 != REQ_OK) || (req_err2 != REQ_OK))
    {
        AFB_DEBUG("wrong request");
        afb_req_fail(request,"wrong-request", NULL);
        return;
    }

    audiomanager_routinginterface_call_ack_set_source_state_sync(
        am_route_bus,
        handle,
        error,
        NULL, &err);

    if(err != NULL)
    {
        afb_req_fail_f(request, "failed", "Unable to call %s", __FUNCTION__);
        return;
    }
    /*create response json object*/
    struct json_object *res = json_object_new_object();
    sm_add_object_to_json_object_func(res, __FUNCTION__, 2,
        _ERROR, ret);
    char *info = get_response_audiomanager_massage_error(ret);
    afb_req_success(request, res, info);
}

/**
 * Call "registerSource" function of Audio Manager.
 * Register source(application) to Audio Manager Policy Management
 * Application must call this function on its initialization
 *
 * #### Parameters
 *  - appname  : Application unieque name
 * [Option]
 * It is not necessary to designate following argument, because these are default value is selected y soundmanager
 * If you would like to set value, please input the following key and value
 *   - sourceClassID :
 *   - sourceState   :
 *
 * #### Return
 * - error      : Error status number. If error is 0, it means the request is accepted, otherwise error message is attached with error code in reply message.
 *
 * #### Note
 *
 */
static void registerSource(struct afb_req request)
{
    AFB_DEBUG("call %s", __FUNCTION__);
    GError *err = NULL;


    guint16 source_id; /* q  0 is for dynamic id*/
    guint16 domain_id;  /* q */
    guint16 source_class_id;   /* q */
    gint32  source_state; /* i  */
    gint16  volume;  /* n */

    if(REQ_OK != get_value_uint16(request, _SOURCE_ID, &source_id)){
        source_id = DYNAMIC_SOURCE_ID;  /* if 0, dynamic source id will be applied */
    }
    REQ_ERROR req_err = get_value_uint16(request, _DOMAIN_ID, &domain_id);
    if( req_err != REQ_OK){
        if(req_err == REQ_FAIL)
        {
            domain_id = SOUNDMANAGER_DOMAIN_ID;    /* default in AGL */
        }
        else{
            afb_req_fail(request,"wrong-request", "Please input domainID as uint16, otherwise no value is OK");
            return;
        }
    }
    if(domain_id == 0)
    {
        afb_req_fail(request,"wrong-request", "domainID should be more than 0");
        return;
    }
    const gchar* name = afb_req_value(request, _APPNAME);  /* s */
    if(!name)
    {
        char* info = "Must specify the name. Please input json arg such as {\"appname\":\"radio\"}";
        afb_req_fail(request, NULL, info);
        return;
    }
    if(REQ_OK != get_value_uint16(request, _SOURCE_CLASS_ID, &source_class_id)){
        source_class_id = DEFAULT_SOURCE_CLASS_ID;    /* BASE */
    }
    if(REQ_OK != get_value_int32(request, _SOURCE_STATE, &source_state)){
        source_state = DEFAULT_SOURCE_STATE; /* SS_OFF */
    }
    if(REQ_OK != get_value_int16(request, _VOLUME, &volume)){
        volume = DEFAULT_VOLUME;
    }
    gboolean visible = TRUE;   /* b */
    struct availability_s available;     /* (ii) */
    available.availability = DEFAULT_AVAILABLES;         /* A_UNKNOWN */
    available.avalilable_reason = 0;    /* AR_UNKNOWN */

    guint16 interrupt;
    if(REQ_OK != get_value_int16(request, _INTERRUPT, &interrupt)){
        interrupt = DEFAULT_INTERRUPT;  /* q IS_OFF */
    }
    struct sound_property_s sound_property_list;   /* a(in) */
    sound_property_list.type = 0;
    sound_property_list.value = 0;     /* in reality, this is array of struct */

    gint32 connection_format_list = DEFAULT_CONNECTION_FORMAT; /* ai */
    struct  main_sound_property_s main_property_list;    /* a(in) */
    main_property_list.type = 0;
    main_property_list.value = 0;

    struct notification_config_s nconf_routing;
    struct notification_config_s nconf_command; /* a(iin)a(iin) */
    nconf_routing.type = 0;
    nconf_routing.status = 0;
    nconf_routing.parameter = 0;

    nconf_command.type = 0;
    nconf_command.status = 0;
    nconf_command.parameter = 0;

    /* acquire data */
    guint16 acquire_source_id;
    guint16 ret;

    GVariant* sourceData = create_source_data (source_id, domain_id, name, source_class_id,
        source_state, volume, visible, available, interrupt,
        sound_property_list, connection_format_list, main_property_list,
        nconf_routing, nconf_command);

    GVariant* input =  g_variant_ref_sink(sourceData);
    audiomanager_routinginterface_call_register_source_sync(
        am_route_bus,
        input,
        &acquire_source_id,
        &ret,
        NULL, &err);
    g_variant_unref(input);

    if(err != NULL)
    {
        afb_req_fail_f(request, "failed", "Unable to call %s", __FUNCTION__);
        return;
    }

    /*create response json object*/
    struct json_object *res = json_object_new_object();
    sm_add_object_to_json_object_func(res, __FUNCTION__, 4,
        _ERROR, ret,
        _SOURCE_ID, acquire_source_id);
    char *info = get_response_audiomanager_massage_error(ret);
    afb_req_success(request, res, info);
}

/**
 * Call "deregisterSource" function of Audio Manager.
 * Deregister source(application) to Audio Manager Policy Management
 *
 * #### Parameters
 *  - sourceID  : sourceID returned in resisterSource
 *
 * #### Rreturn
 * - error      : Error status number. If error is 0, it means the request is accepted, otherwise error message is attached with error code in reply message.
 *
 * #### Note
 *
 */
static void deregisterSource(struct afb_req request)
{
    guint16 source_id;
    guint16 ret;

    GError *err = NULL;

    if(REQ_OK != get_value_uint16(request, _SOURCE_ID, &source_id)){
        afb_req_fail(request, "wrong-request", NULL);
    }
    audiomanager_routinginterface_call_deregister_source_sync(
        am_route_bus,
        source_id,
        &ret,
        NULL, &err
    );
    if(err != NULL)
    {
        afb_req_fail_f(request, "failed", "Unable to call %s", __FUNCTION__);
        return;
    }
    /*create response json object*/
    struct json_object *res = json_object_new_object();
    sm_add_object_to_json_object_func(res, __FUNCTION__, 2,
        _ERROR, ret);
    char *info = get_response_audiomanager_massage_error(ret);
    afb_req_success(request, res, info);

}

/**
 * Subscribe event
 *
 * #### Parameters
 *  - event  : Event name. Event list is written in libsoundmanager.hpp
 *
 * #### Rreturn
 * - error      : Error status number. If error is 0, it means the request is accepted, otherwise error message is attached with error code in reply message.
 *
 * #### Note
 *
 */
static void subscribe(struct afb_req request)
{
    const char *value = afb_req_value(request, "event");
    AFB_DEBUG( "value is %s", value);
    int ret = 0;
    if(value) {
        int index = sm_search_event_name_index(value);
        if(index < 0)
        {
            index = sm_search_routing_event_name_index(value);
            if(index < 0)
            {
                AFB_NOTICE( "dedicated event doesn't exist");
                ret = EVENT_SUBSCRIBE_ERROR_CODE;
            }
            else
            {
                afb_req_subscribe(request, *routing_event_list[index].event);
            }
        }
        else
        {
            afb_req_subscribe(request, *command_event_list[index].event);
        }
    }
    else{
        AFB_NOTICE( "Please input event name");
        ret = EVENT_SUBSCRIBE_ERROR_CODE;
    }
    /*create response json object*/
    struct json_object *res = json_object_new_object();
    sm_add_object_to_json_object_func(res, __FUNCTION__, 2,
        _ERROR, ret);
    char *info = get_response_audiomanager_massage_error(ret);
    afb_req_success(request, res, info);
}

/**
 * Unsubscribe event
 *
 * #### Parameters
 *  - event  : Event name. Event list is written in libsoundmanager.hpp
 *
 * #### Rreturn
 * - error      : Error status number. If error is 0, it means the request is accepted, otherwise error message is attached with error code in reply message.
 *
 * #### Note
 *
 */
static void unsubscribe(struct afb_req request)
{
    const char *value = afb_req_value(request, "event");
    AFB_DEBUG( "value is %s", value);
    int ret = 0;
    if(value) {
        int index = sm_search_event_name_index(value);
        if(index < 0)
        {
            index = sm_search_routing_event_name_index(value);
            if(index < 0)
            {
                AFB_NOTICE( "dedicated event doesn't exist");
                ret = EVENT_SUBSCRIBE_ERROR_CODE;
            }
            else
            {
                afb_req_unsubscribe(request, *routing_event_list[index].event);
            }
        }
        else
        {
            afb_req_unsubscribe(request, *command_event_list[index].event);
        }
    }
    else{
        AFB_NOTICE( "Please input event name");
        ret = EVENT_SUBSCRIBE_ERROR_CODE;
    }
    /*create response json object*/
    struct json_object *res = json_object_new_object();
    sm_add_object_to_json_object_func(res, __FUNCTION__, 2,
        _ERROR, ret);
    char *info = get_response_audiomanager_massage_error(ret);
    afb_req_success(request, res, info);
}

/*
********** Callback Function invoked by Audio Manager **********
*/

static void on_new_main_connection(AudiomanagerCommandinterface* interface,
    GVariant* mainConnection)
{
    AFB_DEBUG("%s is called",__FUNCTION__);

    guint16 mcid, srcid, sinkid;
    gint16 delay, constate;
    g_variant_get(
        mainConnection,"(qqqnn)", &mcid, &srcid, &sinkid, &delay, &constate);

    struct json_object* res_obj = json_object_new_object();
    sm_add_object_to_json_object(res_obj,10,
        _MAIN_CONNECTION_ID, mcid,
        _SOURCE_ID, srcid,
        _SINK_ID, sinkid,
        _DELAY, delay,
        _CONNECTION_STATE, constate
        );
    AFB_DEBUG("json object :%s:",json_object_to_json_string(res_obj));

    afb_event_push(ev_new_connection, res_obj);
}

static void on_removed_main_connection(
    AudiomanagerCommandinterface* interface, guint16 mainConnectionID)
{
    AFB_DEBUG("%s is called",__FUNCTION__);

    struct json_object* res_obj = json_object_new_object();
    sm_add_object_to_json_object(res_obj, 2,
        _MAIN_CONNECTION_ID, mainConnectionID);
    afb_event_push(ev_removed_main_connection, res_obj);
}

static void on_main_connection_state_changed(
    AudiomanagerCommandinterface* interface, guint16 connectionID, gint16 connectionState)
{
    AFB_DEBUG("%s is called",__FUNCTION__);

    struct json_object* res_obj = json_object_new_object();
    sm_add_object_to_json_object(res_obj, 4,
        _CONNECTION_ID, connectionID,
        _CONNECTION_STATE, connectionState);
    afb_event_push(ev_main_connection_state_changed, res_obj);
}

static void on_volume_changed(
            AudiomanagerCommandinterface* interface, guint16 sinkID, gint16 volume)
{
    AFB_DEBUG("%s is called",__FUNCTION__);
    struct json_object* res_obj = json_object_new_object();
    sm_add_object_to_json_object(res_obj, 4,
        _SINK_ID, sinkID,
        _VOLUME, volume);
    afb_event_push(ev_volume_changed, res_obj);
}

static void on_sink_mute_state_changed(
            AudiomanagerCommandinterface* interface, guint16 sinkID, gint16 mute)
{
    AFB_DEBUG("%s is called",__FUNCTION__);
    struct json_object* res_obj = json_object_new_object();
    sm_add_object_to_json_object(res_obj, 4,
        _SINK_ID, sinkID,
        _MUTE_STATE, mute);
    afb_event_push(ev_sink_mute_state_changed, res_obj);
}

/*
********** Callback Function invoked by Audio Manager Routing Interface**********
*/
static void on_set_routing_ready(
            AudiomanagerRoutinginterface* interface)
{
    AFB_DEBUG("%s is called",__FUNCTION__);
    afb_event_push(ev_set_routing_ready, NULL);
}

static void on_set_routing_rundown(
            AudiomanagerRoutinginterface* interface)
{
    AFB_DEBUG("%s is called",__FUNCTION__);
    afb_event_push(ev_set_routing_ready, NULL);
}



/*
********** Callback Function invoked by Sound Manager Adapter Interface**********
*
*   For now, there may be no need to send events to applications from these invocation.
*   Sound Manager just sends ack to Audio Manager in charge of applications.
*
*/
static gboolean on_async_abort(
    AudiomanagerRoutingSoundmanager *object,
    GDBusMethodInvocation *invocation,
    guint16 arg_handle)
{
    AFB_DEBUG( "%s called", __FUNCTION__);
    /* Nothing To Do. If it is better to implement something, I will implement */
    return TRUE;
}

static gboolean on_async_connect(
    AudiomanagerRoutingSoundmanager *object,
    GDBusMethodInvocation *invocation,
    guint16 arg_handle,
    guint16 arg_connectionID,
    guint16 arg_sourceID,
    guint16 arg_sinkID,
    gint arg_connectionFormat)
{
    AFB_DEBUG( "%s called", __FUNCTION__);

    struct json_object* ev_obj = json_object_new_object();
    sm_add_object_to_json_object(ev_obj, 10,
        _HANDLE, arg_handle,
        _CONNECTION_ID, arg_connectionID,
        _SOURCE_ID, arg_sourceID,
        _SINK_ID, arg_sinkID,
        _CONNECTION_FORMAT, arg_connectionFormat);
    afb_event_push(ev_async_connect, ev_obj);

    /* GError must be initialized here because it is same as grobal errno,
       so if afb_event_push is failed due to something, number will be changed */
    GError* err = NULL;
    audiomanager_routinginterface_call_ack_connect_sync(
        am_route_bus,
        arg_handle,
        arg_connectionID,
        0,
        NULL, &err);
    if(err != NULL)
    {
        AFB_ERROR( "Can't send ack to sound manager adapter %s", __FUNCTION__);
        return FALSE;
    }
    return TRUE;
}

static gboolean on_async_disconnect(
    AudiomanagerRoutingSoundmanager *object,
    GDBusMethodInvocation *invocation,
    guint16 arg_handle,
    guint16 arg_connectionID)
{
    AFB_DEBUG( "%s called", __FUNCTION__);
    struct json_object* ev_obj = json_object_new_object();
    sm_add_object_to_json_object(ev_obj, 4,
        _HANDLE, arg_handle,
        _CONNECTION_ID, arg_connectionID);
    afb_event_push(ev_async_disconnect, ev_obj);
    GError* err = NULL;
    audiomanager_routinginterface_call_ack_disconnect_sync(
        am_route_bus,
        arg_handle,
        arg_connectionID,
        0,
        NULL, &err);
    if(err != NULL)
    {
        AFB_ERROR( "Can't send ack to sound manager adapter %s", __FUNCTION__);
        return FALSE;
    }
    return TRUE;
}

static gboolean on_async_set_sink_volume(
    AudiomanagerRoutingSoundmanager *object,
    GDBusMethodInvocation *invocation,
    guint16 arg_handle,
    guint16 arg_sinkID,
    gint16 arg_volume,
    gint16 arg_ramp,
    guint16 arg_time)
{
    AFB_DEBUG( "%s called", __FUNCTION__);
    GError* err = NULL;
    audiomanager_routinginterface_call_ack_set_sink_volume_sync(
        am_route_bus,
        arg_handle,
        arg_volume,
        0, NULL, &err);
    if(err != NULL);{
        AFB_ERROR( "Can't send ack to sound manager adapter %s", __FUNCTION__);
        return FALSE;
    }
    return TRUE;
}

/**
 * Event "asyncSetSourceState"
 * This event is one of the result of Audio Management for connect/disconnect.
 *
 * #### Parameters
 * Request key
 * - sourceID     : sourceID to be commanded by Audio Manager. The contents of command is sourceState
 * - handle       : handle is the dynamic number managed by Audio Manager. Please return this parameter to input ackSetSourceState as is
 * - sourceState  : "on" is the instruction that application can output sound
 *                  "off" is the instruction that application sound right will be removed_main_connection
 *                  "pause" is the instruction that application must stop output sound because other applications temporaly got sound right and will output sound
 *
 * #### Note
 * This function is very important for applications to realise the sequence of Audio Management.
 * An Application which matches with sourceID in the parameter of asyncSetSourceState has to return ack to use this function
 *
 */
static gboolean on_async_set_source_state(
    AudiomanagerRoutingSoundmanager *object,
    GDBusMethodInvocation *invocation,
    guint16 arg_handle,
    guint16 arg_sourceID,
    gint arg_sourceState)
{
    AFB_DEBUG( "%s called", __FUNCTION__);
    struct json_object* ev_obj = json_object_new_object();
    char* ss_key = get_source_state_key(arg_sourceState);
    sm_add_object_to_json_object(ev_obj, 4,
        _HANDLE, arg_handle,
        _SOURCE_ID, arg_sourceID);
    json_object_object_add(ev_obj, _SOURCE_STATE, json_object_new_string(ss_key));
    afb_event_push(ev_async_set_source_state, ev_obj);
    /* Applications must return ackSetSourceState to look sourceID, then Sound Manager doen't return ackSetSourceState */
    /*audiomanager_routinginterface_call_ack_set_source_state_sync(
        am_route_bus,
        arg_handle,
        NULL,
        NULL, &err);*/
}


/*
 * array of the verbs exported to afb-daemon
 */
static const struct afb_verb_v2 binding_verbs[]= {
{ .verb = "connect",                .callback = connect,                .auth = NULL,
                .info = "Connect source id and sink id" ,       .session = AFB_SESSION_NONE},
{ .verb = "disconnect",             .callback = disconnect,             .auth = NULL,
                .info = "Disconnect source id and sink id" ,    .session = AFB_SESSION_NONE},
{ .verb = "setVolume",              .callback = setVolume,              .auth = NULL,
                .info = "Set volume value" ,                    .session = AFB_SESSION_NONE}, /* it is better to show the range*/
{ .verb = "volumeStep",             .callback = volumeStep,             .auth = NULL,
                .info = "Set volume step range" ,               .session = AFB_SESSION_NONE},
{ .verb = "setSinkMuteState",       .callback = setSinkMuteState,       .auth = NULL,
                .info = "Set Mute state: 1 means mute, 2 means umute. Others are invalid" ,.session = AFB_SESSION_NONE},
{ .verb = "getListMainConnections", .callback = getListMainConnections, .auth = NULL,
                .info = "Get MainConnection List" ,             .session = AFB_SESSION_NONE},
{ .verb = "getListMainSinks",       .callback = getListMainSinks,       .auth = NULL,
                .info = "Get MainSink List" ,                   .session = AFB_SESSION_NONE},
{ .verb = "registerSource",         .callback = registerSource,         .auth = NULL,
                .info = "Register Application" ,                .session = AFB_SESSION_NONE},
{ .verb = "deregisterSource",       .callback = deregisterSource,       .auth = NULL,
                .info = "Deregister Application" ,              .session = AFB_SESSION_NONE},
{ .verb = "ackConnect",             .callback = ackConnect,             .auth = NULL,
                .info = "Acknowledge of asyncConnect" ,         .session = AFB_SESSION_NONE},
{ .verb = "ackDisconnect",          .callback = ackDisconnect,          .auth = NULL,
                .info = "Acknowledge of asyncConnect" ,         .session = AFB_SESSION_NONE},
{ .verb = "ackSetSourceState",      .callback = ackSetSourceState,      .auth = NULL,
                .info = "Acknowledge of asyncSetSourceState" ,  .session = AFB_SESSION_NONE},
{ .verb = "subscribe",              .callback = subscribe,              .auth = NULL,
                .info = "Subscribe event" ,                     .session = AFB_SESSION_NONE},
{ .verb = "unsubscribe",            .callback = unsubscribe,            .auth = NULL,
                .info = "Unsubscribe event" ,                   .session = AFB_SESSION_NONE},
{ .verb = NULL } /* marker for end of the array */};

static void *dbus_event_loop_run(void *args)
{
    loop = g_main_loop_new(NULL, FALSE);
    g_main_loop_run(loop);
}

/*
*
********** Internal Function used by Sound Manager **********
*
*/

static int registerDomain()
{
    /* Default Setting of Sound Manager Domain */
    struct domain_data ddata = {
        .domainID   = DYNAMIC_DOMAIN_ID,
        .name       = "SoundManager",
        .busname    = SOUND_MANAGER_BUS_NAME,
        .nodename   = "soundmanager",
        .early      = FALSE,
        .complete   = TRUE,
        .state      = DS_CONTROLLED
    };
    GVariant* domainData = create_domain_data(&ddata);
    gchar* retBusName = SOUND_MANAGER_BUS_NAME;
    gchar* retPath = SOUND_MANAGER_PATH;
    gchar* retInterface = SOUND_MANAGER_RETURN_INTERFACE;
    guint16 domain_id;
    GError *err = NULL;
    guint16 error;

    audiomanager_routinginterface_call_register_domain_sync(
        am_route_bus,
        domainData,
        retBusName,
        retPath,
        retInterface,
        &domain_id, &error,
        NULL, &err);
    if(err != NULL){
        AFB_ERROR( "Failed to call %s", __FUNCTION__);
        return -1;
    }
    if(error != 0)
    {
        AFB_ERROR( "Failed to register domain");
        return error;
    }
    SOUNDMANAGER_DOMAIN_ID = domain_id;
    AFB_NOTICE( "Complete registered domain id:%d",SOUNDMANAGER_DOMAIN_ID);
    return 0;
}

static int preinit()
{
    int ret;
    AFB_INFO("Initialize Dbus object");
    /* Initialize Dbus interface */
    if(am_cmd_bus || am_route_bus)
    {
        AFB_ERROR( "Dbus object to Audio Manager is already created");
        goto out;
    }
    am_cmd_bus = audiomanager_commandinterface_proxy_new_for_bus_sync(
        G_BUS_TYPE_SYSTEM,
        G_DBUS_PROXY_FLAGS_NONE,
        AM_NAME,
        AM_CMD_PATH,
        NULL,
        NULL
        );
    am_route_bus = audiomanager_routinginterface_proxy_new_for_bus_sync(
        G_BUS_TYPE_SYSTEM,
        G_DBUS_PROXY_FLAGS_NONE,
        AM_NAME,
        AM_ROUTE_PATH,
        NULL,
        NULL
        );

    if(!am_cmd_bus || !am_route_bus)
    {
        goto out;
    }

    AFB_NOTICE( "Finish Initialize");
    return 0;
out:
    AFB_ERROR("Failed to initialize");
    return -1;
}

static int create_adapter()
{
    GError *error = NULL;
    gboolean ret;
    GVariant *value;
    system_conn = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &error);
    if (error)
    {
        g_error_free(error);
        return -1;
    }
    sm_adapter = audiomanager_routing_soundmanager_skeleton_new();
    sm_itf = AUDIOMANAGER_ROUTING_SOUNDMANAGER_GET_IFACE(sm_adapter);

    /* initialize sound manager adapter */
    sm_itf->handle_async_abort = on_async_abort;
    sm_itf->handle_async_connect = on_async_connect;
    sm_itf->handle_async_disconnect = on_async_disconnect;
    sm_itf->handle_async_set_sink_volume = on_async_set_sink_volume;
    sm_itf->handle_async_set_source_state = on_async_set_source_state;

    int sigret = g_signal_connect(sm_adapter, "handle-async-abort", G_CALLBACK(on_async_abort),NULL);
    sigret = g_signal_connect(sm_adapter, "handle-async-connect", G_CALLBACK(on_async_connect),NULL);
    sigret = g_signal_connect(sm_adapter, "handle-async-disconnect", G_CALLBACK(on_async_disconnect),NULL);
    sigret = g_signal_connect(sm_adapter, "handle-async-set-sink-volume", G_CALLBACK(on_async_set_sink_volume),NULL);
    sigret = g_signal_connect(sm_adapter, "handle-async-set-source-state", G_CALLBACK(on_async_set_source_state),NULL);
    ret = g_dbus_interface_skeleton_export(G_DBUS_INTERFACE_SKELETON(sm_adapter), system_conn, SOUND_MANAGER_PATH, &error);
    if (FALSE == ret)
    {
        AFB_ERROR( "failed to export");
        g_error_free(error);
        g_object_unref(system_conn);

        return -1;
    }

    return 0;
}


static void on_name_lost(GDBusServer *server, GDBusConnection *conn, gpointer data)
{
    AFB_WARNING("%s called", __FUNCTION__);
}


static int sm_event_init()
{
    AFB_NOTICE("Initialize event receive setting");
    printf("Initialize event receive setting");
    int ret;
    /* Initialize make event */
    size_t size = sizeof cmd_evlist / sizeof *cmd_evlist;

    /*create event*/
    /*ToDo Hash table is better. And event should be created in the loop
      I would like to change */
    ev_volume_changed = afb_daemon_make_event(cmd_evlist[0]);
    ev_new_connection = afb_daemon_make_event(cmd_evlist[1]);
    ev_removed_main_connection   = afb_daemon_make_event(cmd_evlist[2]);
    ev_sink_mute_state_changed  = afb_daemon_make_event(cmd_evlist[3]);
    ev_main_connection_state_changed    = afb_daemon_make_event(cmd_evlist[4]);
    command_event_list[0].name = cmd_evlist[0];
    command_event_list[0].event = &ev_volume_changed;
    command_event_list[1].name = cmd_evlist[1];
    command_event_list[1].event = &ev_new_connection;
    command_event_list[2].name = cmd_evlist[2];
    command_event_list[2].event = &ev_removed_main_connection;
    command_event_list[3].name = cmd_evlist[3];
    command_event_list[3].event = &ev_sink_mute_state_changed;
    command_event_list[4].name = cmd_evlist[4];
    command_event_list[4].event = &ev_main_connection_state_changed;

    /* create routing event */
    ev_set_routing_ready = afb_daemon_make_event(route_evlist[0]);
    ev_set_routing_rundown = afb_daemon_make_event(route_evlist[1]);
    ev_async_connect = afb_daemon_make_event(route_evlist[2]);
    ev_async_set_source_state = afb_daemon_make_event(route_evlist[3]);
    ev_async_disconnect = afb_daemon_make_event(route_evlist[4]);

    routing_event_list[0].name = route_evlist[0];
    routing_event_list[0].event = &ev_set_routing_ready;
    routing_event_list[1].name = route_evlist[1];
    routing_event_list[1].event = &ev_set_routing_rundown;
    routing_event_list[2].name = route_evlist[2];
    routing_event_list[2].event = &ev_async_connect;
    routing_event_list[3].name = route_evlist[3];
    routing_event_list[3].event = &ev_async_set_source_state;
    routing_event_list[4].name = route_evlist[4];
    routing_event_list[4].event = &ev_async_disconnect;
    /*for(size_t i = 0; i < size; ++i)
    {
        struct afb_event afbev = afb_daemon_make_event(afbitf->daemon, cmd_evlist[i]));
        size_t afbev_size = sizeof afbev;
        size_t key_size = sizeof cmd_evlist[i];

        struct event ev = {cmd_evlist[i],afbev};
        command_event_list[i] = malloc(key_size + afbev_size);
        command_event_list[i] = ev;
        search_result = hsearch(entry, FIND);
        if(search_result)
            AFB_NOTICE( "event name is %s", search_result->key);
    }*/

    /* Initialize dbus event thread */
    if(!am_cmd_bus || !am_route_bus)
    {
        goto ev_init_out;
    }
    pthread_t thread_id;
    ret = pthread_create(&thread_id, NULL, dbus_event_loop_run, NULL);
    if(ret != 0)
    {
        goto ev_init_out;
    }
    /* initialize signal from audio manager command interface */
    g_signal_connect(am_cmd_bus,
        "volume_changed",
        G_CALLBACK(on_volume_changed),
        NULL);
    g_signal_connect(am_cmd_bus,
        "new_main_connection",
        G_CALLBACK(on_new_main_connection),
        NULL);
    g_signal_connect(am_cmd_bus,
        "removed_main_connection",
        G_CALLBACK(on_removed_main_connection),
        NULL);
    g_signal_connect(am_cmd_bus,
        "sink_mute_state_changed",
        G_CALLBACK(on_sink_mute_state_changed),
        NULL);
    g_signal_connect(am_cmd_bus,
        "main_connection_state_changed",
        G_CALLBACK(on_main_connection_state_changed),
        NULL);
    g_signal_connect(am_route_bus,
        "set_routing_ready",
        G_CALLBACK(on_set_routing_ready),
        NULL);
    g_signal_connect(am_route_bus,
        "set_routing_rundown",
        G_CALLBACK(on_set_routing_rundown),
        NULL);

    /* Get soundmanager adapter bus */
    ret = g_bus_own_name(G_BUS_TYPE_SYSTEM, SOUND_MANAGER_BUS_NAME, G_BUS_NAME_OWNER_FLAGS_NONE,
        NULL,NULL, NULL, NULL, NULL);
	AFB_DEBUG( "g_bus_own_name ret: %d", ret);
    ret = create_adapter();
    if(ret != 0)
    {
        goto ev_init_out;
    }
    ret = registerDomain();

    if(ret != 0)
    {
		AFB_ERROR("registerDomain error: %s",get_response_audiomanager_massage_error(ret));
        goto ev_init_out;
    }

    AFB_INFO("Finish Initialize event receive setting");
    return 0;

ev_init_out:
    if(loop != NULL)
    {
        g_main_loop_unref(loop);
    }
    AFB_WARNING( "DBus connection is not created");
    return -1;
}

static void onevent(const char *event, struct json_object *object)
{
   AFB_NOTICE("on_event %s", event);
}

const struct afb_binding_v2 afbBindingV2 = {
    .api = "soundmanager",
    .specification = NULL,
    .verbs = binding_verbs,
    .preinit = preinit,
    .init = sm_event_init,
    .onevent = onevent
};