[FRWK] Add "Custom Discovery" & "Profile Connected devices"
[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         /* Update Bluetooth Status to OFF */
980         if (vconf_set_int(VCONFKEY_BT_STATUS, VCONFKEY_BT_STATUS_OFF) != 0)
981                 BT_ERR("Set vconf failed\n");
982
983         if (status & VCONFKEY_BT_STATUS_ON) {
984                 ret = _bt_enable_adapter();
985                 if (ret != BLUETOOTH_ERROR_NONE)
986                         BT_ERR("_bt_enable_adapter failed with error: %d", ret);
987         }
988 }
989
990 /* OAL initialization handler */
991 static void __bt_handle_oal_initialisation(oal_event_t event)
992 {
993         BT_DBG("");
994
995         switch(event) {
996         case OAL_EVENT_OAL_INITIALISED_SUCCESS:
997                 __bt_post_oal_init();
998                 break;
999         case OAL_EVENT_OAL_INITIALISED_FAILED:
1000                 BT_ERR("OAL Initialisation Failed, terminate bt-service daemon..");
1001                 g_idle_add(_bt_terminate_service, NULL);
1002                 break;
1003         default:
1004                 BT_ERR("Unknown Event");
1005                 break;
1006         }
1007 }
1008
1009 static gboolean __bt_is_service_request_present(int service_function)
1010 {
1011         GSList *l;
1012         invocation_info_t *req_info;
1013
1014         BT_DBG("+");
1015
1016         /* Get method invocation context */
1017         for (l = _bt_get_invocation_list(); l != NULL; l = g_slist_next(l)) {
1018                 req_info = l->data;
1019                 if (req_info && req_info->service_function == service_function)
1020                         return TRUE;
1021         }
1022
1023         BT_DBG("-");
1024         return FALSE;
1025 }
1026
1027 /* Internal functions of core adapter service */
1028 static void __bt_adapter_handle_pending_requests(int service_function, void *user_data, unsigned int size)
1029 {
1030         GSList *l;
1031         GArray *out_param;
1032         invocation_info_t *req_info;
1033         BT_INFO("+");
1034
1035         /* Get method invocation context */
1036         for (l = _bt_get_invocation_list(); l != NULL; l = g_slist_next(l)) {
1037                 req_info = l->data;
1038                 if (req_info == NULL || req_info->service_function != service_function)
1039                         continue;
1040
1041                 /* Create out param */
1042                 out_param = g_array_new(FALSE, FALSE, sizeof(gchar));
1043
1044                 switch(service_function) {
1045                 case BT_ENABLE_ADAPTER:
1046                 case BT_DISABLE_ADAPTER: {
1047                         gboolean done = TRUE;
1048                         g_array_append_vals(out_param, &done, sizeof(gboolean));
1049                         break;
1050                 }
1051                 case BT_GET_LOCAL_NAME:
1052                 case BT_GET_LOCAL_ADDRESS:
1053                 case BT_GET_LOCAL_VERSION:
1054                         g_array_append_vals(out_param, user_data, size);
1055                         break;
1056                 case BT_IS_SERVICE_USED: {
1057                         unsigned int i;
1058                         gboolean used = FALSE;
1059                         unsigned char *uuid;
1060                         char uuid_str[BT_UUID_STRING_SIZE];
1061                         char *request_uuid = req_info->user_data;
1062                         service_uuid_t *service_list = user_data;
1063
1064                         BT_INFO("Check for service uuid: %s", request_uuid);
1065                         for (i = 0; i < size; i++) {
1066                                 uuid = service_list[i].uuid;
1067                                 _bt_service_convert_uuid_type_to_string(uuid_str, uuid);
1068                                 BT_INFO("Adapter Service: [%s]", uuid_str);
1069                                 if (strcasecmp(uuid_str, request_uuid) == 0) {
1070                                         BT_INFO("UUID matched!!");
1071                                         used = TRUE;
1072                                         break;
1073                                 }
1074                         }
1075
1076                         g_array_append_vals(out_param, &used, sizeof(gboolean));
1077                         break;
1078                 }
1079                 case BT_GET_BONDED_DEVICES: {
1080                         bluetooth_device_address_t *addr_list = user_data;
1081                         bonded_devices_req_info_t *bonded_devices_req_info;
1082                         char address[BT_ADDRESS_STRING_SIZE];
1083                         int count = size;
1084                         int res = BLUETOOTH_ERROR_NONE;
1085
1086                         /*
1087                          * BT_GET_BONDED_DEVICES is already processed for this request,
1088                          * continue for next BT_GET_BONDED_DEVICES request if any
1089                          */
1090                         if (NULL != req_info->user_data)
1091                                 continue;
1092
1093                         BT_DBG("BT_GET_BONDED_DEVICES: count = [%d]", count);
1094                         /* No bonded devices, return method invocation */
1095                         if (0 == count || !addr_list)
1096                                 break;
1097
1098                         /* Save address list in user data  for futur reference. */
1099                         bonded_devices_req_info = g_malloc0(sizeof(bonded_devices_req_info));
1100                         if (!bonded_devices_req_info) {
1101                                 BT_ERR("Memory allocation failed");
1102                                 req_info->result = BLUETOOTH_ERROR_MEMORY_ALLOCATION;
1103                                 g_free(addr_list);
1104                                 break;
1105                         }
1106
1107                         bonded_devices_req_info->count = count;
1108                         bonded_devices_req_info->addr_list = addr_list;
1109                         bonded_devices_req_info->out_param = out_param;
1110                         req_info->user_data = bonded_devices_req_info;
1111
1112                         while (bonded_devices_req_info->count > 0) {
1113                                 bonded_devices_req_info->count -= 1;
1114                                 res = _bt_device_get_bonded_device_info(
1115                                                 &addr_list[bonded_devices_req_info->count]);
1116                                 if (BLUETOOTH_ERROR_NONE == res)
1117                                         return;
1118                                 else {
1119                                         _bt_convert_addr_type_to_string((char *)address,
1120                                                         addr_list[bonded_devices_req_info->count].addr);
1121                                         BT_ERR("_bt_device_get_bonded_device_info Failed for [%s]", address);
1122                                         if (bonded_devices_req_info->count == 0) {
1123                                                 g_free(bonded_devices_req_info->addr_list);
1124                                                 g_free(bonded_devices_req_info);
1125                                                 req_info->user_data = NULL;
1126                                         }
1127                                 }
1128                         }
1129                         break;
1130                 }
1131                 default:
1132                         BT_ERR("Unknown service function[%d]", service_function);
1133                 }
1134
1135                 _bt_service_method_return(req_info->context, out_param, req_info->result);
1136                 g_array_free(out_param, TRUE);
1137                 /* Now free invocation info for this request*/
1138                 _bt_free_info_from_invocation_list(req_info);
1139         }
1140 }
1141
1142 static void __bt_phone_name_changed_cb(keynode_t *node, void *data)
1143 {
1144         char *phone_name = NULL;
1145         char *ptr = NULL;
1146
1147         if (node == NULL)
1148                 return;
1149
1150         if (vconf_keynode_get_type(node) == VCONF_TYPE_STRING) {
1151                 phone_name = vconf_keynode_get_str(node);
1152
1153                 if (phone_name && strlen(phone_name) != 0) {
1154                         if (!g_utf8_validate(phone_name, -1,
1155                                         (const char **)&ptr))
1156                                 *ptr = '\0';
1157
1158                         _bt_set_local_name(phone_name);
1159                 }
1160         }
1161 }
1162
1163 /* Request return handlings */
1164 static gboolean __bt_adapter_post_set_enabled(gpointer user_data)
1165 {
1166         BT_INFO("__bt_adapter_post_set_enabled>>");
1167
1168         if (!TIZEN_PROFILE_TV) {
1169                 __bt_set_visible_mode();
1170
1171                 /* add the vconf noti handler */
1172                 if (0 != vconf_notify_key_changed(VCONFKEY_SETAPPL_DEVICE_NAME_STR,
1173                                 (vconf_callback_fn)__bt_phone_name_changed_cb, NULL))
1174                         BT_ERR("DEVICE_NAME key changed notification registration failed");
1175
1176                 __bt_set_local_name();
1177         } else {
1178                 if (BLUETOOTH_ERROR_NONE != _bt_set_discoverable_mode(
1179                                 BLUETOOTH_DISCOVERABLE_MODE_GENERAL_DISCOVERABLE, 0))
1180                         BT_ERR("Fail to set discoverable mode");
1181         }
1182
1183         /* Get All properties */
1184         if (OAL_STATUS_SUCCESS != adapter_get_properties())
1185                 BT_ERR("adapter_get_properties failed");
1186
1187         /* Add Adapter enabled post processing codes */
1188         return FALSE;
1189 }
1190
1191 static gboolean __bt_adapter_post_set_disabled(gpointer user_data)
1192 {
1193         BT_INFO("_bt_adapter_post_set_disabled>>");
1194
1195         if (!TIZEN_PROFILE_TV) {
1196                 /* Add Adapter disabled post processing codes */
1197                 if (vconf_ignore_key_changed(VCONFKEY_SETAPPL_DEVICE_NAME_STR,
1198                                 (vconf_callback_fn)__bt_phone_name_changed_cb) != 0)
1199                         BT_ERR("vconf_ignore_key_changed failed");
1200         }
1201
1202         return FALSE;
1203 }
1204
1205 static void __bt_adapter_update_bt_enabled(void)
1206 {
1207         int result = BLUETOOTH_ERROR_NONE;
1208         BT_INFO("_bt_adapter_update_bt_enabled >> Init profiles...");
1209         if (BLUETOOTH_ERROR_NONE != _bt_init_profiles())
1210                 BT_ERR("Bluetooth profile init failed");
1211
1212         /* Update Bluetooth Status to notify other modules */
1213         if (vconf_set_int(VCONFKEY_BT_STATUS, VCONFKEY_BT_STATUS_ON) != 0)
1214                 BT_ERR("Set vconf failed\n");
1215
1216         /* TODO:Add timer function to handle any further post processing */
1217         g_idle_add((GSourceFunc)__bt_adapter_post_set_enabled, NULL);
1218
1219         /*Return BT_ADAPTER_ENABLE Method invocation context */
1220         __bt_adapter_handle_pending_requests(BT_ENABLE_ADAPTER, NULL, 0);
1221         /*Send BT Enabled event to application */
1222         _bt_send_event(BT_ADAPTER_EVENT, BLUETOOTH_EVENT_ENABLED,
1223                         g_variant_new("(i)", result));
1224 }
1225
1226 static void __bt_adapter_update_bt_disabled(void)
1227 {
1228         int result = BLUETOOTH_ERROR_NONE;
1229         BT_INFO("_bt_adapter_update_bt_disabled >> Cleanup profiles...");
1230         _bt_cleanup_profiles();
1231
1232         int power_off_status = 0;
1233         int ret;
1234
1235         /* Update the vconf BT status in normal Deactivation case only */
1236         ret = vconf_get_int(VCONFKEY_SYSMAN_POWER_OFF_STATUS, &power_off_status);
1237         BT_DBG("ret : %d, power_off_status : %d", ret, power_off_status);
1238
1239         /* Update Bluetooth Status to notify other modules */
1240         if (vconf_set_int(VCONFKEY_BT_STATUS, VCONFKEY_BT_STATUS_OFF) != 0)
1241                 BT_ERR("Set vconf failed");
1242
1243         /* TODO:Add timer function to handle any further post processing */
1244         g_idle_add((GSourceFunc)__bt_adapter_post_set_disabled, NULL);
1245
1246         /* Return BT_ADAPTER_DISABLE Method invocation context */
1247         __bt_adapter_handle_pending_requests(BT_DISABLE_ADAPTER, NULL, 0);
1248
1249         /* Send BT Disabled event to application */
1250         _bt_send_event(BT_ADAPTER_EVENT, BLUETOOTH_EVENT_DISABLED,
1251                         g_variant_new("(i)", result));
1252 }
1253
1254 static void __bt_adapter_state_set_status(bt_status_t status)
1255 {
1256         BT_INFO("adapter_status changed [%d] -> [%d]", adapter_state, status);
1257         adapter_state = status;
1258 }
1259
1260 static void __bt_adapter_update_discovery_status(bt_adapter_discovery_state_t status)
1261 {
1262         BT_INFO("adapter_discovery_status changed [%d] -> [%d]", adapter_discovery_state, status);
1263         adapter_discovery_state = status;
1264 }
1265
1266 static void __bt_adapter_state_change_callback(int bt_status)
1267 {
1268         BT_INFO("__bt_adapter_state_change_callback: status [%d]", bt_status);
1269
1270         switch (bt_status) {
1271         case BT_DEACTIVATED:
1272                 __bt_adapter_state_set_status(bt_status);
1273
1274                 /* Adapter is disabled, unregister event handlers */
1275                 _bt_service_unregister_event_handler_callback(BT_ADAPTER_MODULE);
1276                 //_bt_deinit_device_event_handler();
1277
1278                 /* Add Adapter disabled post processing codes */
1279                 __bt_adapter_update_bt_disabled();
1280                 break;
1281         case BT_ACTIVATED:
1282                 __bt_adapter_state_set_status(bt_status);
1283                 /* Add Adapter enabled post processing codes */
1284                 if (timer_id > 0) {
1285                         BT_DBG("g_source is removed");
1286                         g_source_remove(timer_id);
1287                         timer_id = 0;
1288                 }
1289                 __bt_adapter_update_bt_enabled();
1290                 break;
1291         default:
1292                 BT_ERR("Incorrect Bluetooth adapter state changed status");
1293
1294         }
1295 }
1296
1297 static int __bt_adapter_state_handle_request(gboolean enable)
1298 {
1299         int result = BLUETOOTH_ERROR_NONE;
1300         BT_DBG("");
1301
1302         switch (adapter_state) {
1303         case BT_ACTIVATING: {
1304                 BT_INFO("Adapter is currently in activating state, state [%d]",
1305                                 adapter_state);
1306                 if (enable) {
1307                         return BLUETOOTH_ERROR_IN_PROGRESS;
1308                 } else {
1309                         if (adapter_discovery_state == ADAPTER_DISCOVERY_STARTED ||
1310                                         adapter_discovery_state == ADAPTER_DISCOVERY_STARTING) {
1311                                 /*TODO Stop Discovery*/
1312                                 if (result != OAL_STATUS_SUCCESS)
1313                                         BT_ERR("Discover stop failed: %d", result);
1314                                 __bt_adapter_update_discovery_status(FALSE);
1315                         }
1316                         result = adapter_disable();
1317                         if (result != OAL_STATUS_SUCCESS) {
1318                                 BT_ERR("adapter_enable failed: [%d]", result);
1319                                 result = BLUETOOTH_ERROR_INTERNAL;
1320                                 /*TODO: perform if anything more needs to be done to handle failure */
1321                         } else {
1322                                 /* TODO: To be handled */
1323                                 __bt_adapter_state_set_status(BT_DEACTIVATING);
1324                                 result = BLUETOOTH_ERROR_NONE;
1325                         }
1326                 }
1327                 break;
1328         }
1329         case BT_ACTIVATED: {
1330                 BT_INFO("Adapter is currently in activated state, state [%d]",
1331                                 adapter_state);
1332                 if (enable) {
1333                         return BLUETOOTH_ERROR_DEVICE_ALREADY_ENABLED;
1334                 } else {
1335                         if (adapter_discovery_state == ADAPTER_DISCOVERY_STARTED ||
1336                                         adapter_discovery_state == ADAPTER_DISCOVERY_STARTING) {
1337                                 /*TODO Stop Discovery*/
1338                                 if (result != OAL_STATUS_SUCCESS)
1339                                         BT_ERR("Discover stop failed: %d", result);
1340                                 __bt_adapter_update_discovery_status(FALSE);
1341                         }
1342                         result = adapter_disable();
1343                         if (result != OAL_STATUS_SUCCESS) {
1344                                 BT_ERR("adapter_enable failed: [%d]", result);
1345                                 result = BLUETOOTH_ERROR_INTERNAL;
1346                                 /*TODO: perform if anything more needs to be done to handle failure */
1347                         } else {
1348                                 /* TODO: To be handled */
1349                                 __bt_adapter_state_set_status(BT_DEACTIVATING);
1350                                 result = BLUETOOTH_ERROR_NONE;
1351                         }
1352                 }
1353                 break;
1354         }
1355         case BT_DEACTIVATING: {
1356                 BT_INFO("Adapter is currently in deactivating state, state [%d]",
1357                                 adapter_state);
1358                 if (!enable) {
1359                         return BLUETOOTH_ERROR_IN_PROGRESS;
1360
1361                 } else {
1362                         result = adapter_enable();
1363                         if (result != OAL_STATUS_SUCCESS && result != OAL_STATUS_PENDING) {
1364                                 BT_ERR("adapter_enable failed: [%d]", result);
1365                                 adapter_disable();
1366                                 result = BLUETOOTH_ERROR_INTERNAL;
1367                                 /*TODO: perform if anything more needs to be done to handle failure */
1368                         } else {
1369                                 /* TODO: To be handled */
1370                                 __bt_adapter_state_set_status(BT_ACTIVATING);
1371                                 result = BLUETOOTH_ERROR_NONE;
1372                         }
1373                 }
1374                 break;
1375         }
1376         case BT_DEACTIVATED: {
1377                 BT_INFO("Adapter is currently in deactivated state, state [%d]",
1378                                 adapter_state);
1379                 if (!enable) {
1380                         return BLUETOOTH_ERROR_DEVICE_NOT_ENABLED;
1381                 } else {
1382                         result = adapter_enable();
1383                         if (result != OAL_STATUS_SUCCESS && result != OAL_STATUS_PENDING) {
1384                                 BT_ERR("adapter_enable failed: [%d]", result);
1385                                 adapter_disable();
1386                                 result = BLUETOOTH_ERROR_INTERNAL;
1387                                 /*TODO: perform if anything more needs to be done to handle failure */
1388                         } else {
1389                                 /* TODO: To be handled */
1390                                 __bt_adapter_state_set_status(BT_ACTIVATING);
1391                                 result = BLUETOOTH_ERROR_NONE;
1392                         }
1393                 }
1394                 break;
1395         }
1396         default:
1397                 BT_ERR("Unknown state: %d", adapter_state);
1398                 break;
1399         }
1400
1401         if (enable && result == BLUETOOTH_ERROR_NONE) {
1402                 /* Adapter enable request is successful, setup event handlers */
1403                 _bt_service_register_event_handler_callback(
1404                                 BT_ADAPTER_MODULE, __bt_adapter_event_handler);
1405                 _bt_device_state_handle_callback_set_request();
1406         }
1407         return result;
1408 }
1409
1410 static int __bt_adapter_state_discovery_request(gboolean enable,
1411                 unsigned short max_response, unsigned short duration,
1412                 unsigned int mask, gboolean is_custom,
1413                 bt_discovery_role_type_t role)
1414 {
1415         int result = BLUETOOTH_ERROR_NONE;
1416
1417         BT_DBG("+");
1418         switch (adapter_discovery_state) {
1419         case ADAPTER_DISCOVERY_STARTED: {
1420                 BT_INFO("Adapter is currently in discovery started state, state [%d]",
1421                                 adapter_discovery_state);
1422                 if (enable) {
1423                         return BLUETOOTH_ERROR_IN_PROGRESS;
1424                 } else {
1425                         result = adapter_stop_inquiry();
1426                         if (result != OAL_STATUS_SUCCESS) {
1427                                 BT_ERR("Discover stop failed: %d", result);
1428                                 result = BLUETOOTH_ERROR_INTERNAL;
1429                         } else {
1430                                 BT_ERR("Stop Discovery Triggered successfully");
1431                                 __bt_adapter_update_discovery_status(ADAPTER_DISCOVERY_STOPPING);
1432                                 result = BLUETOOTH_ERROR_NONE;
1433                         }
1434                 }
1435                 break;
1436         }
1437         case ADAPTER_DISCOVERY_STARTING: {
1438                 BT_INFO("Adapter is currently in discovery starting state, state [%d]",
1439                                 adapter_discovery_state);
1440                 if (enable) {
1441                         return BLUETOOTH_ERROR_IN_PROGRESS;
1442                 } else {
1443                         result = adapter_stop_inquiry();
1444                         if (result != OAL_STATUS_SUCCESS) {
1445                                 BT_ERR("Discover stop failed: %d", result);
1446                                 result = BLUETOOTH_ERROR_INTERNAL;
1447                         } else {
1448                                 BT_ERR("Stop Discovery Triggered successfully");
1449                                 __bt_adapter_update_discovery_status(ADAPTER_DISCOVERY_STOPPING);
1450                                 result = BLUETOOTH_ERROR_NONE;
1451                         }
1452                 }
1453                 break;
1454         }
1455         case ADAPTER_DISCOVERY_STOPPED: {
1456                 BT_INFO("Adapter is currently in discovery stopped state, state [%d]",
1457                                 adapter_discovery_state);
1458                 if (!enable)
1459                         return BLUETOOTH_ERROR_NOT_IN_OPERATION;
1460                 else {
1461                         BT_DBG("max_resp: %u, duration: %u, cod: 0x%X", max_response, duration, mask);
1462
1463                         if (!is_custom)
1464                                 result = adapter_start_inquiry(duration);
1465                         else
1466                                 result = adapter_start_custom_inquiry(role);
1467
1468                         if (result != OAL_STATUS_SUCCESS) {
1469                                 BT_ERR("Start Discovery failed: %d", result);
1470                                 result = BLUETOOTH_ERROR_INTERNAL;
1471                         } else {
1472                                 BT_ERR("Start Discovery Triggered successfully");
1473                                 __bt_adapter_update_discovery_status(ADAPTER_DISCOVERY_STARTING);
1474                                 result = BLUETOOTH_ERROR_NONE;
1475                         }
1476                 }
1477                 break;
1478         }
1479         case ADAPTER_DISCOVERY_STOPPING: {
1480                 BT_INFO("Adapter is currently in discovery stopping state, state [%d]",
1481                                 adapter_discovery_state);
1482                 if (!enable)
1483                         return BLUETOOTH_ERROR_NOT_IN_OPERATION;
1484                 else {
1485                         BT_DBG("max_resp: %u, duration: %u, cod: 0x%X", max_response, duration, mask);
1486                         if (!is_custom)
1487                                 result = adapter_start_inquiry(duration);
1488                         else
1489                                 result = adapter_start_custom_inquiry(role);
1490                         if (result != OAL_STATUS_SUCCESS) {
1491                                 BT_ERR("Start Discovery failed: %d", result);
1492                                 result = BLUETOOTH_ERROR_INTERNAL;
1493                         } else {
1494                                 BT_ERR("Start Discovery Triggered successfully");
1495                         __bt_adapter_update_discovery_status(ADAPTER_DISCOVERY_STARTING);
1496                                 result = BLUETOOTH_ERROR_NONE;
1497                         }
1498                 }
1499                 break;
1500         }
1501         default:
1502                 BT_ERR("Unknown state: %d", adapter_discovery_state);
1503                 break;
1504         }
1505
1506         BT_DBG("-");
1507         return result;
1508 }
1509
1510 static void __bt_adapter_discovery_state_change_callback(int bt_discovery_status)
1511 {
1512         BT_INFO("__bt_adapter_discovery_state_change_callback: status [%d]", bt_discovery_status);
1513         GVariant *param = NULL;
1514         int result = BLUETOOTH_ERROR_NONE;
1515
1516         switch (bt_discovery_status) {
1517         case ADAPTER_DISCOVERY_STOPPED:
1518         {
1519                 __bt_adapter_update_discovery_status(bt_discovery_status);
1520                 param = g_variant_new("(i)", result);
1521                 _bt_send_event(BT_ADAPTER_EVENT,
1522                                 BLUETOOTH_EVENT_DISCOVERY_FINISHED,
1523                                 param);
1524                 break;
1525         }
1526         case ADAPTER_DISCOVERY_STARTED:
1527         {
1528                 __bt_adapter_update_discovery_status(bt_discovery_status);
1529                 param = g_variant_new("(i)", result);
1530                 _bt_send_event(BT_ADAPTER_EVENT,
1531                                 BLUETOOTH_EVENT_DISCOVERY_STARTED,
1532                                 param);
1533                 break;
1534         }
1535         default:
1536                 BT_ERR("Incorrect Bluetooth adapter Discovery state changed status");
1537         }
1538 }
1539
1540 static void __bt_set_visible_mode(void)
1541 {
1542         int timeout = 0;
1543 #ifdef TIZEN_FEATURE_BT_DPM
1544         int discoverable_state = DPM_BT_ERROR;
1545 #endif
1546
1547         if (vconf_get_int(BT_FILE_VISIBLE_TIME, &timeout) != 0)
1548                 BT_ERR("Fail to get the timeout value");
1549
1550 #ifdef TIZEN_FEATURE_BT_DPM
1551         _bt_dpm_get_bluetooth_limited_discoverable_state(&discoverable_state);
1552         if (timeout == -1 || discoverable_state == DPM_RESTRICTED) {
1553                 if (_bt_set_discoverable_mode(
1554                                         BLUETOOTH_DISCOVERABLE_MODE_GENERAL_DISCOVERABLE,
1555                                         timeout) != BLUETOOTH_ERROR_NONE) {
1556                         if (vconf_set_int(BT_FILE_VISIBLE_TIME, 0) != 0)
1557                                 BT_ERR("Set vconf failed");
1558                 }
1559         } else {
1560                 if (_bt_set_discoverable_mode(
1561                                         BLUETOOTH_DISCOVERABLE_MODE_CONNECTABLE,
1562                                         timeout) != BLUETOOTH_ERROR_NONE) {
1563                         BT_ERR("Set connectable mode failed");
1564                 }
1565         }
1566 #else
1567         if (timeout == -1) {
1568                 if (_bt_set_discoverable_mode(
1569                                         BLUETOOTH_DISCOVERABLE_MODE_GENERAL_DISCOVERABLE,
1570                                         timeout) != BLUETOOTH_ERROR_NONE) {
1571                         if (vconf_set_int(BT_FILE_VISIBLE_TIME, 0) != 0)
1572                                 BT_ERR("Set vconf failed");
1573                 }
1574         } else {
1575                 if (_bt_set_discoverable_mode(
1576                                         BLUETOOTH_DISCOVERABLE_MODE_CONNECTABLE,
1577                                         timeout) != BLUETOOTH_ERROR_NONE) {
1578                         BT_ERR("Set connectable mode failed");
1579                 }
1580         }
1581 #endif
1582 }
1583
1584 static void __bt_set_local_name(void)
1585 {
1586         char *phone_name = NULL;
1587         char *ptr = NULL;
1588
1589         phone_name = vconf_get_str(VCONFKEY_SETAPPL_DEVICE_NAME_STR);
1590
1591         if (!phone_name)
1592                 return;
1593
1594         if (strlen(phone_name) != 0) {
1595                 if (!g_utf8_validate(phone_name, -1, (const char **)&ptr))
1596                         *ptr = '\0';
1597
1598                 _bt_set_local_name(phone_name);
1599         }
1600         free(phone_name);
1601 }
1602
1603 void _bt_adapter_set_status(bt_status_t status)
1604 {
1605         BT_INFO("adapter_status changed [%d] -> [%d]", adapter_state, status);
1606         adapter_state = status;
1607 }
1608
1609 bt_status_t _bt_adapter_get_status(void)
1610 {
1611         return adapter_state;
1612 }
1613
1614 void _bt_set_disabled(int result)
1615 {
1616         int power_off_status = 0;
1617         int ret;
1618         int ret_pm_ignore;
1619         int pm_ignore_mode = 0;
1620
1621         ret = vconf_get_int(VCONFKEY_SYSMAN_POWER_OFF_STATUS, &power_off_status);
1622         BT_DBG("ret : %d, power_off_status : %d", ret, power_off_status);
1623
1624         ret_pm_ignore = vconf_get_int(VCONFKEY_PM_KEY_IGNORE, &pm_ignore_mode);
1625
1626         /* Update the vconf BT status in normal Deactivation case only */
1627         if (ret == 0 && power_off_status == VCONFKEY_SYSMAN_POWER_OFF_NONE &&
1628                 ret_pm_ignore == 0 && pm_ignore_mode != VCONFKEY_PM_KEY_LOCK) {
1629
1630                 BT_DBG("Update vconf for BT normal Deactivation");
1631
1632                 if (result == BLUETOOTH_ERROR_TIMEOUT)
1633                         if (vconf_set_int(BT_OFF_DUE_TO_TIMEOUT, 1) != 0)
1634                                 BT_ERR("Set vconf failed");
1635
1636                 /* Update Bluetooth Status to notify other modules */
1637                 if (vconf_set_int(VCONFKEY_BT_STATUS, VCONFKEY_BT_STATUS_OFF) != 0)
1638                         BT_ERR("Set vconf failed");
1639
1640                 if (_bt_eventsystem_set_value(SYS_EVENT_BT_STATE, EVT_KEY_BT_STATE,
1641                                                         EVT_VAL_BT_OFF) != ES_R_OK)
1642                         BT_ERR("Fail to set value");
1643         }
1644
1645         if (vconf_set_int(VCONFKEY_BT_DEVICE, VCONFKEY_BT_DEVICE_NONE) != 0)
1646                 BT_ERR("Set vconf failed\n");
1647
1648         _bt_cancel_queued_transfers();
1649         _bt_adapter_set_status(BT_DEACTIVATED);
1650         __bt_adapter_update_discovery_status(ADAPTER_DISCOVERY_STOPPED);
1651
1652         BT_INFO("Adapter disabled");
1653 }
1654