summaryrefslogtreecommitdiffstats
path: root/LICENSE
blob: 8dada3edaf50dbc082c9a125058f25def75e625a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "{}"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright {yyyy} {name of copyright owner}

   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.
15 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 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
/*
 * Copyright 2018 Konsulko Group
 * Author: Matt Ranostay <matt.ranostay@konsulko.com>
 * Author: Pantelis Antoniou <pantelis.antoniou@konsulko.com>
 *
 * 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 <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>
#include <semaphore.h>

#include <glib.h>
#include <stdlib.h>
#include <gio/gio.h>
#include <glib-object.h>

#include <json-c/json.h>

#define AFB_BINDING_VERSION 3
#include <afb/afb-binding.h>

#include "bluetooth-api.h"
#include "bluetooth-common.h"

/**
 * The global thread
 */
static GThread *global_thread;

struct bluetooth_state *bluetooth_get_userdata(afb_req_t request) {
	afb_api_t api = afb_req_get_api(request);
	return afb_api_get_userdata(api);
}

void call_work_lock(struct bluetooth_state *ns)
{
	g_mutex_lock(&ns->cw_mutex);
}

void call_work_unlock(struct bluetooth_state *ns)
{
	g_mutex_unlock(&ns->cw_mutex);
}

static void mediaplayer1_set_path(struct bluetooth_state *ns, const char *path)
{
	if (ns->mediaplayer_path)
		g_free(ns->mediaplayer_path);
	ns->mediaplayer_path = g_strdup(path);
}

static void mediaplayer1_connect_disconnect(struct bluetooth_state *ns,
				            const gchar *player, int state)
{
	GVariant *reply;
	gchar *path = g_strdup(player);
	const char *uuids[] = { "0000110a-0000-1000-8000-00805f9b34fb", "0000110e-0000-1000-8000-00805f9b34fb", NULL };
	const char **tmp = (const char **) uuids;

	*g_strrstr(path, "/") = '\0';

	for (; *tmp; tmp++) {
		reply = bluez_call(ns, BLUEZ_AT_DEVICE, path, state ? "ConnectProfile" : "DisconnectProfile", g_variant_new("(&s)", *tmp), NULL);
		if (!reply)
			break;
		g_variant_unref(reply);
	}

	g_free(path);
}

struct call_work *call_work_lookup_unlocked(
		struct bluetooth_state *ns,
		const char *access_type, const char *type_arg,
		const char *method)
{
	struct call_work *cw;
	GSList *list;

	/* we can only allow a single pending call */
	for (list = ns->cw_pending; list; list = g_slist_next(list)) {
		cw = list->data;
		if (!g_strcmp0(access_type, cw->access_type) &&
		    !g_strcmp0(type_arg, cw->type_arg) &&
		    !g_strcmp0(method, cw->method))
			return cw;
	}
	return NULL;
}

struct call_work *call_work_lookup(
		struct bluetooth_state *ns,
		const char *access_type, const char *type_arg,
		const char *method)
{
	struct call_work *cw;

	g_mutex_lock(&ns->cw_mutex);
	cw = call_work_lookup_unlocked(ns, access_type, type_arg, method);
	g_mutex_unlock(&ns->cw_mutex);

	return cw;
}

int call_work_pending_id(
		struct bluetooth_state *ns,
		const char *access_type, const char *type_arg,
		const char *method)
{
	struct call_work *cw;
	int id = -1;

	g_mutex_lock(&ns->cw_mutex);
	cw = call_work_lookup_unlocked(ns, access_type, type_arg, method);
	if (cw)
		id = cw->id;
	g_mutex_unlock(&ns->cw_mutex);

	return id;
}

struct call_work *call_work_lookup_by_id_unlocked(
		struct bluetooth_state *ns, int id)
{
	struct call_work *cw;
	GSList *list;

	/* we can only allow a single pending call */
	for (list = ns->cw_pending; list; list = g_slist_next(list)) {
		cw = list->data;
		if (cw->id == id)
			return cw;
	}
	return NULL;
}

struct call_work *call_work_lookup_by_id(
		struct bluetooth_state *ns, int id)
{
	struct call_work *cw;

	g_mutex_lock(&ns->cw_mutex);
	cw = call_work_lookup_by_id_unlocked(ns, id);
	g_mutex_unlock(&ns->cw_mutex);

	return cw;
}

struct call_work *call_work_create_unlocked(struct bluetooth_state *ns,
		const char *access_type, const char *type_arg,
		const char *method, const char *bluez_method,
		GError **error)
{

	struct call_work *cw = NULL;

	cw = call_work_lookup_unlocked(ns, access_type, type_arg, method);
	if (cw) {
		g_set_error(error, NB_ERROR, NB_ERROR_CALL_IN_PROGRESS,
				"another call in progress (%s/%s/%s)",
				access_type, type_arg, method);
		return NULL;
	}

	/* no other pending; allocate */
	cw = g_malloc0(sizeof(*cw));
	cw->ns = ns;
	do {
		cw->id = ns->next_cw_id;
		if (++ns->next_cw_id < 0)
			ns->next_cw_id = 1;
	} while (call_work_lookup_by_id_unlocked(ns, cw->id));

	cw->access_type = g_strdup(access_type);
	cw->type_arg = g_strdup(type_arg);
	cw->method = g_strdup(method);
	cw->bluez_method = g_strdup(bluez_method);

	ns->cw_pending = g_slist_prepend(ns->cw_pending, cw);

	return cw;
}

struct call_work *call_work_create(struct bluetooth_state *ns,
		const char *access_type, const char *type_arg,
		const char *method, const char *bluez_method,
		GError **error)
{

	struct call_work *cw;

	g_mutex_lock(&ns->cw_mutex);
	cw = call_work_create_unlocked(ns,
			access_type, type_arg, method, bluez_method,
			error);
	g_mutex_unlock(&ns->cw_mutex);

	return cw;
}

void call_work_destroy_unlocked(struct call_work *cw)
{
	struct bluetooth_state *ns = cw->ns;
	struct call_work *cw2;

	/* verify that it's something we know about */
	cw2 = call_work_lookup_by_id_unlocked(ns, cw->id);
	if (cw2 != cw) {
		AFB_ERROR("Bad call work to destroy");
		return;
	}

	/* remove it */
	ns->cw_pending = g_slist_remove(ns->cw_pending, cw);

	/* agent struct data */
	g_free(cw->agent_data.device_path);
	cw->agent_data.device_path = NULL;
	g_free(cw->access_type);
	g_free(cw->type_arg);
	g_free(cw->method);
	g_free(cw->bluez_method);
}

void call_work_destroy(struct call_work *cw)
{
	struct bluetooth_state *ns = cw->ns;

	g_mutex_lock(&ns->cw_mutex);
	call_work_destroy_unlocked(cw);
	g_mutex_unlock(&ns->cw_mutex);
}

static afb_event_t get_event_from_value(struct bluetooth_state *ns,
			const char *value)
{
	if (!g_strcmp0(value, "adapter_changes"))
		return ns->adapter_changes_event;

	if (!g_strcmp0(value, "device_changes"))
		return ns->device_changes_event;

	if (!g_strcmp0(value, "media"))
		return ns->media_event;

	if (!g_strcmp0(value, "agent"))
		return ns->agent_event;

	return NULL;
}

static void bluez_devices_signal_callback(
	GDBusConnection *connection,
	const gchar *sender_name,
	const gchar *object_path,
	const gchar *interface_name,
	const gchar *signal_name,
	GVariant *parameters,
	gpointer user_data)
{
	struct bluetooth_state *ns = user_data;
	GVariantIter *array1 = NULL;
	GError *error = NULL;
	GVariant *var = NULL;
	const gchar *path = NULL;
	const gchar *key = NULL;
	json_object *jresp = NULL, *jobj;
	GVariantIter *array = NULL;
	gboolean is_config, ret;
	afb_event_t event = ns->device_changes_event;

	/* AFB_INFO("sender=%s", sender_name);
	AFB_INFO("object_path=%s", object_path);
	AFB_INFO("interface=%s", interface_name);
	AFB_INFO("signal=%s", signal_name); */

	if (!g_strcmp0(signal_name, "InterfacesAdded")) {

		g_variant_get(parameters, "(&oa{sa{sv}})", &path, &array);

		// no adapter or device in path
		if (!g_strcmp0(path, BLUEZ_PATH))
			return;

		jresp = json_object_new_object();

		json_process_path(jresp, path);

		jobj = json_object_new_object();

		while (g_variant_iter_next(array, "{&s@a{sv}}", &key, &var)) {
			const char *name = NULL;
			GVariant *val = NULL;

			if (g_strcmp0(key, BLUEZ_DEVICE_INTERFACE) &&
			    g_strcmp0(key, BLUEZ_MEDIATRANSPORT_INTERFACE) &&
			    g_strcmp0(key, BLUEZ_ADAPTER_INTERFACE))
				continue;

			array1 = g_variant_iter_new(var);

			while (g_variant_iter_next(array1, "{&sv}", &name, &val)) {
				if (!g_strcmp0(key, BLUEZ_DEVICE_INTERFACE)) {
					ret = device_property_dbus2json(jobj,
						name, val, &is_config, &error);
				} else if (!g_strcmp0(key, BLUEZ_MEDIATRANSPORT_INTERFACE)) {
					ret = mediatransport_property_dbus2json(jobj,
						name, val, &is_config, &error);
				} else if (!g_strcmp0(key, BLUEZ_ADAPTER_INTERFACE)) {
					ret = adapter_property_dbus2json(jobj,
						name, val, &is_config, &error);
					event = ns->adapter_changes_event;
				} else {
					ret = TRUE;
				}

				g_variant_unref(val);
				if (!ret) {
					AFB_DEBUG("%s property %s - %s",
							path,
							key, error->message);
					g_clear_error(&error);
				}
			}
			g_variant_iter_free(array1);
		}
		g_variant_iter_free(array);

		if (array1) {
			json_object_object_add(jresp, "action",
				json_object_new_string("added"));

			if (is_mediatransport1_interface(path)) {
				gchar *endpoint = find_index(path, 5);
				json_object_object_add(jresp, "type",
					json_object_new_string("transport"));
				json_object_object_add(jresp, "endpoint",
					json_object_new_string(endpoint));
				g_free(endpoint);

				event = ns->media_event;
			}
			json_object_object_add(jresp, "properties", jobj);
		} else if (is_mediaplayer1_interface(path)) {
			gchar *player = find_index(path, 5);
			json_object_object_add(jresp, "connected",
				json_object_new_boolean(TRUE));
			json_object_object_add(jresp, "type",
				json_object_new_string("playback"));
			json_object_object_add(jresp, "player",
				json_object_new_string(player));
			mediaplayer1_set_path(ns, path);
			event = ns->media_event;
		} else {
			json_object_put(jresp);
			jresp = NULL;
		}

	} else if (!g_strcmp0(signal_name, "InterfacesRemoved")) {

		g_variant_get(parameters, "(&oas)", &path, &array);
		g_variant_iter_free(array);

		jresp = json_object_new_object();
		json_process_path(jresp, path);

		if (is_mediatransport1_interface(path)) {
			gchar *endpoint = find_index(path, 5);
			json_object_object_add(jresp, "type",
				json_object_new_string("transport"));
			json_object_object_add(jresp, "action",
				json_object_new_string("removed"));
			json_object_object_add(jresp, "endpoint",
				json_object_new_string(endpoint));
			g_free(endpoint);

			event = ns->media_event;
		} else if (is_mediaplayer1_interface(path)) {
			gchar *player = find_index(path, 5);
			json_object_object_add(jresp, "connected",
				json_object_new_boolean(FALSE));
			json_object_object_add(jresp, "type",
				json_object_new_string("playback"));
			json_object_object_add(jresp, "player",
				json_object_new_string(player));
			event = ns->media_event;
		/* adapter removal */
		} else if (split_length(path) == 4) {
			json_object_object_add(jresp, "action",
				json_object_new_string("removed"));
			event = ns->adapter_changes_event;
		/* device removal */
		} else if (split_length(path) == 5) {
			json_object_object_add(jresp, "action",
				json_object_new_string("removed"));
		} else {
			json_object_put(jresp);
			jresp = NULL;
		}

	} else if (!g_strcmp0(signal_name, "PropertiesChanged")) {

		g_variant_get(parameters, "(&sa{sv}as)", &path, &array, &array1);

		if (!g_strcmp0(path, BLUEZ_DEVICE_INTERFACE) ||
		    !g_strcmp0(path, BLUEZ_ADAPTER_INTERFACE)) {
			int cnt = 0;

			jresp = json_object_new_object();

			json_process_path(jresp, object_path);
			json_object_object_add(jresp, "action",
					json_object_new_string("changed"));

			jobj = json_object_new_object();

			while (g_variant_iter_next(array, "{&sv}", &key, &var)) {
				if (!g_strcmp0(path, BLUEZ_DEVICE_INTERFACE)) {
					ret = device_property_dbus2json(jobj,
						key, var, &is_config, &error);
					event = ns->device_changes_event;
				} else {
					ret = adapter_property_dbus2json(jobj,
						key, var, &is_config, &error);
					event = ns->adapter_changes_event;
				}
				g_variant_unref(var);
				if (!ret) {
					AFB_DEBUG("%s property %s - %s",
							"devices",
							key, error->message);
					g_clear_error(&error);
					continue;
				}
				cnt++;
			}

			// NOTE: Possible to get a changed property for something we don't care about
			if (cnt > 0) {
				json_object_object_add(jresp, "properties", jobj);
			} else {
				json_object_put(jobj);
				json_object_put(jresp);
				jresp = NULL;
			}

		} else if (!g_strcmp0(path, BLUEZ_MEDIAPLAYER_INTERFACE) ||
			   !g_strcmp0(path, BLUEZ_MEDIATRANSPORT_INTERFACE)) {
			int cnt = 0;
			jresp = json_object_new_object();
			json_process_path(jresp, object_path);

			while (g_variant_iter_next(array, "{&sv}", &key, &var)) {
				if (!g_strcmp0(path, BLUEZ_MEDIAPLAYER_INTERFACE))
					ret = mediaplayer_property_dbus2json(jresp,
						key, var, &is_config, &error);
				else
					ret = mediatransport_property_dbus2json(jresp,
						key, var, &is_config, &error);
				g_variant_unref(var);
				if (!ret) {
					AFB_DEBUG("%s property %s - %s",
							path,
							key, error->message);
					g_clear_error(&error);
					continue;
				}
				cnt++;
			}

			if (!g_strcmp0(path, BLUEZ_MEDIAPLAYER_INTERFACE)) {
				json_object_object_add(jresp, "type",
					json_object_new_string("playback"));
			} else {
				gchar *endpoint = find_index(object_path, 5);
				json_object_object_add(jresp, "action",
					json_object_new_string("changed"));
				json_object_object_add(jresp, "type",
					json_object_new_string("transport"));
				json_object_object_add(jresp, "endpoint",
					json_object_new_string(endpoint));
				g_free(endpoint);
			}

			// NOTE: Possible to get a changed property for something we don't care about
			if (!cnt) {
				json_object_put(jresp);
				jresp = NULL;
			}

			event = ns->media_event;
		}

		g_variant_iter_free(array);
		g_variant_iter_free(array1);
	}

	if (jresp) {
		afb_event_push(event, jresp);
		jresp = NULL;
	}

	json_object_put(jresp);
}

static int bluetooth_select_init_adapter(struct init_data *id)
{
	struct bluetooth_state *ns =id->ns;
	GError *error = NULL;
	json_object *jresp, *jobj = NULL;
	int ret, i;
	size_t count;

	jresp = object_properties(ns, &error);
	if (error) {
		AFB_INFO("object_properties for adapters error: %s",
			error->message);
		g_clear_error(&error);
		ret = -EIO;
	} else {
		json_object_object_get_ex(jresp, "adapters", &jobj);
		count = json_object_array_length(jobj);
		ret = (int)count;

		for (i = 1; (ret-i) >= 0; i++) {
			json_object *idx = json_object_array_get_idx(jobj, count-i);
			json_object *name = NULL;
			const char *adapter;
			json_object_object_get_ex(idx, "name", &name);
			adapter = json_object_get_string(name);
			if (!g_strcmp0(adapter, id->default_adapter)) {
				id->ns->adapter = id->default_adapter;
				break;
			}
			if (!(count-i)) {
				/* fallback to 1st available adapter */
				id->ns->adapter = g_strdup(adapter);
				AFB_WARNING("default adapter %s not found, fell back to: %s",
						id->default_adapter, adapter);
			}
		}
		json_object_put(jresp);
	}
	return ret;
}

static struct bluetooth_state *bluetooth_init(GMainLoop *loop)
{
	struct bluetooth_state *ns;
	GError *error = NULL;

	ns = g_try_malloc0(sizeof(*ns));
	if (!ns) {
		AFB_ERROR("out of memory allocating bluetooth state");
		goto err_no_ns;
	}

	AFB_INFO("connecting to dbus");

	ns->loop = loop;
	ns->conn = g_bus_get_sync(G_BUS_TYPE_SYSTEM, NULL, &error);
	if (!ns->conn) {
		if (error)
			g_dbus_error_strip_remote_error(error);
		AFB_ERROR("Cannot connect to D-Bus, %s",
				error ? error->message : "unspecified");
		g_error_free(error);
		goto err_no_conn;

	}

	AFB_INFO("connected to dbus");

	ns->adapter_changes_event =
		afb_daemon_make_event("adapter_changes");
	ns->device_changes_event =
		afb_daemon_make_event("device_changes");
	ns->media_event =
		afb_daemon_make_event("media");
	ns->agent_event =
		afb_daemon_make_event("agent");

	if (!afb_event_is_valid(ns->device_changes_event) ||
	    !afb_event_is_valid(ns->media_event) ||
	    !afb_event_is_valid(ns->agent_event)) {
		AFB_ERROR("Cannot create events");
		goto err_no_events;
	}

	ns->device_sub = g_dbus_connection_signal_subscribe(
			ns->conn,
			BLUEZ_SERVICE,
			NULL,   /* interface */
			NULL,	/* member */
			NULL,	/* object path */
			NULL,	/* arg0 */
			G_DBUS_SIGNAL_FLAGS_NONE,
			bluez_devices_signal_callback,
			ns,
			NULL);
	if (!ns->device_sub) {
		AFB_ERROR("Unable to subscribe to interface signals");
		goto err_no_device_sub;
	}

	g_mutex_init(&ns->cw_mutex);
	ns->next_cw_id = 1;

	g_timeout_add_seconds(5, bluetooth_autoconnect, ns);

	return ns;

err_no_device_sub:
	/* no way to clear the events */
err_no_events:
	g_dbus_connection_close(ns->conn, NULL, NULL, NULL);
err_no_conn:
	g_free(ns);
err_no_ns:
	return NULL;
}

static void bluetooth_cleanup(struct bluetooth_state *ns)
{
	g_dbus_connection_signal_unsubscribe(ns->conn, ns->device_sub);
	g_dbus_connection_close(ns->conn, NULL, NULL, NULL);
	g_free(ns);
}

static gpointer bluetooth_func(gpointer ptr)
{
	struct init_data *id = ptr;
	struct bluetooth_state *ns;
	GMainLoop *loop;
	int rc = 0;

	g_atomic_rc_box_acquire(id);

	loop = g_main_loop_new(NULL, FALSE);
	if (!loop) {
		AFB_ERROR("Unable to create main loop");
		goto err_no_loop;
	}

	/* real bluetooth init */
	ns = bluetooth_init(loop);
	if (!ns) {
		AFB_ERROR("bluetooth_init() failed");
		goto err_no_ns;
	}

	id->ns = ns;
	rc = bluetooth_select_init_adapter(id);
	if (rc > 0) {
		rc = bluetooth_register_agent(id);
		if (rc) {
			AFB_ERROR("bluetooth_register_agent() failed");
			goto err_no_service;
		}
	}
	else if (rc < 0) {
		goto err_no_service;
	}
	else {
		//fake it
		AFB_INFO("No adapter present, completed initialization");
		signal_init_done(id, 0);
	}
	/* note that we wait for agent registration to signal done */

	afb_api_set_userdata(id->api, ns);
	g_main_loop_run(loop);

	g_main_loop_unref(ns->loop);

	if (ns->agent_path)
		bluetooth_unregister_agent(ns);

	bluetooth_cleanup(ns);
	afb_api_set_userdata(id->api, NULL);
	g_atomic_rc_box_release(id);

	return NULL;

err_no_service:
	bluetooth_cleanup(ns);

err_no_ns:
	g_main_loop_unref(loop);

err_no_loop:
	signal_init_done(id, -1);
	g_atomic_rc_box_release(id);

	return NULL;
}

static int init(afb_api_t api)
{
	struct init_data *id = NULL;
	json_object *args = NULL;
	gint64 end_time;
	int ret;
	gboolean init_done;

	id = g_atomic_rc_box_new0(struct init_data);
	if (!id)
		return -ENOMEM;
	g_atomic_rc_box_acquire(id);

	id->init_done = FALSE;
	id->rc = 0;
	id->api = api;
	g_cond_init(&id->cond);
	g_mutex_init(&id->mutex);

	ret = afb_daemon_require_api("persistence", 1);
	if (ret < 0) {
		AFB_ERROR("Cannot request data persistence service");
		return ret;
	}

	ret = afb_daemon_require_api("network-manager", 1);
	if (ret < 0) {
		AFB_ERROR("Cannot request network manager service");
		return ret;
	}

	id->default_adapter = get_default_adapter(id->api);
	if (!id->default_adapter) {
		id->default_adapter = g_strdup(BLUEZ_DEFAULT_ADAPTER);
		ret = set_default_adapter(api, BLUEZ_DEFAULT_ADAPTER);
		if (ret)
			AFB_WARNING("Request to save default adapter to persistent storage failed ");
	}

	args = json_object_new_object();
	json_object_object_add(args , "technology", json_object_new_string("bluetooth"));
	afb_api_call_sync(api, "network-manager", "enable_technology", args, NULL, NULL, NULL);

	global_thread = g_thread_new("agl-service-bluetooth",
				bluetooth_func,
				id);

	AFB_INFO("bluetooth-binding waiting for init done");

	/* wait maximum 10 seconds for init done */
	end_time = g_get_monotonic_time () + 10 * G_TIME_SPAN_SECOND;
	g_mutex_lock(&id->mutex);
	while (!id->init_done) {
		if (!g_cond_wait_until(&id->cond, &id->mutex, end_time))
			break;
	}
	ret = id->rc;
	init_done = id->init_done;
	g_mutex_unlock(&id->mutex);
	g_atomic_rc_box_release(id);

	if (!init_done) {
		AFB_ERROR("bluetooth-binding init timeout");
		return -1;
	}

	if (ret)
		AFB_ERROR("bluetooth-binding init thread returned %d", ret);
	else
		AFB_INFO("bluetooth-binding operational");

	return ret;
}

static void mediaplayer1_send_event(struct bluetooth_state *ns)
{
	if (!ns->mediaplayer_path) {
		AFB_ERROR("NULL mediaplayer_path");
		return;
	}

	gchar *player = g_strdup(ns->mediaplayer_path);
	json_object *jresp = mediaplayer_properties(ns, NULL, player);

	if (!jresp)
		goto out_err;

	json_process_path(jresp, player);
	json_object_object_add(jresp, "connected",
			json_object_new_boolean(TRUE));

	afb_event_push(ns->media_event, jresp);

out_err:
	g_free(player);
}

static void bluetooth_subscribe_unsubscribe(afb_req_t request,
		gboolean unsub)
{
	struct bluetooth_state *ns = bluetooth_get_userdata(request);
	json_object *jresp = json_object_new_object();
	const char *value;
	afb_event_t event;
	int rc;

	if (!ns) {
		afb_req_fail(request, "failed", "Cannot process request");
		return;
	}

	/* if value exists means to set offline mode */
	value = afb_req_value(request, "value");
	if (!value) {
		afb_req_fail_f(request, "failed", "Missing \"value\" event");
		return;
	}

	event = get_event_from_value(ns, value);
	if (!event) {
		afb_req_fail_f(request, "failed", "Bad \"value\" event \"%s\"",
				value);
		return;
	}

	if (!unsub) {
		rc = afb_req_subscribe(request, event);

		if (!g_strcmp0(value, "media"))
			mediaplayer1_send_event(ns);
	} else {
		rc = afb_req_unsubscribe(request, event);
	}
	if (rc != 0) {
		afb_req_fail_f(request, "failed",
					"%s error on \"value\" event \"%s\"",
					!unsub ? "subscribe" : "unsubscribe",
					value);
		return;
	}

	afb_req_success_f(request, jresp, "Bluetooth %s to event \"%s\"",
			!unsub ? "subscribed" : "unsubscribed",
			value);
}

static void bluetooth_subscribe(afb_req_t request)
{
	bluetooth_subscribe_unsubscribe(request, FALSE);
}

static void bluetooth_unsubscribe(afb_req_t request)
{
	bluetooth_subscribe_unsubscribe(request, TRUE);
}

static void bluetooth_list(afb_req_t request)
{
	struct bluetooth_state *ns = bluetooth_get_userdata(request);
	GError *error = NULL;
	json_object *jresp;

	if (!ns) {
		afb_req_fail(request, "failed", "Cannot process request");
		return;
	}

	jresp = object_properties(ns, &error);
	if (error) {
		AFB_INFO("object_properties error: %s",
			error->message);
		g_clear_error(&error);
		afb_req_fail(request, "failed", "BlueZ managed objects error");
	} else
		afb_req_success(request, jresp, "BlueZ managed objects");

}

static void bluetooth_state(afb_req_t request)
{
	struct bluetooth_state *ns = bluetooth_get_userdata(request);
	GError *error = NULL;
	json_object *jresp;
	const char *adapter = afb_req_value(request, "adapter");

	if (!ns || (!adapter && !ns->adapter)) {
		afb_req_fail(request, "failed", "No adapter");
		return;
	}

	adapter = BLUEZ_ROOT_PATH(adapter ? adapter : ns->adapter);

	jresp = adapter_properties(ns, &error, adapter);
	if (!jresp) {
		afb_req_fail_f(request, "failed", "property %s error %s",
				"State", BLUEZ_ERRMSG(error));
		return;
	}

	afb_req_success(request, jresp, "Bluetooth - adapter state");
}

static void bluetooth_adapter(afb_req_t request)
{
	struct bluetooth_state *ns = bluetooth_get_userdata(request);
	GError *error = NULL;
	const char *adapter = afb_req_value(request, "adapter");
	const char *scan, *discoverable, *powered, *filter, *transport;

	if (!ns || (!adapter && !ns->adapter)) {
		afb_req_fail(request, "failed", "No adapter");
		return;
	}

	adapter = BLUEZ_ROOT_PATH(adapter ? adapter : ns->adapter);

	scan = afb_req_value(request, "discovery");
	if (scan) {
		GVariant *reply = adapter_call(ns, adapter, str2boolean(scan) ?
				"StartDiscovery" : "StopDiscovery", NULL, &error);

		if (!reply) {
			afb_req_fail_f(request, "failed",
					"adapter %s method %s error %s",
					scan, "Scan", BLUEZ_ERRMSG(error));
			g_error_free(error);
			return;
		}
		g_variant_unref(reply);
	}

	discoverable = afb_req_value(request, "discoverable");
	if (discoverable) {
		int ret = adapter_set_property(ns, adapter, FALSE, "Discoverable",
				json_object_new_boolean(str2boolean(discoverable)),
				&error);
		if (!ret) {
			afb_req_fail_f(request, "failed",
					"adapter %s set_property %s error %s",
					adapter, "Discoverable", BLUEZ_ERRMSG(error));
			g_error_free(error);
			return;
		}
	}

	powered = afb_req_value(request, "powered");
	if (powered) {
		int ret = adapter_set_property(ns, adapter, FALSE, "Powered",
				json_object_new_boolean(str2boolean(powered)),
				&error);

		if (!ret) {
			afb_req_fail_f(request, "failed",
					"adapter %s set_property %s error %s",
					adapter, "Powered", BLUEZ_ERRMSG(error));
			g_error_free(error);
			return;
		}
	}

	filter = afb_req_value(request, "filter");
	transport = afb_req_value(request, "transport");

	if (filter || transport) {
		GVariantBuilder builder;
		GVariant *flt, *reply;

		g_variant_builder_init(&builder, G_VARIANT_TYPE("a{sv}"));

		if (filter) {
			json_object *jobj = json_tokener_parse(filter);
			gchar **uuid = NULL;

			if (json_object_get_type(jobj) != json_type_array) {
				afb_req_fail_f(request, "failed", "invalid discovery filter");
				return;
			}

			uuid = json_array_to_strv(jobj);
			g_variant_builder_add(&builder, "{sv}", "UUIDs",
					g_variant_new_strv((const gchar * const *) uuid, -1));

			g_strfreev(uuid);
		}

		if (transport) {
			g_variant_builder_add(&builder, "{sv}", "Transport",
					      g_variant_new_string(transport));

		}

		flt = g_variant_builder_end(&builder);

		reply = adapter_call(ns, adapter, "SetDiscoveryFilter",
				     g_variant_new("(@a{sv})", flt), &error);


		if (!reply) {
			afb_req_fail_f(request, "failed",
					"adapter %s SetDiscoveryFilter error %s",
					adapter, BLUEZ_ERRMSG(error));
			g_error_free(error);
			return;
		}
		g_variant_unref(reply);
	}

	bluetooth_state(request);
}

static void bluetooth_default_adapter(afb_req_t request)
{
	const char *adapter = afb_req_value(request, "adapter");
	json_object *jresp = json_object_new_object();
	afb_api_t api = afb_req_get_api(request);
	const char *adapter_default = get_default_adapter(api);
	int rc;

	if (adapter) {
		if (adapter_default && g_strcmp0(adapter_default, adapter)) {
			rc = set_default_adapter(api, adapter);
			if (rc) {
				AFB_DEBUG("Request to save default adapter to persistent storage failed ");
				afb_req_fail(request, "failed", "Update default adapter failed");
				return;
			}
		}
		json_object_object_add(jresp, "adapter", json_object_new_string(adapter));
	} else if (adapter_default) {
		json_object_object_add(jresp, "adapter", json_object_new_string(adapter_default));
	} else {
		afb_req_fail(request, "failed", "No default adapter");
	        return;
	}
	afb_req_success(request, jresp, "Bluetooth - default adapter");
}

static void connect_service_callback(void *user_data,
		GVariant *result, GError **error)
{
	struct call_work *cw = user_data;
	struct bluetooth_state *ns = cw->ns;

	bluez_decode_call_error(ns,
		cw->access_type, cw->type_arg, cw->bluez_method,
		error);

	if (error && *error) {
		afb_req_fail_f(cw->request, "failed", "Connect error: %s",
				(*error)->message);
		goto out_free;
	}

	if (result)
		g_variant_unref(result);

	afb_req_success_f(cw->request, NULL, "Bluetooth - device %s connected",
			cw->type_arg);
out_free:
	afb_req_unref(cw->request);
	call_work_destroy(cw);
}

static void bluetooth_connect_device(afb_req_t request)
{
	struct bluetooth_state *ns = bluetooth_get_userdata(request);
	GError *error = NULL;
	const char *uuid;
	struct call_work *cw;
	gchar *device;

	device = return_bluez_path(request);
	if (!device) {
		afb_req_fail(request, "failed", "No path given");
		return;
	}

	/* optional, connect single profile */
	uuid = afb_req_value(request, "uuid");

	cw = call_work_create(ns, BLUEZ_AT_DEVICE, device,
			"connect_service", "Connect", &error);
	if (!cw) {
		afb_req_fail_f(request, "failed", "can't queue work %s",
				error->message);
		g_error_free(error);
		goto out_free;
	}

	cw->request = request;
	afb_req_addref(request);

	if (uuid)
		cw->cpw = bluez_call_async(ns, BLUEZ_AT_DEVICE, device,
			"ConnectProfile", g_variant_new("(&s)", uuid), &error,
			connect_service_callback, cw);
	else
		cw->cpw = bluez_call_async(ns, BLUEZ_AT_DEVICE, device,
			"Connect", NULL, &error,
			connect_service_callback, cw);

	if (!cw->cpw) {
		afb_req_fail_f(request, "failed", "connection error %s",
				error->message);
		call_work_destroy(cw);
		g_error_free(error);
		/* fall-thru */
	}

out_free:
	g_free(device);

}

static void bluetooth_disconnect_device(afb_req_t request)
{
	struct bluetooth_state *ns = bluetooth_get_userdata(request);
	json_object *jresp;
	GVariant *reply = NULL;
	GError *error = NULL;
	const char *uuid;
	gchar *device;

	device = return_bluez_path(request);
	if (!device) {
		afb_req_fail(request, "failed", "No device given to disconnect");
		return;
	}

	/* optional, disconnect single profile */
	uuid = afb_req_value(request, "uuid");

	if (uuid)
		reply = device_call(ns, device, "DisconnectProfile",
				g_variant_new("(&s)", uuid), &error);
	else
		reply = device_call(ns, device, "Disconnect", NULL, &error);

	if (!reply) {
		afb_req_fail_f(request, "failed", "Disconnect error %s",
				error ? error->message : "unspecified");
		g_free(device);
		g_error_free(error);
		return;
	}

	g_variant_unref(reply);

	jresp = json_object_new_object();
	afb_req_success_f(request, jresp, "Device - Bluetooth %s disconnected",
			device);

	g_free(device);
}

static void pair_service_callback(void *user_data,
		GVariant *result, GError **error)
{
	struct call_work *cw = user_data;
	struct bluetooth_state *ns = cw->ns;

	bluez_decode_call_error(ns,
		cw->access_type, cw->type_arg, cw->bluez_method,
		error);

	if (error && *error) {
		afb_req_fail_f(cw->request, "failed", "Connect error: %s",
				(*error)->message);
		goto out_free;
	}

	if (result)
		g_variant_unref(result);

	afb_req_success_f(cw->request, NULL, "Bluetooth - device %s paired",
			cw->type_arg);
out_free:
	afb_req_unref(cw->request);
	call_work_destroy(cw);
}

static void bluetooth_pair_device(afb_req_t request)
{
	struct bluetooth_state *ns = bluetooth_get_userdata(request);
	GError *error = NULL;
	gchar *device;
	struct call_work *cw;

	device = return_bluez_path(request);
	if (!device) {
		afb_req_fail(request, "failed", "No path given");
		return;
	}

	cw = call_work_create(ns, BLUEZ_AT_DEVICE, device,
			"pair_device", "Pair", &error);
	if (!cw) {
		afb_req_fail_f(request, "failed", "can't queue work %s",
				error->message);
		g_error_free(error);
		goto out_free;
	}

	cw->request = request;
	afb_req_addref(request);

	cw->agent_data.fixed_pincode = get_pincode(afb_req_get_api(request));

	cw->cpw = bluez_call_async(ns, BLUEZ_AT_DEVICE, device, "Pair", NULL, &error,
			pair_service_callback, cw);

	if (!cw->cpw) {
		afb_req_fail_f(request, "failed", "connection error %s",
				error->message);
		call_work_destroy(cw);
		g_error_free(error);
		goto out_free;
	}

out_free:
	g_free(device);

}

static void bluetooth_cancel_pairing(afb_req_t request)
{
	struct bluetooth_state *ns = bluetooth_get_userdata(request);
	struct call_work *cw;
	GVariant *reply = NULL;
	GError *error = NULL;
	gchar *device;

	call_work_lock(ns);

	cw = call_work_lookup_unlocked(ns, "device", NULL, "RequestConfirmation");

	if (!cw) {
		call_work_unlock(ns);
		afb_req_fail(request, "failed", "No pairing in progress");
		return;
	}

	device = cw->agent_data.device_path;
	reply = device_call(ns, device, "CancelPairing", NULL, &error);

	if (!reply) {
		call_work_unlock(ns);
		afb_req_fail_f(request, "failed",
				"device %s method %s error %s",
				device, "CancelPairing", error->message);
		return;
	}

	call_work_unlock(ns);

	afb_req_success(request, json_object_new_object(),
			"Bluetooth - pairing canceled");
}

static void bluetooth_confirm_pairing(afb_req_t request)
{
	struct bluetooth_state *ns = bluetooth_get_userdata(request);
	struct call_work *cw;
	int pin = -1;

	const char *value = afb_req_value(request, "pincode");

	if (value)
		pin = (int)strtol(value, NULL, 10);

	if (!value || !pin) {
		afb_req_fail(request, "failed", "No pincode parameter");
		return;
	}

	call_work_lock(ns);

	cw = call_work_lookup_unlocked(ns, "device", NULL, "RequestConfirmation");

	if (!cw) {
		call_work_unlock(ns);
		afb_req_fail(request, "failed", "No pairing in progress");
		return;
	}

	if (pin == cw->agent_data.pin_code) {
		g_dbus_method_invocation_return_value(cw->invocation, NULL);

		afb_req_success(request, json_object_new_object(),
				"Bluetooth - pairing confimed");
	} else {
		g_dbus_method_invocation_return_dbus_error(cw->invocation,
				"org.bluez.Error.Rejected",
				"No connection pending");

		afb_req_fail(request, "failed", "Bluetooth - pairing failed");
	}

	call_work_destroy_unlocked(cw);
	call_work_unlock(ns);
}

static void bluetooth_remove_device(afb_req_t request)
{
	struct bluetooth_state *ns = bluetooth_get_userdata(request);
	GError *error = NULL;
	GVariant *reply;
	json_object *jval = NULL;
	const char *adapter;
	gchar *device;

	device = return_bluez_path(request);
	if (!device) {
		afb_req_fail(request, "failed", "No path given");
		return;
	}

	jval = bluez_get_property(ns, BLUEZ_AT_DEVICE, device, FALSE, "Adapter", &error);

	if (!jval) {
		afb_req_fail_f(request, "failed",
					" adapter not found for device %s error %s",
					device, error->message);

		g_error_free(error);
		goto out_free;
	}

	adapter = json_object_get_string(jval);

	reply = adapter_call(ns, adapter, "RemoveDevice",
			     g_variant_new("(o)", device), &error);

	if (!reply) {
		afb_req_fail_f(request, "failed",
					" device %s method %s error %s",
					device, "RemoveDevice", error->message);
		g_error_free(error);
		goto out_free;
	}
	g_variant_unref(reply);

	afb_req_success_f(request, json_object_new_object(),
			"Bluetooth - device %s removed", adapter);

out_free:
	if (!jval)
		json_object_put(jval);
	g_free(device);

}

static void bluetooth_avrcp_controls(afb_req_t request)
{
	struct bluetooth_state *ns = bluetooth_get_userdata(request);
	const char *action = afb_req_value(request, "action");
	gchar *device, *player = NULL;
	GVariant *reply;
	GError *error = NULL;
	json_object *jval = NULL;

	if (!action) {
		afb_req_fail(request, "failed", "No action given");
		return;
	}

	device = return_bluez_path(request);
	if (device) {
		/* TODO: handle multiple players per device */
		jval = bluez_get_property(ns, BLUEZ_AT_MEDIACONTROL, device, FALSE, "Player", NULL);
		if (jval) {
			player = (gchar *)json_object_get_string(jval);
			json_object_put(jval);
			jval = NULL;
		}
		if (!player)
			player = g_strconcat(device, "/", BLUEZ_DEFAULT_PLAYER, NULL);
		g_free(device);
	} else {
		player = g_strdup(ns->mediaplayer_path);
	}

	if (!player) {
		afb_req_fail(request, "failed", "No path given");
		return;
	}

	if (!g_strcmp0(action, "connect") || !g_strcmp0(action, "disconnect")) {
		mediaplayer1_connect_disconnect(ns, player, !!g_strcmp0(action, "disconnect"));
		goto out_success;
	}

	reply = mediaplayer_call(ns, player, action, NULL, &error);

	if (!reply) {
		afb_req_fail_f(request, "failed",
				"mediaplayer %s method %s error %s",
				player, action, BLUEZ_ERRMSG(error));
		g_free(player);
		g_error_free(error);
		return;
	}

out_success:
	g_free(player);
	afb_req_success(request, NULL, "Bluetooth - AVRCP controls");
}

static void bluetooth_pincode(afb_req_t request)
{
	char *error = NULL;
	const char *pincode;
	int rc;

	pincode = afb_req_value(request, "pincode");
	rc = set_pincode(afb_req_get_api(request), pincode, &error);

	if (rc) {
		afb_req_fail(request, "failed", error);
		return;
	}

	afb_req_success(request, NULL, "Bluetooth - pincode");
	return;
}

static const afb_verb_t bluetooth_verbs[] = {
	{
		.verb = "subscribe",
		.session = AFB_SESSION_NONE,
		.callback = bluetooth_subscribe,
		.info = "Subscribe to the event of 'value'",
	}, {
		.verb = "unsubscribe",
		.session = AFB_SESSION_NONE,
		.callback = bluetooth_unsubscribe,
		.info = "Unsubscribe to the event of 'value'",
	}, {
		.verb = "managed_objects",
		.session = AFB_SESSION_NONE,
		.callback = bluetooth_list,
		.info = "Retrieve managed bluetooth devices"
	}, {
		.verb = "adapter_state",
		.session = AFB_SESSION_NONE,
		.callback = bluetooth_adapter,
		.info = "Set adapter mode and retrieve properties"
	}, {
		.verb = "default_adapter",
		.session = AFB_SESSION_NONE,
		.callback = bluetooth_default_adapter,
		.info = "Set default adapter for commands"
	}, {
		.verb = "connect",
		.session = AFB_SESSION_NONE,
		.callback = bluetooth_connect_device,
		.info = "Connect device and/or profile"
	}, {
		.verb = "disconnect",
		.session = AFB_SESSION_NONE,
		.callback = bluetooth_disconnect_device,
		.info = "Disconnect device and/or profile"
	}, {
		.verb = "pair",
		.session = AFB_SESSION_NONE,
		.callback = bluetooth_pair_device,
		.info = "Pair device"
	}, {
		.verb = "cancel_pairing",
		.session = AFB_SESSION_NONE,
		.callback = bluetooth_cancel_pairing,
		.info = "Cancel pairing"
	}, {
		.verb = "confirm_pairing",
		.session = AFB_SESSION_NONE,
		.callback = bluetooth_confirm_pairing,
		.info = "Confirm pairing",
	}, {
		.verb = "remove_device",
		.session = AFB_SESSION_NONE,
		.callback = bluetooth_remove_device,
		.info = "Removed paired device",
	}, {
		.verb = "avrcp_controls",
		.session = AFB_SESSION_NONE,
		.callback = bluetooth_avrcp_controls,
		.info = "AVRCP controls"
	}, {
		.verb = "set_pincode",
		.session = AFB_SESSION_NONE,
		.callback = bluetooth_pincode,
		.info = "Set pincode for outgoing pairing"},
	{ } /* marker for end of the array */
};

/*
 * description of the binding for afb-daemon
 */
const afb_binding_t afbBindingV3 = {
	.api = "Bluetooth-Manager",
	.specification = "bluetooth manager API",
	.verbs = bluetooth_verbs,
	.init = init,
};