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