Add permanent log
[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
1033                 char uuids[512] = {0,};
1034                 char standard_prefix[2] = {0,};
1035                 int index = 0;
1036                 for (int i = 0; i < count; i++) {
1037                         if (i > 0)
1038                                 g_snprintf(uuids + (index++), 2, ",");
1039                         if (memcmp(service_list[i].uuid, standard_prefix, 2) == 0) {
1040                                 g_snprintf(uuids + index, 5, "%.2x%.2x",
1041                                         service_list[i].uuid[2], service_list[i].uuid[3]);
1042                                 index += 4;
1043                         } else {
1044                                 g_snprintf(uuids + index, 9, "%.2x%.2x..%.2x,",
1045                                         service_list[i].uuid[0], service_list[i].uuid[1], service_list[i].uuid[15]);
1046                                 index += 8;
1047                         }
1048                 }
1049                 BT_PERMANENT_LOG("UUIDs %s", uuids);
1050                 break;
1051         }
1052         case OAL_EVENT_ADAPTER_BONDED_DEVICE_LIST: {
1053                 int i;
1054                 int count;
1055                 bluetooth_device_address_t *addr_list;
1056
1057                 event_device_list_t *bonded_device_list = event_data;
1058                 count = bonded_device_list->num;
1059
1060                 addr_list = g_malloc0(count * sizeof(bluetooth_device_address_t));
1061                 for (i = 0; i < count; i++) {
1062                         memcpy(addr_list[i].addr,
1063                                         bonded_device_list->devices[i].addr,
1064                                         BLUETOOTH_ADDRESS_LENGTH);
1065                 }
1066
1067                 BT_INFO("Adapter Bonded device List count: [%d]", count);
1068                 _bt_device_handle_paired_address_list(addr_list, bonded_device_list->num);
1069                 g_free(addr_list);
1070                 break;
1071         }
1072         case OAL_EVENT_ADAPTER_PROPERTY_A2DP_ROLE: {
1073                 unsigned int *a2dp_role = event_data;
1074
1075                 BT_INFO("a2dp role: [%u]", *a2dp_role);
1076
1077                 __bt_handle_pending_a2dp_init(*a2dp_role);
1078
1079                 break;
1080         }
1081         default:
1082                 BT_ERR("Unhandled event..");
1083                 break;
1084         }
1085
1086         BT_DBG("-");
1087 }
1088
1089 int _bt_init_profiles()
1090 {
1091         int ret;
1092         BT_INFO("+");
1093
1094         /*TODO: Init bluetooth profiles */
1095         ret = _bt_hidhost_initialize();
1096         if (ret != BLUETOOTH_ERROR_NONE)
1097                 BT_ERR("_bt_hidhost_initialize Failed");
1098
1099         ret = _bt_hiddevice_initialize();
1100         if (ret != BLUETOOTH_ERROR_NONE)
1101                 BT_ERR("_bt_hiddevice_initialize Failed");
1102
1103         ret = _bt_socket_init();
1104         if (ret != BLUETOOTH_ERROR_NONE)
1105                 BT_ERR("_bt_socket_init Failed");
1106
1107         /* Initialize HFP Audio Gateway */
1108         ret = _bt_audio_initialize(BT_AG_MODULE);
1109         if (ret != BLUETOOTH_ERROR_NONE)
1110                 BT_ERR("_bt_audio_initialize(BT_AG_MODULE) Failed");
1111
1112         /* Registering callback for receiving audio services searched */
1113         ret = _bt_audio_initialize(BT_AUDIO_ALL_MODULE);
1114         if (ret != BLUETOOTH_ERROR_NONE)
1115                 BT_ERR("_bt_audio_initialize(BT_AUDIO_ALL_MODULE) Failed");
1116
1117         ret = _bt_hdp_init();
1118         if (ret != BLUETOOTH_ERROR_NONE)
1119                 BT_ERR("_bt_hdp_init Failed");
1120
1121         ret = _bt_gatt_init();
1122         if (ret != BLUETOOTH_ERROR_NONE)
1123                 BT_ERR("_bt_gatt_init Failed");
1124
1125         /* Initialize HF Client */
1126         ret = _bt_audio_initialize(BT_HFP_MODULE);
1127         if (ret != BLUETOOTH_ERROR_NONE)
1128                 BT_ERR("_bt_audio_initialize(BT_HFP_MODULE) Failed");
1129
1130         return BLUETOOTH_ERROR_NONE;
1131 }
1132
1133 int _bt_cleanup_profiles(void)
1134 {
1135         /* TODO: Cleanup bluetooth profiles */
1136         _bt_hidhost_deinitialize();
1137         _bt_socket_deinit();
1138 #if 0
1139         /* TODO: Cleanup bluetooth audio profiles */
1140         //_bt_audio_deinitialize(BT_A2DP_SOURCE_MODULE);
1141         //_bt_audio_deinitialize(BT_AVRCP_MODULE);
1142         //_bt_audio_deinitialize(BT_A2DP_SINK_MODULE);
1143         //_bt_audio_deinitialize(BT_AG_MODULE);
1144         //_bt_audio_deinitialize(BT_AVRCP_CTRL_MODULE);
1145         //_bt_audio_deinitialize(BT_AUDIO_ALL_MODULE);
1146
1147         a2dp_init_pending = TRUE;
1148 #endif
1149         _bt_hdp_deinit();
1150         _bt_gatt_deinit();
1151
1152         return BLUETOOTH_ERROR_NONE;
1153 }
1154
1155 /* OAL post initialization handler */
1156 static void __bt_post_oal_init(void)
1157 {
1158         int ret;
1159         int status = VCONFKEY_BT_STATUS_OFF;
1160
1161         BT_DBG("OAL initialized");
1162         if (vconf_get_int(VCONFKEY_BT_STATUS, &status) != 0)
1163                 BT_ERR("Fail to get the enabled value");
1164
1165 #if 0
1166         /* Update Bluetooth Status to OFF */
1167         if (vconf_set_int(VCONFKEY_BT_STATUS, VCONFKEY_BT_STATUS_OFF) != 0)
1168                 BT_ERR("Set vconf failed\n");
1169 #endif
1170
1171         if (status & VCONFKEY_BT_STATUS_ON) {
1172                 ret = _bt_enable_adapter();
1173                 if (ret != BLUETOOTH_ERROR_NONE)
1174                         BT_ERR("_bt_enable_adapter failed with error: %d", ret);
1175         }
1176 }
1177
1178 /* OAL initialization handler */
1179 static void __bt_handle_oal_initialisation(oal_event_t event)
1180 {
1181         BT_DBG("");
1182
1183         switch (event) {
1184         case OAL_EVENT_OAL_INITIALISED_SUCCESS:
1185                 __bt_post_oal_init();
1186                 break;
1187         case OAL_EVENT_OAL_INITIALISED_FAILED:
1188                 BT_ERR("OAL Initialisation Failed, terminate bt-service daemon..");
1189                 g_idle_add(_bt_terminate_service, NULL);
1190                 break;
1191         default:
1192                 BT_ERR("Unknown Event");
1193                 break;
1194         }
1195 }
1196
1197 static gboolean __bt_is_service_request_present(int service_function)
1198 {
1199         GSList *l;
1200         invocation_info_t *req_info;
1201
1202         BT_DBG("+");
1203
1204         /* Get method invocation context */
1205         for (l = _bt_get_invocation_list(); l != NULL; l = g_slist_next(l)) {
1206                 req_info = l->data;
1207                 if (req_info && req_info->service_function == service_function)
1208                         return TRUE;
1209         }
1210
1211         BT_DBG("-");
1212         return FALSE;
1213 }
1214
1215 /* Internal functions of core adapter service */
1216 static void __bt_adapter_handle_pending_requests(int service_function, void *user_data, unsigned int size)
1217 {
1218         GSList *l;
1219         GArray *out_param;
1220         invocation_info_t *req_info;
1221         BT_INFO("+");
1222
1223         /* Get method invocation context */
1224         for (l = _bt_get_invocation_list(); l != NULL; ) {
1225                 req_info = l->data;
1226                 l = g_slist_next(l);
1227                 if (req_info == NULL || req_info->service_function != service_function)
1228                         continue;
1229
1230                 /* Create out param */
1231                 out_param = g_array_new(FALSE, FALSE, sizeof(gchar));
1232
1233                 switch (service_function) {
1234                 case BT_ENABLE_ADAPTER:
1235                 case BT_DISABLE_ADAPTER: {
1236                         gboolean done = TRUE;
1237                         g_array_append_vals(out_param, &done, sizeof(gboolean));
1238                         break;
1239                 }
1240                 case BT_GET_LOCAL_NAME:
1241                 case BT_GET_LOCAL_ADDRESS:
1242                 case BT_GET_LOCAL_VERSION:
1243                         g_array_append_vals(out_param, user_data, size);
1244                         break;
1245                 case BT_IS_SERVICE_USED: {
1246                         unsigned int i;
1247                         gboolean used = FALSE;
1248                         unsigned char *uuid;
1249                         char uuid_str[BT_UUID_STRING_SIZE];
1250                         char *request_uuid = req_info->user_data;
1251                         service_uuid_t *service_list = user_data;
1252
1253                         BT_INFO("Check for service uuid: %s", request_uuid);
1254                         for (i = 0; i < size; i++) {
1255                                 uuid = service_list[i].uuid;
1256                                 _bt_service_convert_uuid_type_to_string(uuid_str, uuid);
1257                                 BT_INFO("Adapter Service: [%s]", uuid_str);
1258                                 if (strcasecmp(uuid_str, request_uuid) == 0) {
1259                                         BT_INFO("UUID matched!!");
1260                                         used = TRUE;
1261                                         break;
1262                                 }
1263                         }
1264
1265                         g_array_append_vals(out_param, &used, sizeof(gboolean));
1266                         break;
1267                 }
1268                 default:
1269                         BT_ERR("Unknown service function[%d]", service_function);
1270                 }
1271
1272                 _bt_service_method_return(req_info->context, out_param, req_info->result);
1273                 g_array_free(out_param, TRUE);
1274                 /* Now free invocation info for this request*/
1275                 _bt_free_info_from_invocation_list(req_info);
1276         }
1277 }
1278
1279 static void __bt_phone_name_changed_cb(keynode_t *node, void *data)
1280 {
1281         char *phone_name = NULL;
1282         char *ptr = NULL;
1283
1284         if (node == NULL)
1285                 return;
1286
1287         if (vconf_keynode_get_type(node) == VCONF_TYPE_STRING) {
1288                 phone_name = vconf_keynode_get_str(node);
1289
1290                 if (phone_name && strlen(phone_name) != 0) {
1291                         if (!g_utf8_validate(phone_name, -1,
1292                                         (const char **)&ptr))
1293                                 *ptr = '\0';
1294
1295                         _bt_set_local_name(phone_name);
1296                 }
1297         }
1298 }
1299
1300 /* Request return handlings */
1301 static gboolean __bt_adapter_post_set_enabled(gpointer user_data)
1302 {
1303         int result = BLUETOOTH_ERROR_NONE;
1304
1305         BT_INFO("__bt_adapter_post_set_enabled>>");
1306
1307         if (TIZEN_PROFILE_TV || !headed_plugin_info->plugin_headed_enabled) {
1308                 if (BLUETOOTH_ERROR_NONE != _bt_set_discoverable_mode(
1309                                 BLUETOOTH_DISCOVERABLE_MODE_GENERAL_DISCOVERABLE, 0))
1310                         BT_ERR("Fail to set discoverable mode");
1311         } else {
1312                 __bt_set_visible_mode();
1313         }
1314
1315         /* add the vconf noti handler */
1316         if (0 != vconf_notify_key_changed(VCONFKEY_SETAPPL_DEVICE_NAME_STR,
1317                         (vconf_callback_fn)__bt_phone_name_changed_cb, NULL))
1318                 BT_ERR("DEVICE_NAME key changed notification registration failed");
1319
1320         __bt_set_local_name();
1321
1322         /* Get All properties */
1323         if (OAL_STATUS_SUCCESS != adapter_get_properties())
1324                 BT_ERR("adapter_get_properties failed");
1325
1326         __bt_adapter_state_set_status(BT_ACTIVATED);
1327
1328         /*Send BT Enabled event to application */
1329         _bt_send_event(BT_ADAPTER_EVENT, BLUETOOTH_EVENT_ENABLED,
1330                         g_variant_new("(i)", result));
1331
1332         BT_PERMANENT_LOG("BT Enabled");
1333
1334         return FALSE;
1335 }
1336
1337 static gboolean __bt_adapter_post_set_disabled(gpointer user_data)
1338 {
1339         BT_INFO("_bt_adapter_post_set_disabled>>");
1340
1341         if (!TIZEN_PROFILE_TV) {
1342                 /* Add Adapter disabled post processing codes */
1343                 if (vconf_ignore_key_changed(VCONFKEY_SETAPPL_DEVICE_NAME_STR,
1344                                 (vconf_callback_fn)__bt_phone_name_changed_cb) != 0)
1345                         BT_ERR("vconf_ignore_key_changed failed");
1346         }
1347
1348         /* bt-service should be terminated when BT is off */
1349         if (!TIZEN_FEATURE_BT_USB_DONGLE) {
1350                 /* TODO: Implement to check if it is the recovery mode or not */
1351                 _bt_reliable_terminate_service(NULL);
1352         }
1353
1354         return FALSE;
1355 }
1356
1357 static void __bt_adapter_update_bt_enabled(void)
1358 {
1359         BT_INFO("_bt_adapter_update_bt_enabled >> Init profiles...");
1360         if (BLUETOOTH_ERROR_NONE != _bt_init_profiles())
1361                 BT_ERR("Bluetooth profile init failed");
1362
1363         _bt_device_handle_adapter_state(TRUE);
1364
1365         /* Update Bluetooth Status to notify other modules */
1366         if (vconf_set_int(VCONFKEY_BT_STATUS, VCONFKEY_BT_STATUS_ON) != 0)
1367                 BT_ERR("Set vconf failed\n");
1368
1369         if (vconf_set_int(VCONFKEY_BT_DEVICE, VCONFKEY_BT_DEVICE_NONE) != 0)
1370                 BT_ERR("Set vconf failed\n");
1371
1372         /* TODO:Add timer function to handle any further post processing */
1373         g_idle_add((GSourceFunc)__bt_adapter_post_set_enabled, NULL);
1374 }
1375
1376 static void __bt_adapter_update_bt_disabled(void)
1377 {
1378         int power_off_status = 0;
1379         int ret;
1380
1381         BT_INFO("_bt_adapter_update_bt_disabled >> Cleanup profiles...");
1382         _bt_cleanup_profiles();
1383
1384         _bt_device_handle_adapter_state(FALSE);
1385
1386         /* Update the vconf BT status in normal Deactivation case only */
1387         ret = vconf_get_int(VCONFKEY_SYSMAN_POWER_OFF_STATUS, &power_off_status);
1388         BT_DBG("ret : %d, power_off_status : %d", ret, power_off_status);
1389
1390         /* Update Bluetooth Status to notify other modules */
1391         if (vconf_set_int(VCONFKEY_BT_STATUS, VCONFKEY_BT_STATUS_OFF) != 0)
1392                 BT_ERR("Set vconf failed");
1393
1394         if (vconf_set_int(VCONFKEY_BT_DEVICE, VCONFKEY_BT_DEVICE_NONE) != 0)
1395                 BT_ERR("Set vconf failed\n");
1396
1397         /* TODO:Add timer function to handle any further post processing */
1398         g_idle_add((GSourceFunc)__bt_adapter_post_set_disabled, NULL);
1399
1400         /* Pending BT Disabled event before bt-service's termination */
1401 }
1402
1403 static void __bt_adapter_state_set_status(bt_status_t status)
1404 {
1405         BT_INFO("adapter_status changed [%d] -> [%d]", adapter_state, status);
1406         adapter_state = status;
1407 }
1408
1409 static void __bt_adapter_update_discovery_status(bt_adapter_discovery_state_t status)
1410 {
1411         BT_INFO("adapter_discovery_status changed [%d] -> [%d]", adapter_discovery_state, status);
1412         adapter_discovery_state = status;
1413 }
1414
1415 static void __bt_adapter_state_change_callback(int bt_status)
1416 {
1417         BT_INFO("__bt_adapter_state_change_callback: status [%d]", bt_status);
1418
1419         switch (bt_status) {
1420         case BT_DEACTIVATED:
1421                 __bt_adapter_state_set_status(BT_TERMINATING);
1422
1423                 /* Adapter is disabled, unregister event handlers */
1424                 _bt_service_unregister_event_handler_callback(BT_ADAPTER_MODULE);
1425                 //_bt_deinit_device_event_handler();
1426
1427                 /* Add Adapter disabled post processing codes */
1428                 __bt_adapter_update_bt_disabled();
1429                 break;
1430         case BT_ACTIVATED:
1431                 /* Add Adapter enabled post processing codes */
1432                 if (timer_id > 0) {
1433                         BT_DBG("g_source is removed");
1434                         g_source_remove(timer_id);
1435                         timer_id = 0;
1436                 }
1437                 __bt_adapter_update_bt_enabled();
1438                 break;
1439         default:
1440                 BT_ERR("Incorrect Bluetooth adapter state changed status");
1441
1442         }
1443 }
1444
1445 int _bt_set_adapter_request_state(int enable)
1446 {
1447         return oal_set_adapter_request_state(enable);
1448 }
1449
1450 int _bt_set_le_request_state(int enable)
1451 {
1452         return oal_set_le_request_state(enable);
1453 }
1454
1455 static int __bt_adapter_state_handle_request(gboolean enable)
1456 {
1457         int result = BLUETOOTH_ERROR_NONE;
1458         BT_DBG("");
1459
1460         switch (adapter_state) {
1461         case BT_ACTIVATING:
1462         case BT_DEACTIVATING:
1463                 BT_INFO("Should not be callded : state [%d]", adapter_state);
1464                 return BLUETOOTH_ERROR_INTERNAL;
1465                 break;
1466         case BT_ACTIVATED: {
1467                 BT_INFO("Adapter is currently in activated state, state [%d]",
1468                                 adapter_state);
1469                 if (enable) {
1470                         return BLUETOOTH_ERROR_DEVICE_ALREADY_ENABLED;
1471                 } else {
1472                         if (adapter_discovery_state == ADAPTER_DISCOVERY_STARTED ||
1473                                         adapter_discovery_state == ADAPTER_DISCOVERY_STARTING) {
1474                                 /*TODO Stop Discovery*/
1475                                 __bt_adapter_update_discovery_status(FALSE);
1476                         }
1477                         result = adapter_disable();
1478                         if (result != OAL_STATUS_SUCCESS) {
1479                                 BT_ERR("adapter_enable failed: [%d]", result);
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_DEACTIVATING);
1485                                 result = BLUETOOTH_ERROR_NONE;
1486                         }
1487                 }
1488                 break;
1489         }
1490         case BT_DEACTIVATED: {
1491                 BT_INFO("Adapter is currently in deactivated state, state [%d]",
1492                                 adapter_state);
1493                 if (!enable) {
1494                         return BLUETOOTH_ERROR_DEVICE_NOT_ENABLED;
1495                 } else {
1496                         result = adapter_enable();
1497                         if (result != OAL_STATUS_SUCCESS && result != OAL_STATUS_PENDING) {
1498                                 BT_ERR("adapter_enable failed: [%d]", result);
1499                                 adapter_disable();
1500                                 result = BLUETOOTH_ERROR_INTERNAL;
1501                                 /*TODO: perform if anything more needs to be done to handle failure */
1502                         } else {
1503                                 /* TODO: To be handled */
1504                                 __bt_adapter_state_set_status(BT_ACTIVATING);
1505                                 result = BLUETOOTH_ERROR_NONE;
1506                         }
1507                 }
1508                 break;
1509         }
1510         default:
1511                 BT_ERR("Unknown state: %d", adapter_state);
1512                 break;
1513         }
1514
1515         if (enable && result == BLUETOOTH_ERROR_NONE) {
1516                 /* Adapter enable request is successful, setup event handlers */
1517                 _bt_service_register_event_handler_callback(
1518                                 BT_ADAPTER_MODULE, __bt_adapter_event_handler);
1519                 _bt_device_state_handle_callback_set_request();
1520         }
1521         return result;
1522 }
1523
1524 static int __bt_adapter_state_discovery_request(gboolean enable,
1525                 unsigned short max_response, unsigned short duration,
1526                 unsigned int mask, gboolean is_custom,
1527                 bt_discovery_role_type_t role)
1528 {
1529         int result = BLUETOOTH_ERROR_NONE;
1530
1531         BT_DBG("+");
1532         switch (adapter_discovery_state) {
1533         case ADAPTER_DISCOVERY_STARTED: {
1534                 BT_INFO("Adapter is currently in discovery started state, state [%d]",
1535                                 adapter_discovery_state);
1536                 if (enable) {
1537                         return BLUETOOTH_ERROR_IN_PROGRESS;
1538                 } else {
1539                         result = adapter_stop_inquiry();
1540                         if (result != OAL_STATUS_SUCCESS) {
1541                                 BT_ERR("Discover stop failed: %d", result);
1542                                 result = BLUETOOTH_ERROR_INTERNAL;
1543                         } else {
1544                                 BT_ERR("Stop Discovery Triggered successfully");
1545                                 __bt_adapter_update_discovery_status(ADAPTER_DISCOVERY_STOPPING);
1546                                 result = BLUETOOTH_ERROR_NONE;
1547                         }
1548                 }
1549                 break;
1550         }
1551         case ADAPTER_DISCOVERY_STARTING: {
1552                 BT_INFO("Adapter is currently in discovery starting state, state [%d]",
1553                                 adapter_discovery_state);
1554
1555                 result = enable ?  BLUETOOTH_ERROR_IN_PROGRESS :
1556                                         BLUETOOTH_ERROR_DEVICE_BUSY;
1557
1558                 break;
1559         }
1560         case ADAPTER_DISCOVERY_STOPPED: {
1561                 BT_INFO("Adapter is currently in discovery stopped state, state [%d]",
1562                                 adapter_discovery_state);
1563                 if (!enable)
1564                         return BLUETOOTH_ERROR_NOT_IN_OPERATION;
1565                 else {
1566                         BT_DBG("max_resp: %u, duration: %u, cod: 0x%X", max_response, duration, mask);
1567
1568                         if (!is_custom)
1569                                 result = adapter_start_inquiry(duration);
1570                         else
1571                                 result = adapter_start_custom_inquiry(role);
1572
1573                         if (result != OAL_STATUS_SUCCESS) {
1574                                 BT_ERR("Start Discovery failed: %d", result);
1575                                 result = BLUETOOTH_ERROR_INTERNAL;
1576                         } else {
1577                                 BT_ERR("Start Discovery Triggered successfully");
1578                                 __bt_adapter_update_discovery_status(ADAPTER_DISCOVERY_STARTING);
1579                                 result = BLUETOOTH_ERROR_NONE;
1580                         }
1581                 }
1582                 break;
1583         }
1584         case ADAPTER_DISCOVERY_STOPPING: {
1585                 BT_INFO("Adapter is currently in discovery stopping state, state [%d]",
1586                                 adapter_discovery_state);
1587
1588                 result = enable ?  BLUETOOTH_ERROR_DEVICE_BUSY :
1589                                         BLUETOOTH_ERROR_NOT_IN_OPERATION;
1590
1591                 break;
1592         }
1593         default:
1594                 BT_ERR("Unknown state: %d", adapter_discovery_state);
1595                 break;
1596         }
1597
1598         BT_DBG("-");
1599         return result;
1600 }
1601
1602 static void __bt_adapter_discovery_state_change_callback(int bt_discovery_status)
1603 {
1604         BT_INFO("__bt_adapter_discovery_state_change_callback: status [%d]", bt_discovery_status);
1605         GVariant *param = NULL;
1606         int result = BLUETOOTH_ERROR_NONE;
1607
1608         switch (bt_discovery_status) {
1609         case ADAPTER_DISCOVERY_STOPPED:
1610         {
1611                 __bt_adapter_update_discovery_status(bt_discovery_status);
1612                 param = g_variant_new("(i)", result);
1613                 _bt_send_event(BT_ADAPTER_EVENT,
1614                                 BLUETOOTH_EVENT_DISCOVERY_FINISHED,
1615                                 param);
1616                 break;
1617         }
1618         case ADAPTER_DISCOVERY_STARTED:
1619         {
1620                 __bt_adapter_update_discovery_status(bt_discovery_status);
1621                 param = g_variant_new("(i)", result);
1622                 _bt_send_event(BT_ADAPTER_EVENT,
1623                                 BLUETOOTH_EVENT_DISCOVERY_STARTED,
1624                                 param);
1625                 break;
1626         }
1627         default:
1628                 BT_ERR("Incorrect Bluetooth adapter Discovery state changed status");
1629         }
1630 }
1631
1632 static void __bt_set_visible_mode(void)
1633 {
1634         int timeout = 0;
1635 #ifdef TIZEN_FEATURE_BT_DPM
1636         int discoverable_state = DPM_BT_ERROR;
1637 #endif
1638
1639         if (vconf_get_int(BT_FILE_VISIBLE_TIME, &timeout) != 0)
1640                 BT_ERR("Fail to get the timeout value");
1641
1642 #ifdef TIZEN_FEATURE_BT_DPM
1643         _bt_dpm_get_bluetooth_limited_discoverable_state(&discoverable_state);
1644         if (timeout == -1 || discoverable_state == DPM_RESTRICTED) {
1645                 if (_bt_set_discoverable_mode(
1646                                         BLUETOOTH_DISCOVERABLE_MODE_GENERAL_DISCOVERABLE,
1647                                         timeout) != BLUETOOTH_ERROR_NONE) {
1648                         if (vconf_set_int(BT_FILE_VISIBLE_TIME, 0) != 0)
1649                                 BT_ERR("Set vconf failed");
1650                 }
1651         } else {
1652                 if (_bt_set_discoverable_mode(
1653                                         BLUETOOTH_DISCOVERABLE_MODE_CONNECTABLE,
1654                                         timeout) != BLUETOOTH_ERROR_NONE) {
1655                         BT_ERR("Set connectable mode failed");
1656                 }
1657         }
1658 #else
1659         if (timeout == -1) {
1660                 if (_bt_set_discoverable_mode(
1661                                         BLUETOOTH_DISCOVERABLE_MODE_GENERAL_DISCOVERABLE,
1662                                         timeout) != BLUETOOTH_ERROR_NONE) {
1663                         if (vconf_set_int(BT_FILE_VISIBLE_TIME, 0) != 0)
1664                                 BT_ERR("Set vconf failed");
1665                 }
1666         } else {
1667                 if (_bt_set_discoverable_mode(
1668                                         BLUETOOTH_DISCOVERABLE_MODE_CONNECTABLE,
1669                                         timeout) != BLUETOOTH_ERROR_NONE) {
1670                         BT_ERR("Set connectable mode failed");
1671                 }
1672         }
1673 #endif
1674 }
1675
1676 static void __bt_set_local_name(void)
1677 {
1678         char *phone_name = NULL;
1679         char *ptr = NULL;
1680
1681         phone_name = vconf_get_str(VCONFKEY_SETAPPL_DEVICE_NAME_STR);
1682
1683         if (!phone_name)
1684                 return;
1685
1686         if (strlen(phone_name) != 0) {
1687                 if (!g_utf8_validate(phone_name, -1, (const char **)&ptr))
1688                         *ptr = '\0';
1689
1690                 _bt_set_local_name(phone_name);
1691         }
1692         free(phone_name);
1693 }
1694
1695 void _bt_adapter_set_status(bt_status_t status)
1696 {
1697         BT_INFO("adapter_status changed [%d] -> [%d]", adapter_state, status);
1698         adapter_state = status;
1699 }
1700
1701 bt_status_t _bt_adapter_get_status(void)
1702 {
1703         return adapter_state;
1704 }
1705
1706 void _bt_set_disabled(int result)
1707 {
1708         int power_off_status = 0;
1709         int ret;
1710         int ret_pm_ignore;
1711         int pm_ignore_mode = 0;
1712
1713         ret = vconf_get_int(VCONFKEY_SYSMAN_POWER_OFF_STATUS, &power_off_status);
1714         BT_DBG("ret : %d, power_off_status : %d", ret, power_off_status);
1715
1716         ret_pm_ignore = vconf_get_int(VCONFKEY_PM_KEY_IGNORE, &pm_ignore_mode);
1717
1718         /* Update the vconf BT status in normal Deactivation case only */
1719         if (ret == 0 && power_off_status == VCONFKEY_SYSMAN_POWER_OFF_NONE &&
1720                 ret_pm_ignore == 0 && pm_ignore_mode != VCONFKEY_PM_KEY_LOCK) {
1721
1722                 BT_DBG("Update vconf for BT normal Deactivation");
1723
1724                 if (result == BLUETOOTH_ERROR_TIMEOUT)
1725                         if (vconf_set_int(BT_OFF_DUE_TO_TIMEOUT, 1) != 0)
1726                                 BT_ERR("Set vconf failed");
1727
1728                 /* Update Bluetooth Status to notify other modules */
1729                 if (vconf_set_int(VCONFKEY_BT_STATUS, VCONFKEY_BT_STATUS_OFF) != 0)
1730                         BT_ERR("Set vconf failed");
1731
1732                 if (_bt_eventsystem_set_value(SYS_EVENT_BT_STATE, EVT_KEY_BT_STATE,
1733                                                         EVT_VAL_BT_OFF) != ES_R_OK)
1734                         BT_ERR("Fail to set value");
1735         }
1736
1737         if (vconf_set_int(VCONFKEY_BT_DEVICE, VCONFKEY_BT_DEVICE_NONE) != 0)
1738                 BT_ERR("Set vconf failed\n");
1739
1740         _bt_adapter_set_status(BT_DEACTIVATED);
1741         __bt_adapter_update_discovery_status(ADAPTER_DISCOVERY_STOPPED);
1742
1743         /* Send BT Disabled event to application */
1744         _bt_send_event(BT_ADAPTER_EVENT, BLUETOOTH_EVENT_DISABLED,
1745                         g_variant_new("(i)", result));
1746
1747         BT_INFO("Adapter disabled");
1748         BT_PERMANENT_LOG("BT Disabled");
1749 }
1750