Merge "Add the exception case for audio initialize" into tizen
[platform/core/connectivity/bluetooth-frwk.git] / bt-service-adaptation / services / adapter / bt-service-core-adapter.c
1 /*
2  * Copyright (c) 2015 2016 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  * Contact: Anupam Roy <anupam.r@samsung.com>
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *              http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  */
19
20 #include <stdio.h>
21 #include <gio/gio.h>
22 #include <glib.h>
23 #include <dlog.h>
24 #include <string.h>
25 #include <vconf.h>
26 #include <vconf-internal-keys.h>
27 #include <bundle.h>
28 #include <bundle_internal.h>
29 #include <eventsystem.h>
30
31 #include "alarm.h"
32
33 /*bt-service headers */
34 #include "bt-internal-types.h"
35 #include "bt-service-common.h"
36 #include "bt-service-util.h"
37 #include "bt-service-main.h"
38 #include "bt-service-core-adapter.h"
39 #include "bt-service-core-device.h"
40 #include "bt-service-event-receiver.h"
41 #include "bt-request-handler.h"
42 #include "bt-service-event.h"
43 #include "bt-service-audio-common.h"
44 #include "bt-service-core-adapter-le.h"
45 #include "bt-service-gatt.h"
46
47 #ifdef TIZEN_FEATURE_BT_DPM
48 #include "bt-service-dpm.h"
49 #endif
50 #include "bt-service-hidhost.h"
51 #include "bt-service-hiddevice.h"
52 #include "bt-service-socket.h"
53 #include "bt-service-hdp.h"
54
55 /* OAL headers */
56 #include <oal-event.h>
57 #include <oal-manager.h>
58 #include <oal-adapter-mgr.h>
59
60 #ifdef TIZEN_FEATURE_BT_PAN_NAP
61 #include "bt-service-network.h"
62 #endif
63 /*This file will contain state machines related to adapter and remote device */
64
65 #include "bt-internal-types.h"
66
67 /* Global variables */
68 typedef struct {
69         guint event_id;
70         int timeout;
71         time_t start_time;
72         gboolean alarm_init;
73         int alarm_id;
74 } bt_adapter_timer_t;
75
76 static bt_adapter_timer_t visible_timer;
77
78 static guint timer_id = 0;
79
80 static gboolean a2dp_init_pending = FALSE;
81
82 /* Adapter default states */
83 static bt_status_t adapter_state = BT_DEACTIVATED;
84 static bt_adapter_discovery_state_t adapter_discovery_state = ADAPTER_DISCOVERY_STOPPED;
85
86 /* Forward declarations */
87 static void __bt_adapter_event_handler(int event_type, gpointer event_data);
88 static void __bt_post_oal_init(void);
89 static void __bt_handle_oal_initialisation(oal_event_t event);
90 static void __bt_adapter_handle_pending_requests(int service_function, void *user_data, unsigned int size);
91 static gboolean __bt_adapter_post_set_enabled(gpointer user_data);
92 static gboolean __bt_adapter_post_set_disabled(gpointer user_data);
93 static void __bt_adapter_update_bt_enabled(void);
94 static void __bt_adapter_update_bt_disabled(void);
95 static void __bt_adapter_state_set_status(bt_status_t status);
96 static void __bt_adapter_update_discovery_status(bt_adapter_discovery_state_t status);
97 static void __bt_adapter_state_change_callback(int bt_status);
98 static int __bt_adapter_state_handle_request(gboolean enable);
99 static int __bt_adapter_state_discovery_request(gboolean enable,
100                 unsigned short max_response, unsigned short duration, unsigned int mask,
101                 gboolean is_custom, bt_discovery_role_type_t role);
102 static void __bt_adapter_discovery_state_change_callback(int bt_discovery_status);
103 static gboolean __bt_is_service_request_present(int service_function);
104
105 static void __bt_set_visible_mode(void);
106 static void __bt_set_local_name(void);
107
108 /* Initialize BT stack (Initialize OAL layer) */
109 int _bt_stack_init(void)
110 {
111         int ret;
112
113         BT_INFO("[bt-service] Start to initialize BT stack");
114         /* Adapter enable request is successful, setup event handlers */
115         _bt_service_register_event_handler_callback(
116                         BT_ADAPTER_MODULE, __bt_adapter_event_handler);
117
118         ret = _bt_le_init();
119         if (ret != BLUETOOTH_ERROR_NONE) {
120                 BT_ERR("_bt_le_init Failed");
121                 return ret;
122         }
123
124         ret = oal_bt_init(_bt_service_oal_event_receiver);
125
126         if (OAL_STATUS_PENDING == ret) {
127                 BT_INFO("OAL Initialisation Pending, Profiles Init will be done once oal initialised...");
128                 return BLUETOOTH_ERROR_NONE;
129         } else if (OAL_STATUS_SUCCESS != ret) {
130                 _bt_service_unregister_event_handler_callback(BT_ADAPTER_MODULE);
131                 return BLUETOOTH_ERROR_INTERNAL;
132         }
133
134         return BLUETOOTH_ERROR_NONE;
135 }
136
137 int _bt_enable_adapter(void)
138 {
139         return __bt_adapter_state_handle_request(TRUE);
140 }
141
142 int _bt_enable_core(void)
143 {
144         /* TODO_40 : 4.0 merge  */
145         BT_INFO("Not Supported");
146         return BLUETOOTH_ERROR_NOT_SUPPORT;
147 }
148
149 int _bt_recover_adapter(void)
150 {
151         /* TODO_40 : 4.0 merge  */
152         BT_INFO("Not Supported");
153         return BLUETOOTH_ERROR_NOT_SUPPORT;
154 }
155
156 int _bt_reset_adapter(void)
157 {
158         BT_INFO("+");
159         if (OAL_STATUS_SUCCESS != adapter_reset())
160                 return BLUETOOTH_ERROR_INTERNAL;
161
162         /* TODO_40 : 4.0 merge  */
163         /* TODO Currently bt-service is not terminated in tizen next.
164            It should be handled in future patch */
165         if (_bt_adapter_get_status() == BT_DEACTIVATED)
166                 g_idle_add((GSourceFunc)_bt_terminate_service, NULL);
167
168         return BLUETOOTH_ERROR_NONE;
169 }
170
171 int _bt_check_adapter(int *status)
172 {
173         BT_INFO("+");
174         gboolean powered = FALSE;
175         BT_CHECK_PARAMETER(status, return);
176
177         *status = BT_ADAPTER_DISABLED;
178
179         if (OAL_STATUS_SUCCESS != adapter_get_powered_status(&powered))
180                 return BLUETOOTH_ERROR_INTERNAL;
181         else if (powered) {
182                 BT_INFO("Adapter is in Powered Up state");
183                 *status = BT_ADAPTER_ENABLED;
184         } else
185                 BT_INFO("Adapter is in Powered Down state");
186
187         return BLUETOOTH_ERROR_NONE;
188 }
189
190 int _bt_disable_adapter(void)
191 {
192         return __bt_adapter_state_handle_request(FALSE);
193 }
194
195 int _bt_start_discovery(unsigned short max_response,
196                 unsigned short duration, unsigned int cod_mask)
197 {
198         return __bt_adapter_state_discovery_request(TRUE, max_response, duration,
199                                 cod_mask, FALSE, 0x00);
200 }
201
202 int _bt_start_custom_discovery(bt_discovery_role_type_t role)
203 {
204         return __bt_adapter_state_discovery_request(TRUE, 0, 0, 0, TRUE, role);
205 }
206
207 int _bt_cancel_discovery(void)
208 {
209         return __bt_adapter_state_discovery_request(FALSE, 0, 0, 0, FALSE, 0x00);
210 }
211
212 gboolean _bt_is_discovering(void)
213 {
214         if (adapter_discovery_state == ADAPTER_DISCOVERY_STARTED
215                         || adapter_discovery_state == ADAPTER_DISCOVERY_STARTING)
216                 return TRUE;
217         else
218                 return FALSE;
219 }
220
221 int _bt_get_local_address(void)
222 {
223         int result;
224
225         BT_DBG("+");
226
227         result =  adapter_get_address();
228         if (result != OAL_STATUS_SUCCESS) {
229                 BT_ERR("adapter_get_address failed: %d", result);
230                 result = BLUETOOTH_ERROR_INTERNAL;
231         } else
232                 result = BLUETOOTH_ERROR_NONE;
233
234         BT_DBG("-");
235         return result;
236 }
237
238 int _bt_get_local_version(void)
239 {
240         int result;
241         BT_DBG("+");
242
243         result =  adapter_get_version();
244         if (result != OAL_STATUS_SUCCESS) {
245                 BT_ERR("adapter_get_version failed: %d", result);
246                 result = BLUETOOTH_ERROR_INTERNAL;
247         } else
248                 result = BLUETOOTH_ERROR_NONE;
249
250         BT_DBG("-");
251         return result;
252 }
253
254 int _bt_get_local_name(void)
255 {
256         int result;
257
258         BT_DBG("+");
259
260         result =  adapter_get_name();
261         if (result != OAL_STATUS_SUCCESS) {
262                 BT_ERR("adapter_get_name failed: %d", result);
263                 result = BLUETOOTH_ERROR_INTERNAL;
264         } else
265                 result = BLUETOOTH_ERROR_NONE;
266
267         BT_DBG("-");
268         return result;
269 }
270
271 int _bt_set_local_name(char *local_name)
272 {
273         int result = BLUETOOTH_ERROR_NONE;
274         BT_DBG("+");
275
276         retv_if(NULL == local_name, BLUETOOTH_ERROR_INVALID_PARAM);
277
278         result =  adapter_set_name(local_name);
279         if (result != OAL_STATUS_SUCCESS) {
280                 BT_ERR("adapter_set_name failed: %d", result);
281                 result = BLUETOOTH_ERROR_INTERNAL;
282         } else
283                 result = BLUETOOTH_ERROR_NONE;
284
285         BT_DBG("-");
286         return result;
287 }
288
289 int _bt_get_discoverable_mode(int *mode)
290 {
291         int scan_mode = 0;
292         int timeout = 0;
293
294         BT_DBG("+");
295
296         retv_if(NULL == mode, BLUETOOTH_ERROR_INVALID_PARAM);
297
298         adapter_is_discoverable(&scan_mode);
299         if (TRUE == scan_mode) {
300                 adapter_get_discoverable_timeout(&timeout);
301                 if (timeout > 0)
302                         *mode = BLUETOOTH_DISCOVERABLE_MODE_TIME_LIMITED_DISCOVERABLE;
303                 else
304                         *mode = BLUETOOTH_DISCOVERABLE_MODE_GENERAL_DISCOVERABLE;
305         } else {
306                 adapter_is_connectable(&scan_mode);
307                 if (scan_mode == TRUE)
308                         *mode = BLUETOOTH_DISCOVERABLE_MODE_CONNECTABLE;
309                 else {
310                         /*
311                          * TODO: NON CONNECTABLE is not defined in bluetooth_discoverable_mode_t.
312                          * After adding BLUETOOTH_DISCOVERABLE_MODE_NON_CONNECTABLE, set mode as
313                          * BLUETOOTH_DISCOVERABLE_MODE_NON_CONNECTABLE. Until then set -1.
314                          */
315                         *mode = -1;
316                 }
317         }
318
319         BT_DBG("-");
320         return BLUETOOTH_ERROR_NONE;
321 }
322
323 int _bt_get_timeout_value(int *timeout)
324 {
325         time_t current_time;
326         int time_diff;
327
328         /* Take current time */
329         time(&current_time);
330         time_diff = difftime(current_time, visible_timer.start_time);
331
332         BT_DBG("Time diff = %d\n", time_diff);
333         *timeout = visible_timer.timeout - time_diff;
334
335         return BLUETOOTH_ERROR_NONE;
336 }
337
338 static void __bt_visibility_alarm_remove()
339 {
340         if (visible_timer.event_id > 0) {
341                 g_source_remove(visible_timer.event_id);
342                 visible_timer.event_id = 0;
343         }
344
345         if (visible_timer.alarm_id > 0) {
346                 alarmmgr_remove_alarm(visible_timer.alarm_id);
347                 visible_timer.alarm_id = 0;
348         }
349 }
350
351 static int __bt_visibility_alarm_cb(alarm_id_t alarm_id, void* user_param)
352 {
353         int result = BLUETOOTH_ERROR_NONE;
354         int timeout = 0;
355
356         BT_DBG("__bt_visibility_alarm_cb - alram id = [%d] \n", alarm_id);
357
358         if (alarm_id != visible_timer.alarm_id)
359                 return 0;
360
361         if (visible_timer.event_id) {
362                 _bt_send_event(BT_ADAPTER_EVENT,
363                                 BLUETOOTH_EVENT_DISCOVERABLE_TIMEOUT_CHANGED,
364                                 g_variant_new("(in)", result, timeout));
365                 g_source_remove(visible_timer.event_id);
366                 visible_timer.event_id = 0;
367                 visible_timer.timeout = 0;
368
369                 if (!TIZEN_PROFILE_WEARABLE) {
370                         if (vconf_set_int(BT_FILE_VISIBLE_TIME, 0) != 0)
371                                 BT_ERR("Set vconf failed\n");
372                 }
373         }
374         /* Switch Off visibility in Bluez */
375         _bt_set_discoverable_mode(BLUETOOTH_DISCOVERABLE_MODE_CONNECTABLE, 0);
376         visible_timer.alarm_id = 0;
377         return 0;
378 }
379
380 static gboolean __bt_timeout_handler(gpointer user_data)
381 {
382         int result = BLUETOOTH_ERROR_NONE;
383         time_t current_time;
384         int time_diff;
385
386         /* Take current time */
387         time(&current_time);
388         time_diff = difftime(current_time, visible_timer.start_time);
389
390         /* Send event to application */
391         _bt_send_event(BT_ADAPTER_EVENT,
392                         BLUETOOTH_EVENT_DISCOVERABLE_TIMEOUT_CHANGED,
393                         g_variant_new("(in)", result, time_diff));
394
395         if (visible_timer.timeout <= time_diff) {
396                 g_source_remove(visible_timer.event_id);
397                 visible_timer.event_id = 0;
398                 visible_timer.timeout = 0;
399
400                 if (!TIZEN_PROFILE_WEARABLE) {
401                         if (vconf_set_int(BT_FILE_VISIBLE_TIME, 0) != 0)
402                                 BT_ERR("Set vconf failed\n");
403                 }
404
405                 return FALSE;
406         }
407
408         return TRUE;
409 }
410
411 static void __bt_visibility_alarm_create()
412 {
413         alarm_id_t alarm_id;
414         int result;
415
416         result = alarmmgr_add_alarm(ALARM_TYPE_VOLATILE, visible_timer.timeout,
417                         0, NULL, &alarm_id);
418         if (result < 0) {
419                 BT_ERR("Failed to create alarm error = %d\n", result);
420         } else {
421                 BT_DBG("Alarm created = %d\n", alarm_id);
422                 visible_timer.alarm_id = alarm_id;
423         }
424 }
425
426 int _bt_start_visibility_timer(int timeout)
427 {
428         int result;
429 #ifdef TIZEN_FEATURE_BT_DPM
430         int discoverable_state = DPM_BT_ERROR;
431 #endif
432
433         __bt_visibility_alarm_remove();
434
435         visible_timer.timeout = timeout;
436
437 #ifdef TIZEN_FEATURE_BT_DPM
438         _bt_dpm_get_bluetooth_limited_discoverable_state(&discoverable_state);
439         if (discoverable_state != DPM_RESTRICTED) {
440 #endif
441                 if (vconf_set_int(BT_FILE_VISIBLE_TIME, timeout) != 0)
442                         BT_ERR("Set vconf failed");
443 #ifdef TIZEN_FEATURE_BT_DPM
444         }
445 #endif
446
447         if (timeout <= 0)
448                 return BLUETOOTH_ERROR_NONE;
449
450         if (!visible_timer.alarm_init) {
451                 /* Set Alarm timer to switch off BT */
452                 result = alarmmgr_init("bt-service");
453                 if (result != 0)
454                         return BLUETOOTH_ERROR_INTERNAL;
455
456                 visible_timer.alarm_init = TRUE;
457         }
458
459         result = alarmmgr_set_cb(__bt_visibility_alarm_cb, NULL);
460         if (result != 0)
461                 return BLUETOOTH_ERROR_INTERNAL;
462
463         if (!TIZEN_PROFILE_WEARABLE) {
464                 if (vconf_set_int(BT_FILE_VISIBLE_TIME, timeout) != 0)
465                         BT_ERR("Set vconf failed");
466         }
467
468         /* Take start time */
469         time(&(visible_timer.start_time));
470         visible_timer.event_id = g_timeout_add_seconds(1,
471                         __bt_timeout_handler, NULL);
472
473         visible_timer.timeout = timeout;
474
475         __bt_visibility_alarm_create();
476
477         return BLUETOOTH_ERROR_NONE;
478 }
479
480 int _bt_stop_visibility_timer(void)
481 {
482         __bt_visibility_alarm_remove();
483
484         visible_timer.timeout = 0;
485
486         if (!TIZEN_PROFILE_WEARABLE) {
487                 if (vconf_set_int(BT_FILE_VISIBLE_TIME, 0) != 0)
488                         BT_ERR("Set vconf failed");
489         }
490
491         return BLUETOOTH_ERROR_NONE;
492 }
493
494 int _bt_set_discoverable_mode(int discoverable_mode, int timeout)
495 {
496         int result;
497         int ret = BLUETOOTH_ERROR_NONE;;
498 #ifdef TIZEN_FEATURE_BT_DPM
499         int discoverable_state = DPM_BT_ERROR;
500 #endif
501
502         BT_DBG("+");
503
504         BT_INFO("discoverable_mode: %d, timeout: %d", discoverable_mode, timeout);
505
506 #ifdef TIZEN_FEATURE_BT_DPM
507         _bt_dpm_get_bluetooth_limited_discoverable_state(&discoverable_state);
508         if (discoverable_mode != BLUETOOTH_DISCOVERABLE_MODE_CONNECTABLE &&
509                  discoverable_state == DPM_RESTRICTED) {
510                 if (headed_plugin_info->plugin_headed_enabled)
511                         headed_plugin_info->headed_plugin->bt_launch_dpmpopup("DPM_POLICY_DISABLE_BT_HANDSFREE");
512                 return BLUETOOTH_ERROR_ACCESS_DENIED;
513         }
514         if (discoverable_mode == BLUETOOTH_DISCOVERABLE_MODE_TIME_LIMITED_DISCOVERABLE &&
515                 discoverable_state == DPM_RESTRICTED) {
516                 if (headed_plugin_info->plugin_headed_enabled)
517                         headed_plugin_info->headed_plugin->bt_launch_dpmpopup("DPM_POLICY_DISABLE_BT");
518                 return BLUETOOTH_ERROR_ACCESS_DENIED;
519         }
520 #endif
521
522         switch (discoverable_mode) {
523         case BLUETOOTH_DISCOVERABLE_MODE_CONNECTABLE:
524                 result = adapter_set_connectable(TRUE);
525                 timeout = 0;
526                 break;
527         case BLUETOOTH_DISCOVERABLE_MODE_GENERAL_DISCOVERABLE:
528                 result = adapter_set_discoverable();
529                 timeout = 0;
530                 break;
531         case BLUETOOTH_DISCOVERABLE_MODE_TIME_LIMITED_DISCOVERABLE:
532                 result = adapter_set_discoverable();
533                 break;
534         default:
535                 return BLUETOOTH_ERROR_INVALID_PARAM;
536         }
537
538         if (result != OAL_STATUS_SUCCESS) {
539                 BT_ERR("set scan mode failed %d", result);
540                 return BLUETOOTH_ERROR_INTERNAL;
541         }
542
543         result = adapter_set_discoverable_timeout(timeout);
544         if (result != OAL_STATUS_SUCCESS) {
545                 BT_ERR("adapter_set_discoverable_timeout failed %d", result);
546                 return BLUETOOTH_ERROR_INTERNAL;
547         }
548
549         if (discoverable_mode == BLUETOOTH_DISCOVERABLE_MODE_GENERAL_DISCOVERABLE) {
550                 ret = _bt_stop_visibility_timer();
551                 if (BLUETOOTH_ERROR_NONE != ret)
552                         BT_ERR("_bt_stop_visibility_timer failed");
553                 if (!TIZEN_PROFILE_WEARABLE) {
554                         if (vconf_set_int(BT_FILE_VISIBLE_TIME, -1) != 0)
555                                  BT_ERR("Set vconf failed");
556                 }
557         } else if (discoverable_mode == BLUETOOTH_DISCOVERABLE_MODE_TIME_LIMITED_DISCOVERABLE) {
558                 ret = _bt_start_visibility_timer(timeout);
559                 if (BLUETOOTH_ERROR_NONE != ret)
560                         BT_ERR("_bt_start_visibility_timer failed");
561
562         } else {
563                 ret = _bt_stop_visibility_timer();
564                 if (BLUETOOTH_ERROR_NONE != ret)
565                         BT_ERR("_bt_stop_visibility_timer failed");
566         }
567
568         BT_DBG("-");
569         return result;
570 }
571
572 gboolean _bt_is_connectable(void)
573 {
574         int connectable = 0;
575         int result;
576
577         BT_DBG("+");
578
579         adapter_is_connectable(&connectable);
580         if (connectable)
581                 result = TRUE;
582         else
583                 result = FALSE;
584
585         BT_DBG("Connectable: [%s]", result ? "TRUE" : "FALSE");
586         BT_DBG("-");
587         return result;
588 }
589
590 int _bt_set_connectable(gboolean connectable)
591 {
592         int result = BLUETOOTH_ERROR_NONE;
593
594         BT_DBG("+");
595         result =  adapter_set_connectable(connectable);
596         if (result != OAL_STATUS_SUCCESS) {
597                 BT_ERR("adapter_set_connectable failed: %d", result);
598                 result = BLUETOOTH_ERROR_INTERNAL;
599         } else
600                 result = BLUETOOTH_ERROR_NONE;
601
602         BT_DBG("-");
603         return result;
604 }
605
606 int _bt_is_service_used(void)
607 {
608         int result;
609
610         BT_DBG("+");
611
612         result =  adapter_get_service_uuids();
613         if (result != OAL_STATUS_SUCCESS) {
614                 BT_ERR("adapter_get_service_uuids failed: %d", result);
615                 result = BLUETOOTH_ERROR_INTERNAL;
616         } else {
617                 result = BLUETOOTH_ERROR_NONE;
618         }
619
620         BT_DBG("-");
621         return result;
622 }
623
624 int _bt_adapter_get_bonded_devices(void)
625 {
626         int result = BLUETOOTH_ERROR_NONE;
627
628         BT_DBG("+");
629         result =  adapter_get_bonded_devices();
630         if (result != OAL_STATUS_SUCCESS) {
631                 BT_ERR("adapter_get_bonded_devices failed: %d", result);
632                 result = BLUETOOTH_ERROR_INTERNAL;
633         } else
634                 result = BLUETOOTH_ERROR_NONE;
635
636         BT_DBG("-");
637         return result;
638 }
639
640 int _bt_get_profile_connected_devices(char *profile_uuid, GArray **addr_list)
641 {
642         BT_DBG("+");
643         GDBusConnection *conn;
644         GDBusProxy *manager_proxy;
645         GVariant *result = NULL;
646         GVariant *result1 = NULL;
647         GVariantIter *iter = NULL;
648         GError *error = NULL;
649         char *object_path = NULL;
650         GVariantIter *interface_iter;
651         char *interface_str = NULL;
652         GDBusProxy *device_proxy = NULL;
653         gboolean is_connected = FALSE;
654
655         conn = _bt_gdbus_get_system_gconn();
656         retv_if(conn == NULL, BLUETOOTH_ERROR_INTERNAL);
657
658         manager_proxy = _bt_get_manager_proxy();
659         retv_if(manager_proxy == NULL, BLUETOOTH_ERROR_INTERNAL);
660
661         result = g_dbus_proxy_call_sync(manager_proxy, "GetManagedObjects",
662                         NULL,
663                         G_DBUS_CALL_FLAGS_NONE,
664                         -1,
665                         NULL,
666                         NULL);
667
668         if (!result) {
669                 if (error != NULL) {
670                         BT_ERR("Failed to GetManagedObjects (Error: %s)", error->message);
671                         g_clear_error(&error);
672                         error = NULL;
673                 } else
674                         BT_ERR("Failed to Failed to GetManagedObjects");
675                 return BLUETOOTH_ERROR_INTERNAL;
676         }
677
678         /* signature of GetManagedObjects:  a{oa{sa{sv}}} */
679         g_variant_get(result, "(a{oa{sa{sv}}})", &iter);
680
681         /* Parse the signature:  oa{sa{sv}}} */
682         while (g_variant_iter_loop(iter, "{&oa{sa{sv}}}", &object_path, &interface_iter)) {
683                 if (object_path == NULL)
684                         continue;
685
686                 while (g_variant_iter_loop(interface_iter, "{sa{sv}}",
687                                         &interface_str, NULL)) {
688                         if (g_strcmp0(interface_str, "org.bluez.Device1") == 0) {
689                                 BT_DBG("Found a device: %s", object_path);
690                                 g_free(interface_str);
691
692                                 device_proxy = g_dbus_proxy_new_sync(conn, G_DBUS_PROXY_FLAGS_NONE,
693                                                 NULL, BT_BLUEZ_NAME,
694                                                 object_path, BT_DEVICE_INTERFACE,  NULL, NULL);
695
696                                 if (device_proxy == NULL) {
697                                         BT_DBG("Device don't have this service");
698                                         break;
699                                 }
700
701                                 result1 = g_dbus_proxy_call_sync(device_proxy, "IsConnectedProfile",
702                                                 g_variant_new("(s)", profile_uuid),
703                                                 G_DBUS_CALL_FLAGS_NONE,
704                                                 -1,
705                                                 NULL,
706                                                 &error);
707
708                                 if (result1 == NULL) {
709                                         BT_ERR("Error occured in Proxy call");
710                                         if (error) {
711                                                 BT_ERR("Error occured in Proxy call [%s]\n", error->message);
712                                                 g_error_free(error);
713                                                 error = NULL;
714                                         }
715                                         g_object_unref(device_proxy);
716                                         break;
717                                 }
718                                 g_variant_get(result1, "(b)", &is_connected);
719
720                                 if (is_connected == TRUE) {
721                                         char address[BT_ADDRESS_STRING_SIZE];
722                                         bluetooth_device_address_t *addr = NULL;
723
724                                         _bt_convert_device_path_to_address(object_path, address);
725
726                                         addr = g_malloc0(sizeof(bluetooth_device_address_t));
727                                         _bt_convert_addr_string_to_type(addr->addr, address);
728
729                                         g_array_append_vals(*addr_list, addr,
730                                                         sizeof(bluetooth_device_address_t));
731                                 }
732
733                                 g_variant_unref(result1);
734                                 g_object_unref(device_proxy);
735
736                                 break;
737                         }
738                 }
739         }
740
741         g_variant_unref(result);
742         g_variant_iter_free(iter);
743
744         BT_DBG("-");
745         return BLUETOOTH_ERROR_NONE;
746 }
747
748 static void __bt_handle_pending_a2dp_init(service_uuid_t *service_list, unsigned int count)
749 {
750         int ret;
751         unsigned int i;
752         unsigned char *uuid;
753         char uuid_str[BT_UUID_STRING_SIZE];
754
755         if (!a2dp_init_pending)
756                 return;
757
758         BT_DBG("+");
759         a2dp_init_pending = FALSE;
760         for (i = 0; i < count; i++) {
761                 uuid = service_list[i].uuid;
762                 _bt_service_convert_uuid_type_to_string(uuid_str, uuid);
763                 BT_INFO("Adapter Service: [%s]", uuid_str);
764                 if (!strcasecmp(uuid_str, A2DP_SINK_UUID)) {
765                         BT_INFO("Enable A2DP Sink role");
766                         /* Initialize A2DP Sink */
767                         ret = _bt_audio_initialize(BT_A2DP_SINK_MODULE);
768                         if (ret != BLUETOOTH_ERROR_NONE)
769                                 BT_ERR("_bt_audio_initialize(BT_A2DP_SINK_MODULE) Failed");
770
771                         /* Initialize AVRCP Controller */
772                         ret = _bt_audio_initialize(BT_AVRCP_CTRL_MODULE);
773                         if (ret != BLUETOOTH_ERROR_NONE)
774                                 BT_ERR("_bt_audio_initialize(BT_AVRCP_CTRL_MODULE) Failed");
775
776                         _bt_audio_set_current_role(BLUETOOTH_A2DP_SINK);
777                         return;
778                 }
779         }
780
781         BT_INFO("Enable A2DP Source role by default");
782         /* Initialize A2DP Source */
783         ret = _bt_audio_initialize(BT_A2DP_SOURCE_MODULE);
784         if (ret != BLUETOOTH_ERROR_NONE)
785                 BT_ERR("_bt_audio_initialize(BT_A2DP_SOURCE_MODULE) Failed");
786
787         /* Initialize AVRCP Target */
788         ret = _bt_audio_initialize(BT_AVRCP_MODULE);
789         if (ret != BLUETOOTH_ERROR_NONE)
790                 BT_ERR("_bt_audio_initialize(BT_AVRCP_MODULE) Failed");
791
792         _bt_audio_set_current_role(BLUETOOTH_A2DP_SOURCE);
793         BT_DBG("-");
794 }
795
796 static void __bt_adapter_event_handler(int event_type, gpointer event_data)
797 {
798         int result = BLUETOOTH_ERROR_NONE;
799
800         BT_DBG("+");
801
802         switch (event_type) {
803         case OAL_EVENT_OAL_INITIALISED_SUCCESS:
804         case OAL_EVENT_OAL_INITIALISED_FAILED:
805                 __bt_handle_oal_initialisation(event_type);
806                 break;
807         case OAL_EVENT_ADAPTER_ENABLED:
808                 __bt_adapter_state_change_callback(BT_ACTIVATED);
809                 break;
810         case OAL_EVENT_ADAPTER_DISABLED:
811                 __bt_adapter_state_change_callback(BT_DEACTIVATED);
812                 break;
813         case OAL_EVENT_ADAPTER_INQUIRY_STARTED:
814                 __bt_adapter_discovery_state_change_callback(ADAPTER_DISCOVERY_STARTED);
815                 break;
816         case OAL_EVENT_ADAPTER_INQUIRY_FINISHED:
817                 __bt_adapter_discovery_state_change_callback(ADAPTER_DISCOVERY_STOPPED);
818                 break;
819         case OAL_EVENT_ADAPTER_PROPERTY_ADDRESS: {
820                 bt_address_t *bd_addr = event_data;
821                 bluetooth_device_address_t local_address;
822
823                 /* Copy data */
824                 memcpy(local_address.addr, bd_addr->addr, BT_ADDRESS_LENGTH_MAX);
825                 BT_DBG("Adapter address: [%2.2X:%2.2X:%2.2X:%2.2X:%2.2X:%2.2X]",
826                                 local_address.addr[0], local_address.addr[1], local_address.addr[2],
827                                 local_address.addr[3], local_address.addr[4], local_address.addr[5]);
828
829                 __bt_adapter_handle_pending_requests(BT_GET_LOCAL_ADDRESS,
830                                 (void *) &local_address, sizeof(bluetooth_device_address_t));
831                 break;
832         }
833         case OAL_EVENT_ADAPTER_PROPERTY_NAME: {
834                 char *name = event_data;
835                 BT_DBG("Adapter Name: %s", name);
836
837                 if (__bt_is_service_request_present(BT_GET_LOCAL_NAME)) {
838                         bluetooth_device_name_t local_name;
839
840                         memset(&local_name, 0x00, sizeof(bluetooth_device_name_t));
841                         g_strlcpy(local_name.name,
842                                 (const gchar *)name, BLUETOOTH_DEVICE_NAME_LENGTH_MAX);
843                         __bt_adapter_handle_pending_requests(BT_GET_LOCAL_NAME,
844                                 (void *) &local_name, sizeof(bluetooth_device_name_t));
845                 } else {
846                         /* Send event to application */
847                         _bt_send_event(BT_ADAPTER_EVENT,
848                                         BLUETOOTH_EVENT_LOCAL_NAME_CHANGED,
849                                         g_variant_new("(is)", result, name));
850                 }
851                 break;
852         }
853         case OAL_EVENT_ADAPTER_PROPERTY_VERSION: {
854                 char *ver = event_data;
855                 bluetooth_version_t local_version;
856
857                 memset(&local_version, 0x00, sizeof(bluetooth_version_t));
858                 g_strlcpy(local_version.version,
859                                 (const gchar *)ver, BLUETOOTH_VERSION_LENGTH_MAX);
860                 BT_DBG("BT Version: %s", local_version.version);
861
862                 __bt_adapter_handle_pending_requests(BT_GET_LOCAL_VERSION,
863                                 (void *) &local_version, sizeof(bluetooth_version_t));
864                 break;
865         }
866         case OAL_EVENT_ADAPTER_MODE_NON_CONNECTABLE: {
867                 int mode = -1;
868                 gboolean connectable = FALSE;
869
870                 BT_INFO("Adapter discoverable mode:"
871                                 " BLUETOOTH_DISCOVERABLE_MODE_NON_CONNECTABLE");
872                 _bt_send_event(BT_ADAPTER_EVENT,
873                                 BLUETOOTH_EVENT_CONNECTABLE_CHANGED,
874                                 g_variant_new("(b)", connectable));
875
876                 _bt_send_event(BT_ADAPTER_EVENT,
877                                 BLUETOOTH_EVENT_DISCOVERABLE_MODE_CHANGED,
878                                 g_variant_new("(in)", result, mode));
879                 break;
880         }
881         case OAL_EVENT_ADAPTER_MODE_CONNECTABLE: {
882                 int mode;
883                 gboolean connectable = TRUE;
884
885                 BT_INFO("Adapter discoverable mode:"
886                                 " BLUETOOTH_DISCOVERABLE_MODE_CONNECTABLE");
887                 _bt_send_event(BT_ADAPTER_EVENT,
888                                 BLUETOOTH_EVENT_CONNECTABLE_CHANGED,
889                                 g_variant_new("(b)", connectable));
890
891                 mode = BLUETOOTH_DISCOVERABLE_MODE_CONNECTABLE;
892                 _bt_send_event(BT_ADAPTER_EVENT,
893                                 BLUETOOTH_EVENT_DISCOVERABLE_MODE_CHANGED,
894                                 g_variant_new("(in)", result, mode));
895                 break;
896         }
897         case OAL_EVENT_ADAPTER_MODE_DISCOVERABLE: {
898                 int mode;
899
900                 BT_INFO("Adapter discoverable mode:"
901                                 " BLUETOOTH_DISCOVERABLE_MODE_GENERAL_DISCOVERABLE");
902
903                 /* Send event to application */
904                 mode = BLUETOOTH_DISCOVERABLE_MODE_GENERAL_DISCOVERABLE;
905                 _bt_send_event(BT_ADAPTER_EVENT,
906                                 BLUETOOTH_EVENT_DISCOVERABLE_MODE_CHANGED,
907                                 g_variant_new("(in)", result, mode));
908
909                 break;
910         }
911         case OAL_EVENT_ADAPTER_MODE_DISCOVERABLE_TIMEOUT: {
912                 int *timeout = event_data;
913                 int mode;
914
915                 BT_INFO("Discoverable timeout: [%d]", *timeout);
916
917                 /* Send event to application */
918                 _bt_get_discoverable_mode(&mode);
919                 _bt_send_event(BT_ADAPTER_EVENT,
920                                 BLUETOOTH_EVENT_DISCOVERABLE_MODE_CHANGED,
921                                 g_variant_new("(in)", result, mode));
922                 break;
923         }
924         case OAL_EVENT_ADAPTER_PROPERTY_SERVICES: {
925                 int count;
926                 service_uuid_t *service_list;
927                 event_adapter_services_t *list = event_data;
928
929                 count = list->num;
930                 service_list = list->service_list;
931                 __bt_handle_pending_a2dp_init(service_list, count);
932                 __bt_adapter_handle_pending_requests(BT_IS_SERVICE_USED, service_list, count);
933                 break;
934         }
935         case OAL_EVENT_ADAPTER_BONDED_DEVICE_LIST: {
936                 int i;
937                 int count;
938                 bluetooth_device_address_t *addr_list;
939
940                 event_device_list_t *bonded_device_list = event_data;
941                 count = bonded_device_list->num;
942
943                 addr_list = g_malloc0(count * sizeof(bluetooth_device_address_t));
944                 for (i = 0; i < count; i++) {
945                         memcpy(addr_list[i].addr,
946                                         bonded_device_list->devices[i].addr,
947                                         BLUETOOTH_ADDRESS_LENGTH);
948                 }
949
950                 BT_INFO("Adapter Bonded device List count: [%d]", count);
951                 _bt_device_handle_paired_address_list(addr_list, bonded_device_list->num);
952                 g_free(addr_list);
953                 break;
954         }
955         default:
956                 BT_ERR("Unhandled event..");
957                 break;
958         }
959
960         BT_DBG("-");
961 }
962
963 int _bt_init_profiles()
964 {
965         int ret;
966         BT_INFO("+");
967
968         /*TODO: Init bluetooth profiles */
969         ret = _bt_hidhost_initialize();
970         if (ret != BLUETOOTH_ERROR_NONE)
971                 BT_ERR("_bt_hidhost_initialize Failed");
972
973         ret = _bt_hiddevice_initialize();
974         if (ret != BLUETOOTH_ERROR_NONE)
975                 BT_ERR("_bt_hiddevice_initialize Failed");
976
977         ret = _bt_socket_init();
978         if (ret != BLUETOOTH_ERROR_NONE)
979                 BT_ERR("_bt_socket_init Failed");
980
981         /*
982          * Query local adapter services and based on a2dp service uuids initialized
983          * in bluetooth stack, enable A2DP sourec or A2DP sink role.
984          */
985         ret =  adapter_get_service_uuids();
986         if (ret != OAL_STATUS_SUCCESS)
987                 BT_ERR("adapter_get_service_uuids failed: %d", ret);
988         else
989                 a2dp_init_pending = TRUE;
990
991
992         /* Initialize HFP Audio Gateway */
993         ret = _bt_audio_initialize(BT_AG_MODULE);
994         if (ret != BLUETOOTH_ERROR_NONE)
995                 BT_ERR("_bt_audio_initialize(BT_AG_MODULE) Failed");
996
997         /* Registering callback for receiving audio services searched */
998         ret = _bt_audio_initialize(BT_AUDIO_ALL_MODULE);
999         if (ret != BLUETOOTH_ERROR_NONE)
1000                 BT_ERR("_bt_audio_initialize(BT_AUDIO_ALL_MODULE) Failed");
1001
1002         ret = _bt_hdp_init();
1003         if (ret != BLUETOOTH_ERROR_NONE)
1004                 BT_ERR("_bt_hdp_init Failed");
1005
1006         ret = _bt_gatt_init();
1007         if (ret != BLUETOOTH_ERROR_NONE)
1008                 BT_ERR("_bt_gatt_init Failed");
1009
1010         /* Initialize HF Client */
1011         ret = _bt_audio_initialize(BT_HFP_MODULE);
1012         if (ret != BLUETOOTH_ERROR_NONE)
1013                 BT_ERR("_bt_audio_initialize(BT_HFP_MODULE) Failed");
1014
1015         return BLUETOOTH_ERROR_NONE;
1016 }
1017
1018 int _bt_cleanup_profiles(void)
1019 {
1020         /* TODO: Cleanup bluetooth profiles */
1021         _bt_hidhost_deinitialize();
1022         _bt_socket_deinit();
1023 #if 0
1024         /* TODO: Cleanup bluetooth audio profiles */
1025         //_bt_audio_deinitialize(BT_A2DP_SOURCE_MODULE);
1026         //_bt_audio_deinitialize(BT_AVRCP_MODULE);
1027         //_bt_audio_deinitialize(BT_A2DP_SINK_MODULE);
1028         //_bt_audio_deinitialize(BT_AG_MODULE);
1029         //_bt_audio_deinitialize(BT_AVRCP_CTRL_MODULE);
1030         //_bt_audio_deinitialize(BT_AUDIO_ALL_MODULE);
1031 #endif
1032         _bt_hdp_deinit();
1033         _bt_gatt_deinit();
1034
1035         return BLUETOOTH_ERROR_NONE;
1036 }
1037
1038 /* OAL post initialization handler */
1039 static void __bt_post_oal_init(void)
1040 {
1041         int ret;
1042         int status = VCONFKEY_BT_STATUS_OFF;
1043
1044         BT_DBG("OAL initialized");
1045         if (vconf_get_int(VCONFKEY_BT_STATUS, &status) != 0)
1046                 BT_ERR("Fail to get the enabled value");
1047
1048 #if 0
1049         /* Update Bluetooth Status to OFF */
1050         if (vconf_set_int(VCONFKEY_BT_STATUS, VCONFKEY_BT_STATUS_OFF) != 0)
1051                 BT_ERR("Set vconf failed\n");
1052 #endif
1053
1054         if (status & VCONFKEY_BT_STATUS_ON) {
1055                 ret = _bt_enable_adapter();
1056                 if (ret != BLUETOOTH_ERROR_NONE)
1057                         BT_ERR("_bt_enable_adapter failed with error: %d", ret);
1058         }
1059 }
1060
1061 /* OAL initialization handler */
1062 static void __bt_handle_oal_initialisation(oal_event_t event)
1063 {
1064         BT_DBG("");
1065
1066         switch (event) {
1067         case OAL_EVENT_OAL_INITIALISED_SUCCESS:
1068                 __bt_post_oal_init();
1069                 break;
1070         case OAL_EVENT_OAL_INITIALISED_FAILED:
1071                 BT_ERR("OAL Initialisation Failed, terminate bt-service daemon..");
1072                 g_idle_add(_bt_terminate_service, NULL);
1073                 break;
1074         default:
1075                 BT_ERR("Unknown Event");
1076                 break;
1077         }
1078 }
1079
1080 static gboolean __bt_is_service_request_present(int service_function)
1081 {
1082         GSList *l;
1083         invocation_info_t *req_info;
1084
1085         BT_DBG("+");
1086
1087         /* Get method invocation context */
1088         for (l = _bt_get_invocation_list(); l != NULL; l = g_slist_next(l)) {
1089                 req_info = l->data;
1090                 if (req_info && req_info->service_function == service_function)
1091                         return TRUE;
1092         }
1093
1094         BT_DBG("-");
1095         return FALSE;
1096 }
1097
1098 /* Internal functions of core adapter service */
1099 static void __bt_adapter_handle_pending_requests(int service_function, void *user_data, unsigned int size)
1100 {
1101         GSList *l;
1102         GArray *out_param;
1103         invocation_info_t *req_info;
1104         BT_INFO("+");
1105
1106         /* Get method invocation context */
1107         for (l = _bt_get_invocation_list(); l != NULL; ) {
1108                 req_info = l->data;
1109                 l = g_slist_next(l);
1110                 if (req_info == NULL || req_info->service_function != service_function)
1111                         continue;
1112
1113                 /* Create out param */
1114                 out_param = g_array_new(FALSE, FALSE, sizeof(gchar));
1115
1116                 switch (service_function) {
1117                 case BT_ENABLE_ADAPTER:
1118                 case BT_DISABLE_ADAPTER: {
1119                         gboolean done = TRUE;
1120                         g_array_append_vals(out_param, &done, sizeof(gboolean));
1121                         break;
1122                 }
1123                 case BT_GET_LOCAL_NAME:
1124                 case BT_GET_LOCAL_ADDRESS:
1125                 case BT_GET_LOCAL_VERSION:
1126                         g_array_append_vals(out_param, user_data, size);
1127                         break;
1128                 case BT_IS_SERVICE_USED: {
1129                         unsigned int i;
1130                         gboolean used = FALSE;
1131                         unsigned char *uuid;
1132                         char uuid_str[BT_UUID_STRING_SIZE];
1133                         char *request_uuid = req_info->user_data;
1134                         service_uuid_t *service_list = user_data;
1135
1136                         BT_INFO("Check for service uuid: %s", request_uuid);
1137                         for (i = 0; i < size; i++) {
1138                                 uuid = service_list[i].uuid;
1139                                 _bt_service_convert_uuid_type_to_string(uuid_str, uuid);
1140                                 BT_INFO("Adapter Service: [%s]", uuid_str);
1141                                 if (strcasecmp(uuid_str, request_uuid) == 0) {
1142                                         BT_INFO("UUID matched!!");
1143                                         used = TRUE;
1144                                         break;
1145                                 }
1146                         }
1147
1148                         g_array_append_vals(out_param, &used, sizeof(gboolean));
1149                         break;
1150                 }
1151                 default:
1152                         BT_ERR("Unknown service function[%d]", service_function);
1153                 }
1154
1155                 _bt_service_method_return(req_info->context, out_param, req_info->result);
1156                 g_array_free(out_param, TRUE);
1157                 /* Now free invocation info for this request*/
1158                 _bt_free_info_from_invocation_list(req_info);
1159         }
1160 }
1161
1162 static void __bt_phone_name_changed_cb(keynode_t *node, void *data)
1163 {
1164         char *phone_name = NULL;
1165         char *ptr = NULL;
1166
1167         if (node == NULL)
1168                 return;
1169
1170         if (vconf_keynode_get_type(node) == VCONF_TYPE_STRING) {
1171                 phone_name = vconf_keynode_get_str(node);
1172
1173                 if (phone_name && strlen(phone_name) != 0) {
1174                         if (!g_utf8_validate(phone_name, -1,
1175                                         (const char **)&ptr))
1176                                 *ptr = '\0';
1177
1178                         _bt_set_local_name(phone_name);
1179                 }
1180         }
1181 }
1182
1183 /* Request return handlings */
1184 static gboolean __bt_adapter_post_set_enabled(gpointer user_data)
1185 {
1186         BT_INFO("__bt_adapter_post_set_enabled>>");
1187
1188         if (TIZEN_PROFILE_TV || !headed_plugin_info->plugin_headed_enabled) {
1189                 if (BLUETOOTH_ERROR_NONE != _bt_set_discoverable_mode(
1190                                 BLUETOOTH_DISCOVERABLE_MODE_GENERAL_DISCOVERABLE, 0))
1191                         BT_ERR("Fail to set discoverable mode");
1192         } else {
1193                 __bt_set_visible_mode();
1194         }
1195
1196         /* add the vconf noti handler */
1197         if (0 != vconf_notify_key_changed(VCONFKEY_SETAPPL_DEVICE_NAME_STR,
1198                         (vconf_callback_fn)__bt_phone_name_changed_cb, NULL))
1199                 BT_ERR("DEVICE_NAME key changed notification registration failed");
1200
1201         __bt_set_local_name();
1202
1203         /* Get All properties */
1204         if (OAL_STATUS_SUCCESS != adapter_get_properties())
1205                 BT_ERR("adapter_get_properties failed");
1206
1207         /* Add Adapter enabled post processing codes */
1208         return FALSE;
1209 }
1210
1211 static gboolean __bt_adapter_post_set_disabled(gpointer user_data)
1212 {
1213         BT_INFO("_bt_adapter_post_set_disabled>>");
1214
1215         if (!TIZEN_PROFILE_TV) {
1216                 /* Add Adapter disabled post processing codes */
1217                 if (vconf_ignore_key_changed(VCONFKEY_SETAPPL_DEVICE_NAME_STR,
1218                                 (vconf_callback_fn)__bt_phone_name_changed_cb) != 0)
1219                         BT_ERR("vconf_ignore_key_changed failed");
1220         }
1221
1222         /* bt-service should be terminated when BT is off */
1223         if (!TIZEN_FEATURE_BT_USB_DONGLE) {
1224                 /* TODO: Implement to check if it is the recovery mode or not */
1225                 _bt_reliable_terminate_service(NULL);
1226         }
1227
1228         return FALSE;
1229 }
1230
1231 static void __bt_adapter_update_bt_enabled(void)
1232 {
1233         int result = BLUETOOTH_ERROR_NONE;
1234
1235         BT_INFO("_bt_adapter_update_bt_enabled >> Init profiles...");
1236         if (BLUETOOTH_ERROR_NONE != _bt_init_profiles())
1237                 BT_ERR("Bluetooth profile init failed");
1238
1239         _bt_device_handle_adapter_state(TRUE);
1240
1241         /* Update Bluetooth Status to notify other modules */
1242         if (vconf_set_int(VCONFKEY_BT_STATUS, VCONFKEY_BT_STATUS_ON) != 0)
1243                 BT_ERR("Set vconf failed\n");
1244
1245         if (vconf_set_int(VCONFKEY_BT_DEVICE, VCONFKEY_BT_DEVICE_NONE) != 0)
1246                 BT_ERR("Set vconf failed\n");
1247
1248         /* TODO:Add timer function to handle any further post processing */
1249         g_idle_add((GSourceFunc)__bt_adapter_post_set_enabled, NULL);
1250
1251         /*Return BT_ADAPTER_ENABLE Method invocation context */
1252         __bt_adapter_handle_pending_requests(BT_ENABLE_ADAPTER, NULL, 0);
1253         /*Send BT Enabled event to application */
1254         _bt_send_event(BT_ADAPTER_EVENT, BLUETOOTH_EVENT_ENABLED,
1255                         g_variant_new("(i)", result));
1256 }
1257
1258 static void __bt_adapter_update_bt_disabled(void)
1259 {
1260         int result = BLUETOOTH_ERROR_NONE;
1261         int power_off_status = 0;
1262         int ret;
1263
1264         BT_INFO("_bt_adapter_update_bt_disabled >> Cleanup profiles...");
1265         _bt_cleanup_profiles();
1266
1267         _bt_device_handle_adapter_state(FALSE);
1268
1269         /* Update the vconf BT status in normal Deactivation case only */
1270         ret = vconf_get_int(VCONFKEY_SYSMAN_POWER_OFF_STATUS, &power_off_status);
1271         BT_DBG("ret : %d, power_off_status : %d", ret, power_off_status);
1272
1273         /* Update Bluetooth Status to notify other modules */
1274         if (vconf_set_int(VCONFKEY_BT_STATUS, VCONFKEY_BT_STATUS_OFF) != 0)
1275                 BT_ERR("Set vconf failed");
1276
1277         if (vconf_set_int(VCONFKEY_BT_DEVICE, VCONFKEY_BT_DEVICE_NONE) != 0)
1278                 BT_ERR("Set vconf failed\n");
1279
1280         /* TODO:Add timer function to handle any further post processing */
1281         g_idle_add((GSourceFunc)__bt_adapter_post_set_disabled, NULL);
1282
1283         /* Return BT_ADAPTER_DISABLE Method invocation context */
1284         __bt_adapter_handle_pending_requests(BT_DISABLE_ADAPTER, NULL, 0);
1285
1286         /* Send BT Disabled event to application */
1287         _bt_send_event(BT_ADAPTER_EVENT, BLUETOOTH_EVENT_DISABLED,
1288                         g_variant_new("(i)", result));
1289 }
1290
1291 static void __bt_adapter_state_set_status(bt_status_t status)
1292 {
1293         BT_INFO("adapter_status changed [%d] -> [%d]", adapter_state, status);
1294         adapter_state = status;
1295 }
1296
1297 static void __bt_adapter_update_discovery_status(bt_adapter_discovery_state_t status)
1298 {
1299         BT_INFO("adapter_discovery_status changed [%d] -> [%d]", adapter_discovery_state, status);
1300         adapter_discovery_state = status;
1301 }
1302
1303 static void __bt_adapter_state_change_callback(int bt_status)
1304 {
1305         BT_INFO("__bt_adapter_state_change_callback: status [%d]", bt_status);
1306
1307         switch (bt_status) {
1308         case BT_DEACTIVATED:
1309                 __bt_adapter_state_set_status(bt_status);
1310
1311                 /* Adapter is disabled, unregister event handlers */
1312                 _bt_service_unregister_event_handler_callback(BT_ADAPTER_MODULE);
1313                 //_bt_deinit_device_event_handler();
1314
1315                 /* Add Adapter disabled post processing codes */
1316                 __bt_adapter_update_bt_disabled();
1317                 break;
1318         case BT_ACTIVATED:
1319                 __bt_adapter_state_set_status(bt_status);
1320                 /* Add Adapter enabled post processing codes */
1321                 if (timer_id > 0) {
1322                         BT_DBG("g_source is removed");
1323                         g_source_remove(timer_id);
1324                         timer_id = 0;
1325                 }
1326                 __bt_adapter_update_bt_enabled();
1327                 break;
1328         default:
1329                 BT_ERR("Incorrect Bluetooth adapter state changed status");
1330
1331         }
1332 }
1333
1334 int _bt_set_adapter_request_state(int enable)
1335 {
1336         return oal_set_adapter_request_state(enable);
1337 }
1338
1339 int _bt_set_le_request_state(int enable)
1340 {
1341         return oal_set_le_request_state(enable);
1342 }
1343
1344 static int __bt_adapter_state_handle_request(gboolean enable)
1345 {
1346         int result = BLUETOOTH_ERROR_NONE;
1347         BT_DBG("");
1348
1349         switch (adapter_state) {
1350         case BT_ACTIVATING: {
1351                 BT_INFO("Adapter is currently in activating state, state [%d]",
1352                                 adapter_state);
1353                 if (enable) {
1354                         return BLUETOOTH_ERROR_IN_PROGRESS;
1355                 } else {
1356                         if (adapter_discovery_state == ADAPTER_DISCOVERY_STARTED ||
1357                                         adapter_discovery_state == ADAPTER_DISCOVERY_STARTING) {
1358                                 /*TODO Stop Discovery*/
1359                                 __bt_adapter_update_discovery_status(FALSE);
1360                         }
1361                         result = adapter_disable();
1362                         if (result != OAL_STATUS_SUCCESS) {
1363                                 BT_ERR("adapter_enable failed: [%d]", result);
1364                                 result = BLUETOOTH_ERROR_INTERNAL;
1365                                 /*TODO: perform if anything more needs to be done to handle failure */
1366                         } else {
1367                                 /* TODO: To be handled */
1368                                 __bt_adapter_state_set_status(BT_DEACTIVATING);
1369                                 result = BLUETOOTH_ERROR_NONE;
1370                         }
1371                 }
1372                 break;
1373         }
1374         case BT_ACTIVATED: {
1375                 BT_INFO("Adapter is currently in activated state, state [%d]",
1376                                 adapter_state);
1377                 if (enable) {
1378                         return BLUETOOTH_ERROR_DEVICE_ALREADY_ENABLED;
1379                 } else {
1380                         if (adapter_discovery_state == ADAPTER_DISCOVERY_STARTED ||
1381                                         adapter_discovery_state == ADAPTER_DISCOVERY_STARTING) {
1382                                 /*TODO Stop Discovery*/
1383                                 __bt_adapter_update_discovery_status(FALSE);
1384                         }
1385                         result = adapter_disable();
1386                         if (result != OAL_STATUS_SUCCESS) {
1387                                 BT_ERR("adapter_enable failed: [%d]", result);
1388                                 result = BLUETOOTH_ERROR_INTERNAL;
1389                                 /*TODO: perform if anything more needs to be done to handle failure */
1390                         } else {
1391                                 /* TODO: To be handled */
1392                                 __bt_adapter_state_set_status(BT_DEACTIVATING);
1393                                 result = BLUETOOTH_ERROR_NONE;
1394                         }
1395                 }
1396                 break;
1397         }
1398         case BT_DEACTIVATING: {
1399                 BT_INFO("Adapter is currently in deactivating state, state [%d]",
1400                                 adapter_state);
1401                 if (!enable) {
1402                         return BLUETOOTH_ERROR_IN_PROGRESS;
1403
1404                 } else {
1405                         result = adapter_enable();
1406                         if (result != OAL_STATUS_SUCCESS && result != OAL_STATUS_PENDING) {
1407                                 BT_ERR("adapter_enable failed: [%d]", result);
1408                                 adapter_disable();
1409                                 result = BLUETOOTH_ERROR_INTERNAL;
1410                                 /*TODO: perform if anything more needs to be done to handle failure */
1411                         } else {
1412                                 /* TODO: To be handled */
1413                                 __bt_adapter_state_set_status(BT_ACTIVATING);
1414                                 result = BLUETOOTH_ERROR_NONE;
1415                         }
1416                 }
1417                 break;
1418         }
1419         case BT_DEACTIVATED: {
1420                 BT_INFO("Adapter is currently in deactivated state, state [%d]",
1421                                 adapter_state);
1422                 if (!enable) {
1423                         return BLUETOOTH_ERROR_DEVICE_NOT_ENABLED;
1424                 } else {
1425                         result = adapter_enable();
1426                         if (result != OAL_STATUS_SUCCESS && result != OAL_STATUS_PENDING) {
1427                                 BT_ERR("adapter_enable failed: [%d]", result);
1428                                 adapter_disable();
1429                                 result = BLUETOOTH_ERROR_INTERNAL;
1430                                 /*TODO: perform if anything more needs to be done to handle failure */
1431                         } else {
1432                                 /* TODO: To be handled */
1433                                 __bt_adapter_state_set_status(BT_ACTIVATING);
1434                                 result = BLUETOOTH_ERROR_NONE;
1435                         }
1436                 }
1437                 break;
1438         }
1439         default:
1440                 BT_ERR("Unknown state: %d", adapter_state);
1441                 break;
1442         }
1443
1444         if (enable && result == BLUETOOTH_ERROR_NONE) {
1445                 /* Adapter enable request is successful, setup event handlers */
1446                 _bt_service_register_event_handler_callback(
1447                                 BT_ADAPTER_MODULE, __bt_adapter_event_handler);
1448                 _bt_device_state_handle_callback_set_request();
1449         }
1450         return result;
1451 }
1452
1453 static int __bt_adapter_state_discovery_request(gboolean enable,
1454                 unsigned short max_response, unsigned short duration,
1455                 unsigned int mask, gboolean is_custom,
1456                 bt_discovery_role_type_t role)
1457 {
1458         int result = BLUETOOTH_ERROR_NONE;
1459
1460         BT_DBG("+");
1461         switch (adapter_discovery_state) {
1462         case ADAPTER_DISCOVERY_STARTED: {
1463                 BT_INFO("Adapter is currently in discovery started state, state [%d]",
1464                                 adapter_discovery_state);
1465                 if (enable) {
1466                         return BLUETOOTH_ERROR_IN_PROGRESS;
1467                 } else {
1468                         result = adapter_stop_inquiry();
1469                         if (result != OAL_STATUS_SUCCESS) {
1470                                 BT_ERR("Discover stop failed: %d", result);
1471                                 result = BLUETOOTH_ERROR_INTERNAL;
1472                         } else {
1473                                 BT_ERR("Stop Discovery Triggered successfully");
1474                                 __bt_adapter_update_discovery_status(ADAPTER_DISCOVERY_STOPPING);
1475                                 result = BLUETOOTH_ERROR_NONE;
1476                         }
1477                 }
1478                 break;
1479         }
1480         case ADAPTER_DISCOVERY_STARTING: {
1481                 BT_INFO("Adapter is currently in discovery starting state, state [%d]",
1482                                 adapter_discovery_state);
1483
1484                 result = enable ?  BLUETOOTH_ERROR_IN_PROGRESS :
1485                                         BLUETOOTH_ERROR_DEVICE_BUSY;
1486
1487                 break;
1488         }
1489         case ADAPTER_DISCOVERY_STOPPED: {
1490                 BT_INFO("Adapter is currently in discovery stopped state, state [%d]",
1491                                 adapter_discovery_state);
1492                 if (!enable)
1493                         return BLUETOOTH_ERROR_NOT_IN_OPERATION;
1494                 else {
1495                         BT_DBG("max_resp: %u, duration: %u, cod: 0x%X", max_response, duration, mask);
1496
1497                         if (!is_custom)
1498                                 result = adapter_start_inquiry(duration);
1499                         else
1500                                 result = adapter_start_custom_inquiry(role);
1501
1502                         if (result != OAL_STATUS_SUCCESS) {
1503                                 BT_ERR("Start Discovery failed: %d", result);
1504                                 result = BLUETOOTH_ERROR_INTERNAL;
1505                         } else {
1506                                 BT_ERR("Start Discovery Triggered successfully");
1507                                 __bt_adapter_update_discovery_status(ADAPTER_DISCOVERY_STARTING);
1508                                 result = BLUETOOTH_ERROR_NONE;
1509                         }
1510                 }
1511                 break;
1512         }
1513         case ADAPTER_DISCOVERY_STOPPING: {
1514                 BT_INFO("Adapter is currently in discovery stopping state, state [%d]",
1515                                 adapter_discovery_state);
1516
1517                 result = enable ?  BLUETOOTH_ERROR_DEVICE_BUSY :
1518                                         BLUETOOTH_ERROR_NOT_IN_OPERATION;
1519
1520                 break;
1521         }
1522         default:
1523                 BT_ERR("Unknown state: %d", adapter_discovery_state);
1524                 break;
1525         }
1526
1527         BT_DBG("-");
1528         return result;
1529 }
1530
1531 static void __bt_adapter_discovery_state_change_callback(int bt_discovery_status)
1532 {
1533         BT_INFO("__bt_adapter_discovery_state_change_callback: status [%d]", bt_discovery_status);
1534         GVariant *param = NULL;
1535         int result = BLUETOOTH_ERROR_NONE;
1536
1537         switch (bt_discovery_status) {
1538         case ADAPTER_DISCOVERY_STOPPED:
1539         {
1540                 __bt_adapter_update_discovery_status(bt_discovery_status);
1541                 param = g_variant_new("(i)", result);
1542                 _bt_send_event(BT_ADAPTER_EVENT,
1543                                 BLUETOOTH_EVENT_DISCOVERY_FINISHED,
1544                                 param);
1545                 break;
1546         }
1547         case ADAPTER_DISCOVERY_STARTED:
1548         {
1549                 __bt_adapter_update_discovery_status(bt_discovery_status);
1550                 param = g_variant_new("(i)", result);
1551                 _bt_send_event(BT_ADAPTER_EVENT,
1552                                 BLUETOOTH_EVENT_DISCOVERY_STARTED,
1553                                 param);
1554                 break;
1555         }
1556         default:
1557                 BT_ERR("Incorrect Bluetooth adapter Discovery state changed status");
1558         }
1559 }
1560
1561 static void __bt_set_visible_mode(void)
1562 {
1563         int timeout = 0;
1564 #ifdef TIZEN_FEATURE_BT_DPM
1565         int discoverable_state = DPM_BT_ERROR;
1566 #endif
1567
1568         if (vconf_get_int(BT_FILE_VISIBLE_TIME, &timeout) != 0)
1569                 BT_ERR("Fail to get the timeout value");
1570
1571 #ifdef TIZEN_FEATURE_BT_DPM
1572         _bt_dpm_get_bluetooth_limited_discoverable_state(&discoverable_state);
1573         if (timeout == -1 || discoverable_state == DPM_RESTRICTED) {
1574                 if (_bt_set_discoverable_mode(
1575                                         BLUETOOTH_DISCOVERABLE_MODE_GENERAL_DISCOVERABLE,
1576                                         timeout) != BLUETOOTH_ERROR_NONE) {
1577                         if (vconf_set_int(BT_FILE_VISIBLE_TIME, 0) != 0)
1578                                 BT_ERR("Set vconf failed");
1579                 }
1580         } else {
1581                 if (_bt_set_discoverable_mode(
1582                                         BLUETOOTH_DISCOVERABLE_MODE_CONNECTABLE,
1583                                         timeout) != BLUETOOTH_ERROR_NONE) {
1584                         BT_ERR("Set connectable mode failed");
1585                 }
1586         }
1587 #else
1588         if (timeout == -1) {
1589                 if (_bt_set_discoverable_mode(
1590                                         BLUETOOTH_DISCOVERABLE_MODE_GENERAL_DISCOVERABLE,
1591                                         timeout) != BLUETOOTH_ERROR_NONE) {
1592                         if (vconf_set_int(BT_FILE_VISIBLE_TIME, 0) != 0)
1593                                 BT_ERR("Set vconf failed");
1594                 }
1595         } else {
1596                 if (_bt_set_discoverable_mode(
1597                                         BLUETOOTH_DISCOVERABLE_MODE_CONNECTABLE,
1598                                         timeout) != BLUETOOTH_ERROR_NONE) {
1599                         BT_ERR("Set connectable mode failed");
1600                 }
1601         }
1602 #endif
1603 }
1604
1605 static void __bt_set_local_name(void)
1606 {
1607         char *phone_name = NULL;
1608         char *ptr = NULL;
1609
1610         phone_name = vconf_get_str(VCONFKEY_SETAPPL_DEVICE_NAME_STR);
1611
1612         if (!phone_name)
1613                 return;
1614
1615         if (strlen(phone_name) != 0) {
1616                 if (!g_utf8_validate(phone_name, -1, (const char **)&ptr))
1617                         *ptr = '\0';
1618
1619                 _bt_set_local_name(phone_name);
1620         }
1621         free(phone_name);
1622 }
1623
1624 void _bt_adapter_set_status(bt_status_t status)
1625 {
1626         BT_INFO("adapter_status changed [%d] -> [%d]", adapter_state, status);
1627         adapter_state = status;
1628 }
1629
1630 bt_status_t _bt_adapter_get_status(void)
1631 {
1632         return adapter_state;
1633 }
1634
1635 void _bt_set_disabled(int result)
1636 {
1637         int power_off_status = 0;
1638         int ret;
1639         int ret_pm_ignore;
1640         int pm_ignore_mode = 0;
1641
1642         ret = vconf_get_int(VCONFKEY_SYSMAN_POWER_OFF_STATUS, &power_off_status);
1643         BT_DBG("ret : %d, power_off_status : %d", ret, power_off_status);
1644
1645         ret_pm_ignore = vconf_get_int(VCONFKEY_PM_KEY_IGNORE, &pm_ignore_mode);
1646
1647         /* Update the vconf BT status in normal Deactivation case only */
1648         if (ret == 0 && power_off_status == VCONFKEY_SYSMAN_POWER_OFF_NONE &&
1649                 ret_pm_ignore == 0 && pm_ignore_mode != VCONFKEY_PM_KEY_LOCK) {
1650
1651                 BT_DBG("Update vconf for BT normal Deactivation");
1652
1653                 if (result == BLUETOOTH_ERROR_TIMEOUT)
1654                         if (vconf_set_int(BT_OFF_DUE_TO_TIMEOUT, 1) != 0)
1655                                 BT_ERR("Set vconf failed");
1656
1657                 /* Update Bluetooth Status to notify other modules */
1658                 if (vconf_set_int(VCONFKEY_BT_STATUS, VCONFKEY_BT_STATUS_OFF) != 0)
1659                         BT_ERR("Set vconf failed");
1660
1661                 if (_bt_eventsystem_set_value(SYS_EVENT_BT_STATE, EVT_KEY_BT_STATE,
1662                                                         EVT_VAL_BT_OFF) != ES_R_OK)
1663                         BT_ERR("Fail to set value");
1664         }
1665
1666         if (vconf_set_int(VCONFKEY_BT_DEVICE, VCONFKEY_BT_DEVICE_NONE) != 0)
1667                 BT_ERR("Set vconf failed\n");
1668
1669         _bt_adapter_set_status(BT_DEACTIVATED);
1670         __bt_adapter_update_discovery_status(ADAPTER_DISCOVERY_STOPPED);
1671
1672         BT_INFO("Adapter disabled");
1673 }
1674