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