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