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