Code clean up
[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_get_connectable(void)
677 {
678         int result;
679
680         BT_DBG("+");
681
682         result =  adapter_get_connectable();
683         if (result != OAL_STATUS_SUCCESS) {
684                 BT_ERR("adapter_get_connectable failed: %d", result);
685                 result = BLUETOOTH_ERROR_INTERNAL;
686         } else
687                 result = BLUETOOTH_ERROR_NONE;
688
689         BT_DBG("-");
690         return result;
691 }
692
693 int _bt_is_service_used(void)
694 {
695         int result;
696
697         BT_DBG("+");
698
699         result =  adapter_get_service_uuids();
700         if (result != OAL_STATUS_SUCCESS) {
701                 BT_ERR("adapter_get_service_uuids failed: %d", result);
702                 result = BLUETOOTH_ERROR_INTERNAL;
703         } else {
704                 result = BLUETOOTH_ERROR_NONE;
705         }
706
707         BT_DBG("-");
708         return result;
709 }
710
711 int _bt_adapter_get_bonded_devices(void)
712 {
713         int result = BLUETOOTH_ERROR_NONE;
714
715         BT_DBG("+");
716         result =  adapter_get_bonded_devices();
717         if (result != OAL_STATUS_SUCCESS) {
718                 BT_ERR("adapter_get_bonded_devices failed: %d", result);
719                 result = BLUETOOTH_ERROR_INTERNAL;
720         } else
721                 result = BLUETOOTH_ERROR_NONE;
722
723         BT_DBG("-");
724         return result;
725 }
726
727 int _bt_get_profile_connected_devices(char *profile_uuid, GArray **addr_list)
728 {
729         BT_DBG("+");
730         GDBusConnection *conn;
731         GDBusProxy *manager_proxy;
732         GVariant *result = NULL;
733         GVariant *result1 = NULL;
734         GVariantIter *iter = NULL;
735         GError *error = NULL;
736         char *object_path = NULL;
737         GVariantIter *interface_iter;
738         char *interface_str = NULL;
739         GDBusProxy *device_proxy = NULL;
740         gboolean is_connected = FALSE;
741
742         conn = _bt_gdbus_get_system_gconn();
743         retv_if(conn == NULL, BLUETOOTH_ERROR_INTERNAL);
744
745         manager_proxy = _bt_get_manager_proxy();
746         retv_if(manager_proxy == NULL, BLUETOOTH_ERROR_INTERNAL);
747
748         result = g_dbus_proxy_call_sync(manager_proxy, "GetManagedObjects",
749                         NULL,
750                         G_DBUS_CALL_FLAGS_NONE,
751                         -1,
752                         NULL,
753                         NULL);
754
755         if (!result) {
756                 if (error != NULL) {
757                         BT_ERR("Failed to GetManagedObjects (Error: %s)", error->message);
758                         g_clear_error(&error);
759                         error = NULL;
760                 } else
761                         BT_ERR("Failed to Failed to GetManagedObjects");
762                 return BLUETOOTH_ERROR_INTERNAL;
763         }
764
765         /* signature of GetManagedObjects:  a{oa{sa{sv}}} */
766         g_variant_get(result, "(a{oa{sa{sv}}})", &iter);
767
768         /* Parse the signature:  oa{sa{sv}}} */
769         while (g_variant_iter_loop(iter, "{&oa{sa{sv}}}", &object_path, &interface_iter)) {
770                 if (object_path == NULL)
771                         continue;
772
773                 while (g_variant_iter_loop(interface_iter, "{sa{sv}}",
774                                         &interface_str, NULL)) {
775                         if (g_strcmp0(interface_str, "org.bluez.Device1") == 0) {
776                                 BT_DBG("Found a device: %s", object_path);
777                                 g_free(interface_str);
778
779                                 device_proxy = g_dbus_proxy_new_sync(conn, G_DBUS_PROXY_FLAGS_NONE,
780                                                 NULL, BT_BLUEZ_NAME,
781                                                 object_path, BT_DEVICE_INTERFACE,  NULL, NULL);
782
783                                 if (device_proxy == NULL) {
784                                         BT_DBG("Device don't have this service");
785                                         break;
786                                 }
787
788                                 result1 = g_dbus_proxy_call_sync(device_proxy, "IsConnectedProfile",
789                                                 g_variant_new("(s)", profile_uuid),
790                                                 G_DBUS_CALL_FLAGS_NONE,
791                                                 -1,
792                                                 NULL,
793                                                 &error);
794
795                                 if (result1 == NULL) {
796                                         BT_ERR("Error occured in Proxy call");
797                                         if (error) {
798                                                 BT_ERR("Error occured in Proxy call [%s]\n", error->message);
799                                                 g_error_free(error);
800                                                 error = NULL;
801                                         }
802                                         g_object_unref(device_proxy);
803                                         break;
804                                 }
805                                 g_variant_get(result1, "(b)", &is_connected);
806
807                                 if (is_connected == TRUE) {
808                                         char address[BT_ADDRESS_STRING_SIZE];
809                                         bluetooth_device_address_t *addr = NULL;
810
811                                         _bt_convert_device_path_to_address(object_path, address);
812
813                                         addr = g_malloc0(sizeof(bluetooth_device_address_t));
814                                         _bt_convert_addr_string_to_type(addr->addr, address);
815
816                                         g_array_append_vals(*addr_list, addr,
817                                                         sizeof(bluetooth_device_address_t));
818                                 }
819
820                                 g_variant_unref(result1);
821                                 g_object_unref(device_proxy);
822
823                                 break;
824                         }
825                 }
826         }
827
828         g_variant_unref(result);
829         g_variant_iter_free(iter);
830
831         BT_DBG("-");
832         return BLUETOOTH_ERROR_NONE;
833 }
834
835 static gboolean __bt_disconnect_all(void)
836 {
837         int i;
838         gboolean ret = FALSE;
839         GArray *device_list;
840         guint size;
841         int result;
842         bluetooth_device_info_t *info;
843
844         BT_DBG("");
845         device_list = g_array_new(FALSE, FALSE, sizeof(gchar));
846
847         BT_DBG("The length of device list after the initialisation is [%d]", device_list->len);
848
849         _bt_service_get_bonded_dev_list(&device_list);
850
851         size = (device_list->len) / sizeof(bluetooth_device_info_t);
852
853         for (i = 0; i < size; i++) {
854                 info = &g_array_index(device_list,
855                                 bluetooth_device_info_t, i);
856                 if (info->connected != BLUETOOTH_CONNECTED_LINK_NONE) {
857                         BT_DBG("Found Connected Device");
858                         result = _bt_disconnect_device(&info->device_address);
859                         if (result != BLUETOOTH_ERROR_NONE) {
860                                 BT_ERR("Cannot disconnect all the devices. bt_disconnect_device Failed");
861                                 g_array_free(device_list, TRUE);
862                                 return ret;
863                         }
864                 }
865         }
866         ret = TRUE;
867         g_array_free(device_list, TRUE);
868
869         return ret;
870 }
871
872 static void __bt_handle_pending_a2dp_init(unsigned int a2dp_role)
873 {
874         int ret;
875
876         if (!a2dp_init_pending)
877                 return;
878
879         BT_DBG("+");
880         a2dp_init_pending = FALSE;
881
882         if (a2dp_role == BT_A2DP_SINK_ROLE) {
883                 BT_INFO("Enable A2DP Sink role");
884                 /* Initialize A2DP Sink */
885                 ret = _bt_audio_initialize(BT_A2DP_SINK_MODULE);
886                 if (ret != BLUETOOTH_ERROR_NONE)
887                         BT_ERR("_bt_audio_initialize(BT_A2DP_SINK_MODULE) Failed");
888
889                 /* Initialize AVRCP Controller */
890                 ret = _bt_audio_initialize(BT_AVRCP_CTRL_MODULE);
891                 if (ret != BLUETOOTH_ERROR_NONE)
892                         BT_ERR("_bt_audio_initialize(BT_AVRCP_CTRL_MODULE) Failed");
893
894                 _bt_audio_set_current_role(BLUETOOTH_A2DP_SINK);
895                 return;
896         }
897
898         BT_INFO("Enable A2DP Source role");
899         /* Initialize A2DP Source */
900         ret = _bt_audio_initialize(BT_A2DP_SOURCE_MODULE);
901         if (ret != BLUETOOTH_ERROR_NONE)
902                 BT_ERR("_bt_audio_initialize(BT_A2DP_SOURCE_MODULE) Failed");
903
904         /* Initialize AVRCP Target */
905         ret = _bt_audio_initialize(BT_AVRCP_MODULE);
906         if (ret != BLUETOOTH_ERROR_NONE)
907                 BT_ERR("_bt_audio_initialize(BT_AVRCP_MODULE) Failed");
908
909         _bt_audio_set_current_role(BLUETOOTH_A2DP_SOURCE);
910         BT_DBG("-");
911 }
912
913 static void __bt_adapter_event_handler(int event_type, gpointer event_data)
914 {
915         int result = BLUETOOTH_ERROR_NONE;
916
917         BT_DBG("+");
918
919         switch (event_type) {
920         case OAL_EVENT_OAL_INITIALISED_SUCCESS:
921         case OAL_EVENT_OAL_INITIALISED_FAILED:
922                 __bt_handle_oal_initialisation(event_type);
923                 break;
924         case OAL_EVENT_ADAPTER_ENABLED:
925                 __bt_adapter_state_change_callback(BT_ACTIVATED);
926                 break;
927         case OAL_EVENT_ADAPTER_DISABLED:
928                 __bt_adapter_state_change_callback(BT_DEACTIVATED);
929                 break;
930         case OAL_EVENT_ADAPTER_INQUIRY_STARTED:
931                 __bt_adapter_discovery_state_change_callback(ADAPTER_DISCOVERY_STARTED);
932                 break;
933         case OAL_EVENT_ADAPTER_INQUIRY_FINISHED:
934                 __bt_adapter_discovery_state_change_callback(ADAPTER_DISCOVERY_STOPPED);
935                 break;
936         case OAL_EVENT_ADAPTER_PROPERTY_ADDRESS: {
937                 bt_address_t *bd_addr = event_data;
938                 bluetooth_device_address_t local_address;
939
940                 /* Copy data */
941                 memcpy(local_address.addr, bd_addr->addr, BT_ADDRESS_LENGTH_MAX);
942                 BT_DBG("Adapter address: [%2.2X:%2.2X:%2.2X:%2.2X:%2.2X:%2.2X]",
943                                 local_address.addr[0], local_address.addr[1], local_address.addr[2],
944                                 local_address.addr[3], local_address.addr[4], local_address.addr[5]);
945
946                 __bt_adapter_handle_pending_requests(BT_GET_LOCAL_ADDRESS,
947                                 (void *) &local_address, sizeof(bluetooth_device_address_t));
948                 break;
949         }
950         case OAL_EVENT_ADAPTER_PROPERTY_NAME: {
951                 char *name = event_data;
952                 BT_DBG("Adapter Name: %s", name);
953
954                 if (__bt_is_service_request_present(BT_GET_LOCAL_NAME)) {
955                         bluetooth_device_name_t local_name;
956
957                         memset(&local_name, 0x00, sizeof(bluetooth_device_name_t));
958                         g_strlcpy(local_name.name,
959                                 (const gchar *)name, BLUETOOTH_DEVICE_NAME_LENGTH_MAX);
960                         __bt_adapter_handle_pending_requests(BT_GET_LOCAL_NAME,
961                                 (void *) &local_name, sizeof(bluetooth_device_name_t));
962                 } else {
963                         /* Send event to application */
964                         _bt_send_event(BT_ADAPTER_EVENT,
965                                         BLUETOOTH_EVENT_LOCAL_NAME_CHANGED,
966                                         g_variant_new("(is)", result, name));
967                 }
968                 break;
969         }
970         case OAL_EVENT_ADAPTER_PROPERTY_VERSION: {
971                 char *ver = event_data;
972                 bluetooth_version_t local_version;
973
974                 memset(&local_version, 0x00, sizeof(bluetooth_version_t));
975                 g_strlcpy(local_version.version,
976                                 (const gchar *)ver, BLUETOOTH_VERSION_LENGTH_MAX);
977                 BT_DBG("BT Version: %s", local_version.version);
978
979                 __bt_adapter_handle_pending_requests(BT_GET_LOCAL_VERSION,
980                                 (void *) &local_version, sizeof(bluetooth_version_t));
981                 break;
982         }
983         case OAL_EVENT_ADAPTER_MODE_NON_CONNECTABLE: {
984                 int mode = -1;
985                 gboolean connectable = FALSE;
986
987                 BT_INFO("Adapter discoverable mode:"
988                                 " BLUETOOTH_DISCOVERABLE_MODE_NON_CONNECTABLE");
989
990                 if (__bt_is_service_request_present(BT_GET_CONNECTABLE)) {
991                         __bt_adapter_handle_pending_requests(BT_GET_CONNECTABLE,
992                                 (void *) &connectable, sizeof(gboolean));
993
994                 } else {
995                         _bt_send_event(BT_ADAPTER_EVENT,
996                                         BLUETOOTH_EVENT_CONNECTABLE_CHANGED,
997                                         g_variant_new("(b)", connectable));
998
999                         _bt_send_event(BT_ADAPTER_EVENT,
1000                                         BLUETOOTH_EVENT_DISCOVERABLE_MODE_CHANGED,
1001                                         g_variant_new("(in)", result, mode));
1002                 }
1003                 break;
1004         }
1005         case OAL_EVENT_ADAPTER_MODE_CONNECTABLE: {
1006                 int mode;
1007                 gboolean connectable = TRUE;
1008
1009                 BT_INFO("Adapter discoverable mode:"
1010                                 " BLUETOOTH_DISCOVERABLE_MODE_CONNECTABLE");
1011
1012                 if (__bt_is_service_request_present(BT_GET_CONNECTABLE)) {
1013                         __bt_adapter_handle_pending_requests(BT_GET_CONNECTABLE,
1014                                 (void *) &connectable, sizeof(gboolean));
1015
1016                 } else {
1017
1018                         _bt_send_event(BT_ADAPTER_EVENT,
1019                                         BLUETOOTH_EVENT_CONNECTABLE_CHANGED,
1020                                         g_variant_new("(b)", connectable));
1021
1022                         mode = BLUETOOTH_DISCOVERABLE_MODE_CONNECTABLE;
1023                         _bt_send_event(BT_ADAPTER_EVENT,
1024                                         BLUETOOTH_EVENT_DISCOVERABLE_MODE_CHANGED,
1025                                         g_variant_new("(in)", result, mode));
1026                 }
1027                 break;
1028         }
1029         case OAL_EVENT_ADAPTER_MODE_DISCOVERABLE: {
1030                 int mode;
1031                 gboolean connectable = TRUE;
1032
1033                 BT_INFO("Adapter discoverable mode:"
1034                                 " BLUETOOTH_DISCOVERABLE_MODE_GENERAL_DISCOVERABLE");
1035
1036                 if (__bt_is_service_request_present(BT_GET_CONNECTABLE)) {
1037                         __bt_adapter_handle_pending_requests(BT_GET_CONNECTABLE,
1038                                 (void *) &connectable, sizeof(gboolean));
1039
1040                 } else {
1041                         /* Send event to application */
1042                         mode = BLUETOOTH_DISCOVERABLE_MODE_GENERAL_DISCOVERABLE;
1043                         _bt_send_event(BT_ADAPTER_EVENT,
1044                                         BLUETOOTH_EVENT_DISCOVERABLE_MODE_CHANGED,
1045                                         g_variant_new("(in)", result, mode));
1046                 }
1047                 break;
1048         }
1049         case OAL_EVENT_ADAPTER_MODE_DISCOVERABLE_TIMEOUT: {
1050                 int *timeout = event_data;
1051                 int mode;
1052
1053                 BT_INFO("Discoverable timeout: [%d]", *timeout);
1054
1055                 /* Send event to application */
1056                 _bt_get_discoverable_mode(&mode);
1057                 _bt_send_event(BT_ADAPTER_EVENT,
1058                                 BLUETOOTH_EVENT_DISCOVERABLE_MODE_CHANGED,
1059                                 g_variant_new("(in)", result, mode));
1060                 break;
1061         }
1062         case OAL_EVENT_ADAPTER_PROPERTY_SERVICES: {
1063                 int count;
1064                 service_uuid_t *service_list;
1065                 event_adapter_services_t *list = event_data;
1066
1067                 count = list->num;
1068                 service_list = list->service_list;
1069                 __bt_adapter_handle_pending_requests(BT_IS_SERVICE_USED, service_list, count);
1070
1071                 char uuids[512] = {0,};
1072                 char standard_prefix[2] = {0,};
1073                 int index = 0;
1074                 for (int i = 0; i < count; i++) {
1075                         if (i > 0)
1076                                 g_snprintf(uuids + (index++), 2, ",");
1077                         if (memcmp(service_list[i].uuid, standard_prefix, 2) == 0) {
1078                                 g_snprintf(uuids + index, 5, "%.2x%.2x",
1079                                         service_list[i].uuid[2], service_list[i].uuid[3]);
1080                                 index += 4;
1081                         } else {
1082                                 g_snprintf(uuids + index, 9, "%.2x%.2x..%.2x,",
1083                                         service_list[i].uuid[0], service_list[i].uuid[1], service_list[i].uuid[15]);
1084                                 index += 8;
1085                         }
1086                 }
1087                 BT_PERMANENT_LOG("UUIDs %s", uuids);
1088                 break;
1089         }
1090         case OAL_EVENT_ADAPTER_BONDED_DEVICE_LIST: {
1091                 int i;
1092                 int count;
1093                 bluetooth_device_address_t *addr_list;
1094
1095                 event_device_list_t *bonded_device_list = event_data;
1096                 count = bonded_device_list->num;
1097
1098                 addr_list = g_malloc0(count * sizeof(bluetooth_device_address_t));
1099                 for (i = 0; i < count; i++) {
1100                         memcpy(addr_list[i].addr,
1101                                         bonded_device_list->devices[i].addr,
1102                                         BLUETOOTH_ADDRESS_LENGTH);
1103                 }
1104
1105                 BT_INFO("Adapter Bonded device List count: [%d]", count);
1106                 _bt_device_handle_paired_address_list(addr_list, bonded_device_list->num);
1107                 g_free(addr_list);
1108                 break;
1109         }
1110         case OAL_EVENT_ADAPTER_PROPERTY_A2DP_ROLE: {
1111                 unsigned int *a2dp_role = event_data;
1112
1113                 BT_INFO("a2dp role: [%u]", *a2dp_role);
1114
1115                 __bt_handle_pending_a2dp_init(*a2dp_role);
1116
1117                 break;
1118         }
1119         default:
1120                 BT_ERR("Unhandled event..");
1121                 break;
1122         }
1123
1124         BT_DBG("-");
1125 }
1126
1127 int _bt_init_profiles()
1128 {
1129         int ret;
1130         BT_INFO("+");
1131
1132         /*TODO: Init bluetooth profiles */
1133         ret = _bt_hidhost_initialize();
1134         if (ret != BLUETOOTH_ERROR_NONE)
1135                 BT_ERR("_bt_hidhost_initialize Failed");
1136
1137         ret = _bt_hiddevice_initialize();
1138         if (ret != BLUETOOTH_ERROR_NONE)
1139                 BT_ERR("_bt_hiddevice_initialize Failed");
1140
1141         ret = _bt_socket_init();
1142         if (ret != BLUETOOTH_ERROR_NONE)
1143                 BT_ERR("_bt_socket_init Failed");
1144
1145         /* Initialize HFP Audio Gateway */
1146         ret = _bt_audio_initialize(BT_AG_MODULE);
1147         if (ret != BLUETOOTH_ERROR_NONE)
1148                 BT_ERR("_bt_audio_initialize(BT_AG_MODULE) Failed");
1149
1150         /* Registering callback for receiving audio services searched */
1151         ret = _bt_audio_initialize(BT_AUDIO_ALL_MODULE);
1152         if (ret != BLUETOOTH_ERROR_NONE)
1153                 BT_ERR("_bt_audio_initialize(BT_AUDIO_ALL_MODULE) Failed");
1154
1155         ret = _bt_hdp_init();
1156         if (ret != BLUETOOTH_ERROR_NONE)
1157                 BT_ERR("_bt_hdp_init Failed");
1158
1159         ret = _bt_gatt_init();
1160         if (ret != BLUETOOTH_ERROR_NONE)
1161                 BT_ERR("_bt_gatt_init Failed");
1162
1163         /* Initialize HF Client */
1164         ret = _bt_audio_initialize(BT_HFP_MODULE);
1165         if (ret != BLUETOOTH_ERROR_NONE)
1166                 BT_ERR("_bt_audio_initialize(BT_HFP_MODULE) Failed");
1167
1168         return BLUETOOTH_ERROR_NONE;
1169 }
1170
1171 int _bt_cleanup_profiles(void)
1172 {
1173         /* TODO: Cleanup bluetooth profiles */
1174         _bt_hidhost_deinitialize();
1175         _bt_socket_deinit();
1176 #if 0
1177         /* TODO: Cleanup bluetooth audio profiles */
1178         //_bt_audio_deinitialize(BT_A2DP_SOURCE_MODULE);
1179         //_bt_audio_deinitialize(BT_AVRCP_MODULE);
1180         //_bt_audio_deinitialize(BT_A2DP_SINK_MODULE);
1181         //_bt_audio_deinitialize(BT_AG_MODULE);
1182         //_bt_audio_deinitialize(BT_AVRCP_CTRL_MODULE);
1183         //_bt_audio_deinitialize(BT_AUDIO_ALL_MODULE);
1184
1185         a2dp_init_pending = TRUE;
1186 #endif
1187         _bt_hdp_deinit();
1188         _bt_gatt_deinit();
1189
1190         return BLUETOOTH_ERROR_NONE;
1191 }
1192
1193 /* OAL post initialization handler */
1194 static void __bt_post_oal_init(void)
1195 {
1196         int ret;
1197         int status = VCONFKEY_BT_STATUS_OFF;
1198
1199         BT_DBG("OAL initialized");
1200         if (vconf_get_int(VCONFKEY_BT_STATUS, &status) != 0)
1201                 BT_ERR("Fail to get the enabled value");
1202
1203 #if 0
1204         /* Update Bluetooth Status to OFF */
1205         if (vconf_set_int(VCONFKEY_BT_STATUS, VCONFKEY_BT_STATUS_OFF) != 0)
1206                 BT_ERR("Set vconf failed\n");
1207 #endif
1208
1209         if (status & VCONFKEY_BT_STATUS_ON) {
1210                 ret = _bt_enable_adapter();
1211                 if (ret != BLUETOOTH_ERROR_NONE)
1212                         BT_ERR("_bt_enable_adapter failed with error: %d", ret);
1213         }
1214 }
1215
1216 /* OAL initialization handler */
1217 static void __bt_handle_oal_initialisation(oal_event_t event)
1218 {
1219         BT_DBG("");
1220
1221         switch (event) {
1222         case OAL_EVENT_OAL_INITIALISED_SUCCESS:
1223                 __bt_post_oal_init();
1224                 break;
1225         case OAL_EVENT_OAL_INITIALISED_FAILED:
1226                 BT_ERR("OAL Initialisation Failed, terminate bt-service daemon..");
1227                 g_idle_add(_bt_terminate_service, NULL);
1228                 break;
1229         default:
1230                 BT_ERR("Unknown Event");
1231                 break;
1232         }
1233 }
1234
1235 static gboolean __bt_is_service_request_present(int service_function)
1236 {
1237         GSList *l;
1238         invocation_info_t *req_info;
1239
1240         BT_DBG("+");
1241
1242         /* Get method invocation context */
1243         for (l = _bt_get_invocation_list(); l != NULL; l = g_slist_next(l)) {
1244                 req_info = l->data;
1245                 if (req_info && req_info->service_function == service_function)
1246                         return TRUE;
1247         }
1248
1249         BT_DBG("-");
1250         return FALSE;
1251 }
1252
1253 /* Internal functions of core adapter service */
1254 static void __bt_adapter_handle_pending_requests(int service_function, void *user_data, unsigned int size)
1255 {
1256         GSList *l;
1257         GArray *out_param;
1258         invocation_info_t *req_info;
1259         BT_INFO("+");
1260
1261         /* Get method invocation context */
1262         for (l = _bt_get_invocation_list(); l != NULL; ) {
1263                 req_info = l->data;
1264                 l = g_slist_next(l);
1265                 if (req_info == NULL || req_info->service_function != service_function)
1266                         continue;
1267
1268                 /* Create out param */
1269                 out_param = g_array_new(FALSE, FALSE, sizeof(gchar));
1270
1271                 switch (service_function) {
1272                 case BT_ENABLE_ADAPTER:
1273                 case BT_DISABLE_ADAPTER: {
1274                         gboolean done = TRUE;
1275                         g_array_append_vals(out_param, &done, sizeof(gboolean));
1276                         break;
1277                 }
1278                 case BT_GET_CONNECTABLE:
1279                 case BT_GET_LOCAL_NAME:
1280                 case BT_GET_LOCAL_ADDRESS:
1281                 case BT_GET_LOCAL_VERSION:
1282                         g_array_append_vals(out_param, user_data, size);
1283                         break;
1284                 case BT_IS_SERVICE_USED: {
1285                         unsigned int i;
1286                         gboolean used = FALSE;
1287                         unsigned char *uuid;
1288                         char uuid_str[BT_UUID_STRING_SIZE];
1289                         char *request_uuid = req_info->user_data;
1290                         service_uuid_t *service_list = user_data;
1291
1292                         BT_INFO("Check for service uuid: %s", request_uuid);
1293                         for (i = 0; i < size; i++) {
1294                                 uuid = service_list[i].uuid;
1295                                 _bt_service_convert_uuid_type_to_string(uuid_str, uuid);
1296                                 BT_INFO("Adapter Service: [%s]", uuid_str);
1297                                 if (strcasecmp(uuid_str, request_uuid) == 0) {
1298                                         BT_INFO("UUID matched!!");
1299                                         used = TRUE;
1300                                         break;
1301                                 }
1302                         }
1303
1304                         g_array_append_vals(out_param, &used, sizeof(gboolean));
1305                         break;
1306                 }
1307                 default:
1308                         BT_ERR("Unknown service function[%d]", service_function);
1309                 }
1310
1311                 _bt_service_method_return(req_info->context, out_param, req_info->result);
1312                 g_array_free(out_param, TRUE);
1313                 /* Now free invocation info for this request*/
1314                 _bt_free_info_from_invocation_list(req_info);
1315         }
1316 }
1317
1318 static void __bt_phone_name_changed_cb(keynode_t *node, void *data)
1319 {
1320         char *phone_name = NULL;
1321         char *ptr = NULL;
1322
1323         if (node == NULL)
1324                 return;
1325
1326         if (vconf_keynode_get_type(node) == VCONF_TYPE_STRING) {
1327                 phone_name = vconf_keynode_get_str(node);
1328
1329                 if (phone_name && strlen(phone_name) != 0) {
1330                         if (!g_utf8_validate(phone_name, -1,
1331                                         (const char **)&ptr))
1332                                 *ptr = '\0';
1333
1334                         _bt_set_local_name(phone_name);
1335                 }
1336         }
1337 }
1338
1339 /* Request return handlings */
1340 static gboolean __bt_adapter_post_set_enabled(gpointer user_data)
1341 {
1342         int result = BLUETOOTH_ERROR_NONE;
1343
1344         BT_INFO("__bt_adapter_post_set_enabled>>");
1345
1346         if (TIZEN_PROFILE_TV || !headed_plugin_info->plugin_headed_enabled) {
1347                 if (BLUETOOTH_ERROR_NONE != _bt_set_discoverable_mode(
1348                                 BLUETOOTH_DISCOVERABLE_MODE_GENERAL_DISCOVERABLE, 0))
1349                         BT_ERR("Fail to set discoverable mode");
1350         } else {
1351                 __bt_set_visible_mode();
1352         }
1353
1354         /* add the vconf noti handler */
1355         if (0 != vconf_notify_key_changed(VCONFKEY_SETAPPL_DEVICE_NAME_STR,
1356                         (vconf_callback_fn)__bt_phone_name_changed_cb, NULL))
1357                 BT_ERR("DEVICE_NAME key changed notification registration failed");
1358
1359         __bt_set_local_name();
1360
1361         /* Get All properties */
1362         if (OAL_STATUS_SUCCESS != adapter_get_properties())
1363                 BT_ERR("adapter_get_properties failed");
1364
1365         __bt_adapter_state_set_status(BT_ACTIVATED);
1366
1367         /*Send BT Enabled event to application */
1368         _bt_send_event(BT_ADAPTER_EVENT, BLUETOOTH_EVENT_ENABLED,
1369                         g_variant_new("(i)", result));
1370
1371         BT_PERMANENT_LOG("BT Enabled");
1372
1373         return FALSE;
1374 }
1375
1376 static gboolean __bt_adapter_post_set_disabled(gpointer user_data)
1377 {
1378         BT_INFO("_bt_adapter_post_set_disabled>>");
1379
1380         if (!TIZEN_PROFILE_TV) {
1381                 /* Add Adapter disabled post processing codes */
1382                 if (vconf_ignore_key_changed(VCONFKEY_SETAPPL_DEVICE_NAME_STR,
1383                                 (vconf_callback_fn)__bt_phone_name_changed_cb) != 0)
1384                         BT_ERR("vconf_ignore_key_changed failed");
1385         }
1386
1387         /* bt-service should be terminated when BT is off */
1388         if (!TIZEN_FEATURE_BT_USB_DONGLE) {
1389                 /* TODO: Implement to check if it is the recovery mode or not */
1390                 _bt_reliable_terminate_service(NULL);
1391         } else {
1392                 _bt_set_disabled(BLUETOOTH_ERROR_NONE);
1393         }
1394
1395         return FALSE;
1396 }
1397
1398 static void __bt_adapter_update_bt_enabled(void)
1399 {
1400         BT_INFO("_bt_adapter_update_bt_enabled >> Init profiles...");
1401         if (BLUETOOTH_ERROR_NONE != _bt_init_profiles())
1402                 BT_ERR("Bluetooth profile init failed");
1403
1404         _bt_device_handle_adapter_state(TRUE);
1405
1406         /* Update Bluetooth Status to notify other modules */
1407         if (vconf_set_int(VCONFKEY_BT_STATUS, VCONFKEY_BT_STATUS_ON) != 0)
1408                 BT_ERR("Set vconf failed\n");
1409
1410         if (vconf_set_int(VCONFKEY_BT_DEVICE, VCONFKEY_BT_DEVICE_NONE) != 0)
1411                 BT_ERR("Set vconf failed\n");
1412
1413         /* TODO:Add timer function to handle any further post processing */
1414         g_idle_add((GSourceFunc)__bt_adapter_post_set_enabled, NULL);
1415 }
1416
1417 static void __bt_adapter_update_bt_disabled(void)
1418 {
1419         int power_off_status = 0;
1420         int ret;
1421
1422         BT_INFO("_bt_adapter_update_bt_disabled >> Cleanup profiles...");
1423         _bt_cleanup_profiles();
1424
1425         _bt_device_handle_adapter_state(FALSE);
1426
1427         /* Update the vconf BT status in normal Deactivation case only */
1428         ret = vconf_get_int(VCONFKEY_SYSMAN_POWER_OFF_STATUS, &power_off_status);
1429         BT_DBG("ret : %d, power_off_status : %d", ret, power_off_status);
1430
1431         /* Update Bluetooth Status to notify other modules */
1432         if (vconf_set_int(VCONFKEY_BT_STATUS, VCONFKEY_BT_STATUS_OFF) != 0)
1433                 BT_ERR("Set vconf failed");
1434
1435         if (vconf_set_int(VCONFKEY_BT_DEVICE, VCONFKEY_BT_DEVICE_NONE) != 0)
1436                 BT_ERR("Set vconf failed\n");
1437
1438         /* TODO:Add timer function to handle any further post processing */
1439         g_idle_add((GSourceFunc)__bt_adapter_post_set_disabled, NULL);
1440
1441         /* Pending BT Disabled event before bt-service's termination */
1442 }
1443
1444 static void __bt_adapter_state_set_status(bt_status_t status)
1445 {
1446         BT_INFO("adapter_status changed [%d] -> [%d]", adapter_state, status);
1447         adapter_state = status;
1448 }
1449
1450 static void __bt_adapter_update_discovery_status(bt_adapter_discovery_state_t status)
1451 {
1452         BT_INFO("adapter_discovery_status changed [%d] -> [%d]", adapter_discovery_state, status);
1453         adapter_discovery_state = status;
1454 }
1455
1456 static void __bt_adapter_state_change_callback(int bt_status)
1457 {
1458         BT_INFO("__bt_adapter_state_change_callback: status [%d]", bt_status);
1459
1460         switch (bt_status) {
1461         case BT_DEACTIVATED:
1462                 __bt_adapter_state_set_status(BT_TERMINATING);
1463
1464                 /* Adapter is disabled, unregister event handlers */
1465                 _bt_service_unregister_event_handler_callback(BT_ADAPTER_MODULE);
1466                 //_bt_deinit_device_event_handler();
1467
1468                 /* Add Adapter disabled post processing codes */
1469                 __bt_adapter_update_bt_disabled();
1470                 break;
1471         case BT_ACTIVATED:
1472                 /* Add Adapter enabled post processing codes */
1473                 if (timer_id > 0) {
1474                         BT_DBG("g_source is removed");
1475                         g_source_remove(timer_id);
1476                         timer_id = 0;
1477                 }
1478                 __bt_adapter_update_bt_enabled();
1479                 break;
1480         default:
1481                 BT_ERR("Incorrect Bluetooth adapter state changed status");
1482
1483         }
1484 }
1485
1486 int _bt_set_adapter_request_state(int enable)
1487 {
1488         return oal_set_adapter_request_state(enable);
1489 }
1490
1491 int _bt_set_le_request_state(int enable)
1492 {
1493         return oal_set_le_request_state(enable);
1494 }
1495
1496 static int __bt_adapter_state_handle_request(gboolean enable)
1497 {
1498         int result = BLUETOOTH_ERROR_NONE;
1499
1500         switch (adapter_state) {
1501         case BT_ACTIVATING:
1502         case BT_DEACTIVATING:
1503                 BT_INFO("Should not be callded : state [%d]", adapter_state);
1504                 return BLUETOOTH_ERROR_INTERNAL;
1505                 break;
1506         case BT_ACTIVATED: {
1507                 BT_INFO("Adapter is currently in activated state, state [%d]",
1508                                 adapter_state);
1509                 if (enable) {
1510                         return BLUETOOTH_ERROR_DEVICE_ALREADY_ENABLED;
1511                 } else {
1512                         if (adapter_discovery_state == ADAPTER_DISCOVERY_STARTED ||
1513                                         adapter_discovery_state == ADAPTER_DISCOVERY_STARTING) {
1514                                 /*TODO Stop Discovery*/
1515                                 __bt_adapter_update_discovery_status(FALSE);
1516                         }
1517                         result = adapter_disable();
1518                         if (result != OAL_STATUS_SUCCESS) {
1519                                 BT_ERR("adapter_enable failed: [%d]", result);
1520                                 result = BLUETOOTH_ERROR_INTERNAL;
1521                                 /*TODO: perform if anything more needs to be done to handle failure */
1522                         } else {
1523                                 /* TODO: To be handled */
1524                                 __bt_adapter_state_set_status(BT_DEACTIVATING);
1525                                 result = BLUETOOTH_ERROR_NONE;
1526                         }
1527                 }
1528                 break;
1529         }
1530         case BT_DEACTIVATED: {
1531                 BT_INFO("Adapter is currently in deactivated state, state [%d]",
1532                                 adapter_state);
1533                 if (!enable) {
1534                         return BLUETOOTH_ERROR_DEVICE_NOT_ENABLED;
1535                 } else {
1536                         result = adapter_enable();
1537                         if (result != OAL_STATUS_SUCCESS && result != OAL_STATUS_PENDING) {
1538                                 BT_ERR("adapter_enable failed: [%d]", result);
1539                                 adapter_disable();
1540                                 result = BLUETOOTH_ERROR_INTERNAL;
1541                                 /*TODO: perform if anything more needs to be done to handle failure */
1542                         } else {
1543                                 /* TODO: To be handled */
1544                                 __bt_adapter_state_set_status(BT_ACTIVATING);
1545                                 result = BLUETOOTH_ERROR_NONE;
1546                         }
1547                 }
1548                 break;
1549         }
1550         default:
1551                 BT_ERR("Unknown state: %d", adapter_state);
1552                 break;
1553         }
1554
1555         if (enable && result == BLUETOOTH_ERROR_NONE) {
1556                 /* Adapter enable request is successful, setup event handlers */
1557                 _bt_service_register_event_handler_callback(
1558                                 BT_ADAPTER_MODULE, __bt_adapter_event_handler);
1559                 _bt_device_state_handle_callback_set_request();
1560         }
1561         return result;
1562 }
1563
1564 static int __bt_adapter_state_discovery_request(gboolean enable,
1565                 unsigned short max_response, unsigned short duration,
1566                 unsigned int mask, gboolean is_custom,
1567                 bt_discovery_role_type_t role)
1568 {
1569         int result = BLUETOOTH_ERROR_NONE;
1570
1571         BT_DBG("+");
1572         switch (adapter_discovery_state) {
1573         case ADAPTER_DISCOVERY_STARTED: {
1574                 BT_INFO("Adapter is currently in discovery started state, state [%d]",
1575                                 adapter_discovery_state);
1576                 if (enable) {
1577                         return BLUETOOTH_ERROR_IN_PROGRESS;
1578                 } else {
1579                         result = adapter_stop_inquiry();
1580                         if (result != OAL_STATUS_SUCCESS) {
1581                                 BT_ERR("Discover stop failed: %d", result);
1582                                 result = BLUETOOTH_ERROR_INTERNAL;
1583                         } else {
1584                                 BT_ERR("Stop Discovery Triggered successfully");
1585                                 __bt_adapter_update_discovery_status(ADAPTER_DISCOVERY_STOPPING);
1586                                 result = BLUETOOTH_ERROR_NONE;
1587                         }
1588                 }
1589                 break;
1590         }
1591         case ADAPTER_DISCOVERY_STARTING: {
1592                 BT_INFO("Adapter is currently in discovery starting state, state [%d]",
1593                                 adapter_discovery_state);
1594
1595                 result = enable ?  BLUETOOTH_ERROR_IN_PROGRESS :
1596                                         BLUETOOTH_ERROR_DEVICE_BUSY;
1597
1598                 break;
1599         }
1600         case ADAPTER_DISCOVERY_STOPPED: {
1601                 BT_INFO("Adapter is currently in discovery stopped state, state [%d]",
1602                                 adapter_discovery_state);
1603                 if (!enable)
1604                         return BLUETOOTH_ERROR_NOT_IN_OPERATION;
1605                 else {
1606                         BT_DBG("max_resp: %u, duration: %u, cod: 0x%X", max_response, duration, mask);
1607
1608                         if (!is_custom)
1609                                 result = adapter_start_inquiry(duration);
1610                         else
1611                                 result = adapter_start_custom_inquiry(role);
1612
1613                         if (result != OAL_STATUS_SUCCESS) {
1614                                 BT_ERR("Start Discovery failed: %d", result);
1615                                 result = BLUETOOTH_ERROR_INTERNAL;
1616                         } else {
1617                                 BT_ERR("Start Discovery Triggered successfully");
1618                                 __bt_adapter_update_discovery_status(ADAPTER_DISCOVERY_STARTING);
1619                                 result = BLUETOOTH_ERROR_NONE;
1620                         }
1621                 }
1622                 break;
1623         }
1624         case ADAPTER_DISCOVERY_STOPPING: {
1625                 BT_INFO("Adapter is currently in discovery stopping state, state [%d]",
1626                                 adapter_discovery_state);
1627
1628                 result = enable ?  BLUETOOTH_ERROR_DEVICE_BUSY :
1629                                         BLUETOOTH_ERROR_NOT_IN_OPERATION;
1630
1631                 break;
1632         }
1633         default:
1634                 BT_ERR("Unknown state: %d", adapter_discovery_state);
1635                 break;
1636         }
1637
1638         BT_DBG("-");
1639         return result;
1640 }
1641
1642 static void __bt_adapter_discovery_state_change_callback(int bt_discovery_status)
1643 {
1644         BT_INFO("__bt_adapter_discovery_state_change_callback: status [%d]", bt_discovery_status);
1645         GVariant *param = NULL;
1646         int result = BLUETOOTH_ERROR_NONE;
1647
1648         switch (bt_discovery_status) {
1649         case ADAPTER_DISCOVERY_STOPPED:
1650         {
1651                 __bt_adapter_update_discovery_status(bt_discovery_status);
1652                 param = g_variant_new("(i)", result);
1653                 _bt_send_event(BT_ADAPTER_EVENT,
1654                                 BLUETOOTH_EVENT_DISCOVERY_FINISHED,
1655                                 param);
1656                 break;
1657         }
1658         case ADAPTER_DISCOVERY_STARTED:
1659         {
1660                 __bt_adapter_update_discovery_status(bt_discovery_status);
1661                 param = g_variant_new("(i)", result);
1662                 _bt_send_event(BT_ADAPTER_EVENT,
1663                                 BLUETOOTH_EVENT_DISCOVERY_STARTED,
1664                                 param);
1665                 break;
1666         }
1667         default:
1668                 BT_ERR("Incorrect Bluetooth adapter Discovery state changed status");
1669         }
1670 }
1671
1672 static void __bt_set_visible_mode(void)
1673 {
1674         int timeout = 0;
1675 #ifdef TIZEN_FEATURE_BT_DPM
1676         int discoverable_state = DPM_BT_ERROR;
1677 #endif
1678
1679         if (vconf_get_int(BT_FILE_VISIBLE_TIME, &timeout) != 0)
1680                 BT_ERR("Fail to get the timeout value");
1681
1682 #ifdef TIZEN_FEATURE_BT_DPM
1683         _bt_dpm_get_bluetooth_limited_discoverable_state(&discoverable_state);
1684         if (timeout == -1 || discoverable_state == DPM_RESTRICTED) {
1685                 if (_bt_set_discoverable_mode(
1686                                         BLUETOOTH_DISCOVERABLE_MODE_GENERAL_DISCOVERABLE,
1687                                         timeout) != BLUETOOTH_ERROR_NONE) {
1688                         if (vconf_set_int(BT_FILE_VISIBLE_TIME, 0) != 0)
1689                                 BT_ERR("Set vconf failed");
1690                 }
1691         } else {
1692                 if (_bt_set_discoverable_mode(
1693                                         BLUETOOTH_DISCOVERABLE_MODE_CONNECTABLE,
1694                                         timeout) != BLUETOOTH_ERROR_NONE) {
1695                         BT_ERR("Set connectable mode failed");
1696                 }
1697         }
1698 #else
1699         if (timeout == -1) {
1700                 if (_bt_set_discoverable_mode(
1701                                         BLUETOOTH_DISCOVERABLE_MODE_GENERAL_DISCOVERABLE,
1702                                         timeout) != BLUETOOTH_ERROR_NONE) {
1703                         if (vconf_set_int(BT_FILE_VISIBLE_TIME, 0) != 0)
1704                                 BT_ERR("Set vconf failed");
1705                 }
1706         } else {
1707                 if (_bt_set_discoverable_mode(
1708                                         BLUETOOTH_DISCOVERABLE_MODE_CONNECTABLE,
1709                                         timeout) != BLUETOOTH_ERROR_NONE) {
1710                         BT_ERR("Set connectable mode failed");
1711                 }
1712         }
1713 #endif
1714 }
1715
1716 static void __bt_set_local_name(void)
1717 {
1718         char *phone_name = NULL;
1719         char *ptr = NULL;
1720
1721         phone_name = vconf_get_str(VCONFKEY_SETAPPL_DEVICE_NAME_STR);
1722
1723         if (!phone_name)
1724                 return;
1725
1726         if (strlen(phone_name) != 0) {
1727                 if (!g_utf8_validate(phone_name, -1, (const char **)&ptr))
1728                         *ptr = '\0';
1729
1730                 _bt_set_local_name(phone_name);
1731         }
1732         free(phone_name);
1733 }
1734
1735 void _bt_adapter_set_status(bt_status_t status)
1736 {
1737         BT_INFO("adapter_status changed [%d] -> [%d]", adapter_state, status);
1738         adapter_state = status;
1739 }
1740
1741 bt_status_t _bt_adapter_get_status(void)
1742 {
1743         return adapter_state;
1744 }
1745
1746 void _bt_set_disabled(int result)
1747 {
1748         int power_off_status = 0;
1749         int ret;
1750         int ret_pm_ignore;
1751         int pm_ignore_mode = 0;
1752
1753         ret = vconf_get_int(VCONFKEY_SYSMAN_POWER_OFF_STATUS, &power_off_status);
1754         BT_DBG("ret : %d, power_off_status : %d", ret, power_off_status);
1755
1756         ret_pm_ignore = vconf_get_int(VCONFKEY_PM_KEY_IGNORE, &pm_ignore_mode);
1757
1758         /* Update the vconf BT status in normal Deactivation case only */
1759         if (ret == 0 && power_off_status == VCONFKEY_SYSMAN_POWER_OFF_NONE &&
1760                 ret_pm_ignore == 0 && pm_ignore_mode != VCONFKEY_PM_KEY_LOCK) {
1761
1762                 BT_DBG("Update vconf for BT normal Deactivation");
1763
1764                 if (result == BLUETOOTH_ERROR_TIMEOUT)
1765                         if (vconf_set_int(BT_OFF_DUE_TO_TIMEOUT, 1) != 0)
1766                                 BT_ERR("Set vconf failed");
1767
1768                 /* Update Bluetooth Status to notify other modules */
1769                 if (vconf_set_int(VCONFKEY_BT_STATUS, VCONFKEY_BT_STATUS_OFF) != 0)
1770                         BT_ERR("Set vconf failed");
1771
1772                 if (_bt_eventsystem_set_value(SYS_EVENT_BT_STATE, EVT_KEY_BT_STATE,
1773                                                         EVT_VAL_BT_OFF) != ES_R_OK)
1774                         BT_ERR("Fail to set value");
1775         }
1776
1777         if (vconf_set_int(VCONFKEY_BT_DEVICE, VCONFKEY_BT_DEVICE_NONE) != 0)
1778                 BT_ERR("Set vconf failed\n");
1779
1780         _bt_adapter_set_status(BT_DEACTIVATED);
1781         __bt_adapter_update_discovery_status(ADAPTER_DISCOVERY_STOPPED);
1782
1783         /* Send BT Disabled event to application */
1784         _bt_send_event(BT_ADAPTER_EVENT, BLUETOOTH_EVENT_DISABLED,
1785                         g_variant_new("(i)", result));
1786
1787         BT_INFO("Adapter disabled");
1788         BT_PERMANENT_LOG("BT Disabled");
1789 }
1790