update the header for Doxygen
[platform/framework/native/bluetooth.git] / src / FNetBt_BluetoothGapSystemAdapter.cpp
1 //
2 // Open Service Platform
3 // Copyright (c) 2012-2013 Samsung Electronics Co., Ltd.
4 //
5 // Licensed under the Apache License, Version 2.0 (the License);
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 //     http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 //
17 // @file        FNetBt_BluetoothGapSystemAdapter.cpp
18 // @brief       This is the implementation file for the _BluetoothGapSystemAdapter class.
19 //
20
21 #include <unique_ptr.h>
22 #include <pthread.h>
23 #include <FBaseByteBuffer.h>
24 #include <FBaseUtilStringUtil.h>
25 #include <FBaseUuId.h>
26 #include <FIoFile.h>
27 #include <FNetBtBluetoothTypes.h>
28 #include <FNetBtBluetoothDevice.h>
29 #include <FBaseSysLog.h>
30 #include <FApp_AppInfo.h>
31 #include <FBase_StringConverter.h>
32 #include "FNetBt_BluetoothGapSystemAdapter.h"
33 #include "FNetBt_BluetoothDeviceImpl.h"
34 #include "FNetBt_IBluetoothDeviceEventListener.h"
35 #include "FNetBt_IBluetoothManagerEventListener.h"
36 #include "FNetBt_BluetoothAdapterUtility.h"
37
38 using namespace std;
39 using namespace Tizen::App;
40 using namespace Tizen::Base;
41 using namespace Tizen::Base::Collection;
42 using namespace Tizen::Base::Utility;
43 using namespace Tizen::Io;
44
45 static const Tizen::Base::String _BT_ADDRESS_FILE_PATH(L"/opt/etc/.bd_addr");
46
47 namespace Tizen { namespace Net { namespace Bluetooth
48 {
49
50 struct _DeviceInfoDeleter
51 {
52         template<typename bt_device_info_s>
53         void operator()(bt_device_info_s* pDeviceInfo)
54         {
55                 bt_adapter_free_device_info(pDeviceInfo);
56         }
57 };
58
59 _BluetoothGapSystemAdapter* _BluetoothGapSystemAdapter::__pInstance = null;
60
61 _BluetoothGapSystemAdapter::_BluetoothGapSystemAdapter(void)
62         : __mgrEvtListenerList()
63         , __devEvtListenerList()
64 {
65 }
66
67 _BluetoothGapSystemAdapter::~_BluetoothGapSystemAdapter(void)
68 {
69         // unset all the system callback methods
70         bt_adapter_unset_state_changed_cb();
71         bt_adapter_unset_device_discovery_state_changed_cb();
72         bt_adapter_unset_visibility_mode_changed_cb();
73         bt_device_unset_bond_created_cb();
74         bt_device_unset_bond_destroyed_cb();
75         bt_device_unset_service_searched_cb();
76         bt_device_unset_connection_state_changed_cb();
77 }
78
79 void
80 _BluetoothGapSystemAdapter::InitSingleton(void)
81 {
82         bool isConstructed = false;
83         static _BluetoothGapSystemAdapter inst;
84
85         isConstructed = inst.Construct();
86         SysTryReturnVoidResult(NID_NET_BT, isConstructed == true, E_SYSTEM,
87                         "[E_SYSTEM] Construction of _BluetoothGapSystemAdpater fails.");
88
89         __pInstance = &inst;
90 }
91
92 _BluetoothGapSystemAdapter*
93 _BluetoothGapSystemAdapter::GetInstance(void)
94 {
95         static pthread_once_t onceBlock = PTHREAD_ONCE_INIT;
96
97         if (__pInstance == null)
98         {
99                 ClearLastResult();
100                 pthread_once(&onceBlock, InitSingleton);
101                 result r = GetLastResult();
102                 if (IsFailed(r))
103                 {
104                         onceBlock = PTHREAD_ONCE_INIT;
105                 }
106         }
107
108         return __pInstance;
109 }
110
111 bool
112 _BluetoothGapSystemAdapter::Construct(void)
113 {
114         if (bt_initialize() == BT_ERROR_NONE)
115         {
116                 //register all the call backs.
117                 if ((bt_adapter_set_state_changed_cb(&OnAdapterStateChanged, NULL) == BT_ERROR_NONE) &&
118                         (bt_adapter_set_visibility_mode_changed_cb(&OnVisibilityModeChanged, NULL) == BT_ERROR_NONE) &&
119                         (bt_device_set_bond_created_cb(&OnPairingCompleted, NULL) == BT_ERROR_NONE) &&
120                         (bt_device_set_bond_destroyed_cb(&OnPairedDeviceRemoved, NULL) == BT_ERROR_NONE) &&
121                         (bt_adapter_set_device_discovery_state_changed_cb(&OnDeviceDiscoveryStateChanged, NULL) == BT_ERROR_NONE) &&
122                         (bt_device_set_service_searched_cb(&OnServiceDiscoveryCompleted, NULL) == BT_ERROR_NONE) &&
123                         (bt_device_set_connection_state_changed_cb(&OnConnectionStateChanged, NULL) == BT_ERROR_NONE))
124                 {
125                         return true;
126                 }
127         }
128         SysLog(NID_NET_BT, "Initialising the Bluetooth subsystem has failed");
129
130         return false;
131 }
132
133 result
134 _BluetoothGapSystemAdapter::RegisterManagerEventListener(const _IBluetoothManagerEventListener& listener, bool isHighPriority)
135 {
136         if (isHighPriority == true)
137         {
138                 // insert the specified event listener at the begin of the list
139                 return __mgrEvtListenerList.InsertAt(const_cast<_IBluetoothManagerEventListener*>(&listener), 0);
140         }
141         else
142         {
143                 // insert the specified event listener at the end of the list
144                 return __mgrEvtListenerList.Add(const_cast<_IBluetoothManagerEventListener*>(&listener));
145         }
146 }
147
148 result
149 _BluetoothGapSystemAdapter::UnregisterManagerEventListener(const _IBluetoothManagerEventListener& listener)
150 {
151
152         return __mgrEvtListenerList.Remove(const_cast<_IBluetoothManagerEventListener*>(&listener));
153 }
154
155 result
156 _BluetoothGapSystemAdapter::RegisterDeviceEventListener(const _IBluetoothDeviceEventListener& listener)
157 {
158         return __devEvtListenerList.Add(const_cast<_IBluetoothDeviceEventListener*>(&listener));
159 }
160
161 result
162 _BluetoothGapSystemAdapter::UnregisterDeviceEventListener(const _IBluetoothDeviceEventListener& listener)
163 {
164         return __devEvtListenerList.Remove(const_cast<_IBluetoothDeviceEventListener*>(&listener));
165 }
166
167 result
168 _BluetoothGapSystemAdapter::Activate(void)
169 {
170         if (bt_adapter_enable() == BT_ERROR_NONE)
171         {
172                 return E_SUCCESS;
173         }
174         return E_SYSTEM;
175 }
176
177 result
178 _BluetoothGapSystemAdapter::Deactivate(void)
179 {
180         if (bt_adapter_disable() == BT_ERROR_NONE)
181         {
182                 return E_SUCCESS;
183         }
184         return E_SYSTEM;
185 }
186
187 bool
188 _BluetoothGapSystemAdapter::IsActivated(void) const
189 {
190         bt_adapter_state_e btAdapterState = BT_ADAPTER_DISABLED;
191
192         if (bt_adapter_get_state(&btAdapterState) == BT_ERROR_NONE)
193         {
194                 if (btAdapterState == BT_ADAPTER_ENABLED)
195                 {
196                         return true;
197                 }
198         }
199         return false;
200 }
201
202 bool
203 _BluetoothGapSystemAdapter::IsAvailable(BluetoothConnectionType type) const
204 {
205         bool isAvailable = false;
206         bool isUsed = true;
207         char* pUuidStr = null;
208
209         if (!IsActivated())
210         {
211                 SysLog(NID_NET_BT, "All connection type is not available because Bluetooth is not activated.");
212                 return false;
213         }
214
215         switch (type)
216         {
217         case BT_CONNECTION_GENERIC:
218                 isAvailable = true;
219                 break;
220
221         case BT_CONNECTION_SPP_ACCEPTOR:
222                 pUuidStr = _StringConverter::CopyToCharArrayN(UuId(BT_SVC_UUID_SPP).ToString());
223                 // TODO: meaning of bt_adapter_is_service_used() method is quite wrong
224                 if ((pUuidStr != null) && (bt_adapter_is_service_used(pUuidStr, &isUsed) == BT_ERROR_NONE))
225                 {
226                         SysLog(NID_NET_BT, "SPP(default UUID) server is %s.", isUsed ? "used" : "available");
227                 }
228
229                 isAvailable = isUsed ? false : true;
230
231                 delete[] pUuidStr;
232                 break;
233
234         case BT_CONNECTION_OPP_SERVER:
235                 pUuidStr = _StringConverter::CopyToCharArrayN(UuId(BT_SVC_UUID_OPP).ToString());
236                 // TODO: meaning of bt_adapter_is_service_used() method is quite wrong
237                 if ((pUuidStr != null) && (bt_adapter_is_service_used(pUuidStr, &isUsed) == BT_ERROR_NONE))
238                 {
239                         SysLog(NID_NET_BT, "OPP server is %s.", isUsed ? "used" : "available");
240                 }
241
242                 isAvailable = isUsed ? false : true;
243
244                 delete[] pUuidStr;
245                 break;
246
247         // This is always true, because multiple SPP initiators can be run simultaneously since 3.0
248         case BT_CONNECTION_SPP_INITIATOR:
249                 isAvailable = true;
250                 break;
251
252         // The only one OPP client can be run per process.
253         case BT_CONNECTION_OPP_CLIENT:
254                 isAvailable = true;
255                 break;
256
257         default:
258                 break;
259         }
260
261         return isAvailable;
262 }
263
264 Tizen::Base::String
265 _BluetoothGapSystemAdapter::GetLocalDeviceAddress(void) const
266 {
267         result r = E_SUCCESS;
268         int ret = 0;
269         ByteBuffer addressBuffer;
270         String localAddrString(_BT_ADDRESS_LENGTH*3);
271         char* pLocalAddr = null;
272
273         ret = bt_adapter_get_address(&pLocalAddr);
274
275         if (ret == BT_ERROR_NONE)
276         {
277                 localAddrString = String(pLocalAddr);
278         }
279         else
280         {
281                 File file;
282                 int bufLimit;
283                 byte curByte;
284
285                 // Opens the local cache file and gets the local address from it.
286                 r = file.Construct(_BT_ADDRESS_FILE_PATH, L"r");
287                 SysTryReturn(NID_NET_BT, r == E_SUCCESS, localAddrString, E_SYSTEM, "Construction of the address info file has failed.");
288
289                 (void) file.Seek(FILESEEKPOSITION_BEGIN, 0);
290
291                 addressBuffer.Construct(_BT_ADDRESS_LENGTH*3);
292                 r = file.Read(addressBuffer);
293                 SysTryReturn(NID_NET_BT, r == E_SUCCESS, localAddrString, E_SYSTEM, "Read the address from the info file has failed.");
294
295                 bufLimit = addressBuffer.GetLimit();
296
297                 for (int i = 0, addressIndex = 0 ; i < bufLimit ; i++)
298                 {
299                         addressBuffer.GetByte(i, curByte);
300                         if ((curByte >= '0' && curByte <= '9') ||
301                                 (curByte >= 'a' && curByte <= 'f') ||
302                                 (curByte >= 'A' && curByte <= 'F'))
303                         {
304                                 localAddrString.Append((char)curByte);
305                                 addressIndex++;
306                                 if ((addressIndex % 3 == 2) && (addressIndex < (_BT_ADDRESS_LENGTH * 3 - 1 )))
307                                 {
308                                         // append ":" int the localAddrString to form a correct BT address format[aa:bb:cc:dd:ee:ff]
309                                         localAddrString.Append(':'); 
310                                         addressIndex++;
311                                 }
312                         }
313                 }
314
315                 localAddrString.ToUpperCase();
316         }
317
318         return localAddrString;
319 }
320
321 BluetoothDiscoverableMode
322 _BluetoothGapSystemAdapter::GetDiscoverableMode(void) const
323 {
324         bt_adapter_visibility_mode_e visMode = BT_ADAPTER_VISIBILITY_MODE_NON_DISCOVERABLE;
325         BluetoothDiscoverableMode discMode = BT_DISC_MODE_NOT_DISCOVERABLE;
326
327         // CONNECTABLE is actually not exactly the same as NONE mode but dealt with as the same values herein.
328         // TODO: resolve the problem about failure when the BT adapter is disabled
329         if (bt_adapter_get_visibility(&visMode, null)== BT_ERROR_NONE)
330         {
331                 if (visMode == BT_ADAPTER_VISIBILITY_MODE_GENERAL_DISCOVERABLE)
332                 {
333                         discMode = BT_DISC_MODE_DISCOVERABLE;
334                 }
335                 else if (visMode == BT_ADAPTER_VISIBILITY_MODE_LIMITED_DISCOVERABLE)
336                 {
337                         if (_AppInfo::GetApiVersion() == _API_VERSION_2_0 && _AppInfo::IsOspCompat())
338                         {
339                                 discMode = BT_DISC_MODE_DISCOVERABLE;
340                         }
341                         else
342                         {
343                                 discMode = BT_DISC_MODE_TIME_LIMITED_DISCOVERABLE;
344                         }
345                 }
346                 // BT_DISC_MODE_NOT_DISCOVERABLE, otherwise.
347         }
348
349         return discMode;
350 }
351
352 int
353 _BluetoothGapSystemAdapter::GetRemainingTimeAsDiscoverable(void) const
354 {
355         bt_adapter_visibility_mode_e visMode = BT_ADAPTER_VISIBILITY_MODE_NON_DISCOVERABLE;
356         int duration = 0;
357         int ret = 0;
358
359         ret = bt_adapter_get_visibility(&visMode, &duration);
360
361         if ((ret != BT_ERROR_NONE) || (visMode != BT_ADAPTER_VISIBILITY_MODE_LIMITED_DISCOVERABLE))
362         {
363                 SysLog(NID_NET_BT, "Not the time-limited discoverable mode! Remaining time is 0.");
364         }
365
366         return duration;
367 }
368
369 Tizen::Base::Collection::IList*
370 _BluetoothGapSystemAdapter::GetAllPairedDeviceListN(void) const
371 {
372         ArrayList* pPairedDeviceList = null;
373         SysLog(NID_NET_BT, "Getting all paired device list...");
374
375         pPairedDeviceList = new (std::nothrow) ArrayList();
376
377         bt_adapter_state_e btAdapterState;
378         if (bt_adapter_get_state(&btAdapterState) == BT_ERROR_NONE)
379         {
380                 if (btAdapterState == BT_ADAPTER_ENABLED)
381                 {
382                         if (bt_adapter_foreach_bonded_device(&OnPairedDeviceFound, pPairedDeviceList) != BT_ERROR_NONE)
383                         {
384                                 pPairedDeviceList->RemoveAll(true);
385                                 delete pPairedDeviceList;
386                                 return null;
387                         }
388                 }
389                 else //BT_ADAPTER_DISABLED
390                 {
391                         SysLog(NID_NET_BT, "Cannot get the paired device list because the Bluetooth apdater is disabled!!");
392                 }
393         }
394
395         return pPairedDeviceList;
396 }
397
398 result
399 _BluetoothGapSystemAdapter::Pair(const Tizen::Base::ByteBuffer& deviceAddress)
400 {
401         result r = E_SYSTEM;
402         char* pPairDevAddr = null;
403
404         SysTryReturnResult(NID_NET_BT, deviceAddress.GetRemaining() == _BT_ADDRESS_LENGTH, E_SYSTEM,
405                                                 "The address of the remote device is incorrect.");
406
407         pPairDevAddr = _StringConverter::CopyToCharArrayN(_BluetoothDeviceImpl::GetAddressString(deviceAddress));
408         SysTryReturnResult(NID_NET_BT, pPairDevAddr != null, E_SYSTEM, "Address converting fails.");
409
410         if (bt_device_create_bond(pPairDevAddr) == BT_ERROR_NONE)
411         {
412                 r = E_SUCCESS;
413         }
414
415         SysLog(NID_NET_BT, "Pairing with [%ls] %s.", _BluetoothDeviceImpl::GetAddressString(deviceAddress).GetPointer(),
416                         r == E_SUCCESS ? "is successful" : "fails");
417
418         delete[] pPairDevAddr;
419         return r;
420 }
421
422 result
423 _BluetoothGapSystemAdapter::CancelPair(void)
424 {
425         result r = E_SYSTEM;
426
427         if (bt_device_cancel_bonding() == BT_ERROR_NONE)
428         {
429                 r = E_SUCCESS;
430         }
431
432         SysLog(NID_NET_BT, "Cancel of bonding %s.", r == E_SUCCESS ? "is successful" : "fails");
433
434         return r;
435 }
436
437 result
438 _BluetoothGapSystemAdapter::Unpair(const Tizen::Base::ByteBuffer& deviceAddress)
439 {
440         result r = E_SYSTEM;
441         char* pUnpairDevAddr = null;
442
443         SysTryReturnResult(NID_NET_BT, deviceAddress.GetRemaining() == _BT_ADDRESS_LENGTH, E_SYSTEM,
444                                                 "The address of the remote device is incorrect.");
445
446         pUnpairDevAddr = _StringConverter::CopyToCharArrayN(_BluetoothDeviceImpl::GetAddressString(deviceAddress));
447         SysTryReturnResult(NID_NET_BT, pUnpairDevAddr != null, E_SYSTEM, "Address converting fails.");
448
449         if (bt_device_destroy_bond(pUnpairDevAddr) == BT_ERROR_NONE)
450         {
451                 r = E_SUCCESS;
452         }
453
454         SysLog(NID_NET_BT, "Unpairing with [%ls] %s.", _BluetoothDeviceImpl::GetAddressString(deviceAddress).GetPointer(),
455                         r == E_SUCCESS ? "is successful" : "fails");
456
457         delete[] pUnpairDevAddr;
458         return r;
459 }
460
461 bool
462 _BluetoothGapSystemAdapter::IsPaired(const Tizen::Base::ByteBuffer& deviceAddress) const
463 {
464         bool isPaired = false;
465         
466         if (deviceAddress.GetRemaining() != _BT_ADDRESS_LENGTH)
467         {
468                 SysLog(NID_NET_BT, "The address of the remote device is incorrect.");
469                 return false;
470         }
471
472         char* pRemoteDevAddress = _StringConverter::CopyToCharArrayN(_BluetoothDeviceImpl::GetAddressString(deviceAddress));
473         bt_device_info_s* pDeviceInfo = null;
474         
475         if (bt_adapter_get_bonded_device_info(pRemoteDevAddress, &pDeviceInfo) == BT_ERROR_NONE)
476         {
477                 if (pDeviceInfo)
478                 {
479                         if (pDeviceInfo->is_bonded)
480                         {
481                                 isPaired = true;
482                         }
483                         bt_adapter_free_device_info(pDeviceInfo);
484                 }
485         }
486
487         delete[] pRemoteDevAddress;
488         return isPaired;
489 }
490
491 result
492 _BluetoothGapSystemAdapter::StartDiscovery(void)
493 {
494         result r = E_SYSTEM;
495
496         if (bt_adapter_start_device_discovery() == BT_ERROR_NONE)
497         {
498                 r = E_SUCCESS;
499         }
500
501         SysLog(NID_NET_BT, "Start of discovery %s.", r == E_SUCCESS ? "is successful" : "fails");
502
503         return r;
504 }
505
506 result
507 _BluetoothGapSystemAdapter::CancelDiscovery(void)
508 {
509         result r = E_SYSTEM;
510
511         if (bt_adapter_stop_device_discovery() == BT_ERROR_NONE)
512         {
513                 r = E_SUCCESS;
514         }
515
516         SysLog(NID_NET_BT, "Cancel of discovery %s.", r == E_SUCCESS ? "is successful" : "fails");
517
518         return r;
519 }
520
521 bool
522 _BluetoothGapSystemAdapter::IsDiscoveryInProgress(void) const
523 {
524         bool is_discovering = false;
525
526         (void) bt_adapter_is_discovering(&is_discovering);
527
528         return is_discovering;
529 }
530
531 result
532 _BluetoothGapSystemAdapter::RetrieveServiceList(const Tizen::Base::ByteBuffer& deviceAddress)
533 {
534         result r = E_SYSTEM;
535         char* pDevAddr = null;
536
537         SysTryReturnResult(NID_NET_BT, deviceAddress.GetRemaining() == _BT_ADDRESS_LENGTH, E_SYSTEM,
538                                                 "The address of the remote device is incorrect.");
539
540         pDevAddr = _StringConverter::CopyToCharArrayN(_BluetoothDeviceImpl::GetAddressString(deviceAddress));
541         SysTryReturnResult(NID_NET_BT, pDevAddr != null, E_SYSTEM, "Address converting fails.");
542
543         if (bt_device_start_service_search(pDevAddr) == BT_ERROR_NONE)
544         {
545                 r = E_SUCCESS;
546         }
547
548         SysLog(NID_NET_BT, "Retrieving the service list from [%ls] %s.",
549                         _BluetoothDeviceImpl::GetAddressString(deviceAddress).GetPointer(), r == E_SUCCESS ? "is successful" : "fails");
550
551         delete[] pDevAddr;
552         return r;
553 }
554
555 result
556 _BluetoothGapSystemAdapter::GetPairedDevice(const ByteBuffer& address, BluetoothDevice& pairedDevice)
557 {
558         int err = BT_ERROR_NONE;
559         unique_ptr<char[]> pDevAddr;
560         bt_device_info_s* pDeviceInfo = null;
561         unique_ptr<bt_device_info_s, _DeviceInfoDeleter> pDeviceInfoPtr;
562         _BluetoothDeviceImpl* pDevImpl = null;
563         String convertedName;
564
565         pDevAddr.reset(_StringConverter::CopyToCharArrayN(_BluetoothDeviceImpl::GetAddressString(address)));
566         SysTryReturnResult(NID_NET_BT, pDevAddr != null, E_SYSTEM, "Address converting fails.");
567
568         err = bt_adapter_get_bonded_device_info(pDevAddr.get(), &pDeviceInfo);
569         SysTryReturnResult(NID_NET_BT, err == BT_ERROR_NONE, E_SYSTEM, "Getting paired device infomation has failed.");
570         pDeviceInfoPtr.reset(pDeviceInfo);
571
572         pDevImpl = _BluetoothDeviceImpl::GetInstance(pairedDevice);
573
574         // converts the UTF8 multibyte string to Unicode String
575         (void) StringUtil::Utf8ToString(pDeviceInfoPtr->remote_name, convertedName);
576
577         pDevImpl->SetAddress(address);
578         pDevImpl->SetName(convertedName);
579         pDevImpl->SetPaired(pDeviceInfoPtr->is_bonded);
580         pDevImpl->SetMajorDeviceClassType(_BluetoothAdapterUtility::ConvertToMajorDeviceClassType(
581                         pDeviceInfoPtr->bt_class.major_device_class));
582         pDevImpl->SetMinorDeviceClassType(_BluetoothAdapterUtility::ConvertToMinorDeviceClassType(
583                         pDeviceInfoPtr->bt_class.major_device_class, pDeviceInfoPtr->bt_class.minor_device_class));
584         pDevImpl->SetServiceClassList(_BluetoothAdapterUtility::ConvertToServiceClassList(
585                         pDeviceInfoPtr->bt_class.major_service_class_mask));
586         pDevImpl->SetServiceList(_BluetoothAdapterUtility::ConvertToServiceList(
587                         pDeviceInfoPtr->service_uuid, pDeviceInfoPtr->service_count));
588         pDevImpl->SetServiceUuidList(_BluetoothAdapterUtility::ConvertServiceUuidListN(
589                         pDeviceInfoPtr->service_uuid, pDeviceInfoPtr->service_count), false);
590
591         return E_SUCCESS;
592 }
593
594 void
595 _BluetoothGapSystemAdapter::OnAdapterStateChanged(int status, bt_adapter_state_e adapterState, void* pUserdata)
596 {
597         result r = E_SUCCESS;
598         _IBluetoothManagerEventListener* pMgrEvtListener = null;
599         IEnumeratorT<_IBluetoothManagerEventListener*>* pEnum = null;
600         _BluetoothGapSystemAdapter* pGapAdapter = _BluetoothGapSystemAdapter::GetInstance();
601
602         if (status != BT_ERROR_NONE)
603         {
604                 r = E_SYSTEM;
605         }
606
607         pEnum = pGapAdapter->__mgrEvtListenerList.GetEnumeratorN();
608         while (pEnum->MoveNext() == E_SUCCESS)
609         {
610                 pEnum->GetCurrent(pMgrEvtListener);
611                 if(adapterState == BT_ADAPTER_ENABLED)
612                 {
613                         pMgrEvtListener->OnBluetoothActivated(r);
614                 }
615                 else
616                 {
617                         pMgrEvtListener->OnBluetoothDeactivated(r);
618                 }
619         }
620
621         delete pEnum;
622 }
623
624 void
625 _BluetoothGapSystemAdapter::OnVisibilityModeChanged(int result, bt_adapter_visibility_mode_e mode, void* pUserdata)
626 {
627         _IBluetoothManagerEventListener* pMgrEvtListener = null;
628         IEnumeratorT<_IBluetoothManagerEventListener*>* pEnum = null;
629         _BluetoothGapSystemAdapter* pGapAdapter = _BluetoothGapSystemAdapter::GetInstance();
630         BluetoothDiscoverableMode changedMode = BT_DISC_MODE_NOT_DISCOVERABLE;
631
632         if (result == BT_ERROR_NONE)
633         {
634                 switch (mode)
635                 {
636                 case BT_ADAPTER_VISIBILITY_MODE_NON_DISCOVERABLE:
637                         changedMode = BT_DISC_MODE_NOT_DISCOVERABLE;
638                         break;
639
640                 case BT_ADAPTER_VISIBILITY_MODE_GENERAL_DISCOVERABLE:
641                         changedMode = BT_DISC_MODE_DISCOVERABLE;
642                         break;
643
644                 case BT_ADAPTER_VISIBILITY_MODE_LIMITED_DISCOVERABLE:
645                         changedMode = BT_DISC_MODE_TIME_LIMITED_DISCOVERABLE;
646                         break;
647
648                 default:
649                         return;
650                 }
651
652                 pEnum = pGapAdapter->__mgrEvtListenerList.GetEnumeratorN();
653                 while (pEnum->MoveNext() == E_SUCCESS)
654                 {
655                         pEnum->GetCurrent(pMgrEvtListener);
656                         pMgrEvtListener->OnBluetoothDiscoverableModeChanged(changedMode);
657                 }
658
659                 delete pEnum;
660         }
661 }
662
663 void
664 _BluetoothGapSystemAdapter::OnDeviceDiscoveryStateChanged(int status, bt_adapter_device_discovery_state_e discoveryState,
665                                                                 bt_adapter_device_discovery_info_s* pDiscoveryInfo, void* pUserData)
666 {
667         result r = E_SUCCESS;
668         _IBluetoothDeviceEventListener* pDevEventListener = null;
669         IEnumeratorT<_IBluetoothDeviceEventListener*>* pEnum = null;
670         _BluetoothGapSystemAdapter* pGapAdapter = _BluetoothGapSystemAdapter::GetInstance();
671
672         pEnum = pGapAdapter->__devEvtListenerList.GetEnumeratorN();
673
674         switch(discoveryState)
675         {
676         case BT_ADAPTER_DEVICE_DISCOVERY_STARTED:
677         {
678                 if (status != BT_ERROR_NONE)
679                 {
680                         r = E_SYSTEM;
681                 }
682
683                 while (pEnum->MoveNext() == E_SUCCESS)
684                 {
685                         pEnum->GetCurrent(pDevEventListener);
686                         pDevEventListener->OnBluetoothDiscoveryStarted(r);
687                 }
688         }
689                 break;
690
691         case BT_ADAPTER_DEVICE_DISCOVERY_FOUND:
692         {
693                 BluetoothDevice foundDevice;
694                 ByteBuffer deviceAddress;
695                 deviceAddress.Construct(_BT_ADDRESS_LENGTH);
696                 String convertedName;
697
698                 String tempDevAddr(pDiscoveryInfo->remote_address);
699                 _BluetoothDeviceImpl::GetAddressByteBuffer(tempDevAddr, L":", deviceAddress);
700
701                 // converts the UTF8 multibyte string to Unicode String
702                 (void) StringUtil::Utf8ToString(pDiscoveryInfo->remote_name, convertedName);
703
704                 _BluetoothDeviceImpl* pDevImpl = _BluetoothDeviceImpl::GetInstance(foundDevice);
705
706                 pDevImpl->SetAddress(deviceAddress);
707                 pDevImpl->SetName(convertedName);
708                 pDevImpl->SetPaired(pDiscoveryInfo->is_bonded);
709                 pDevImpl->SetRssi(pDiscoveryInfo->rssi);
710                 pDevImpl->SetMajorDeviceClassType(_BluetoothAdapterUtility::ConvertToMajorDeviceClassType(
711                                 pDiscoveryInfo->bt_class.major_device_class));
712                 pDevImpl->SetMinorDeviceClassType(_BluetoothAdapterUtility::ConvertToMinorDeviceClassType(
713                                 pDiscoveryInfo->bt_class.major_device_class, pDiscoveryInfo->bt_class.minor_device_class));
714                 pDevImpl->SetServiceClassList(_BluetoothAdapterUtility::ConvertToServiceClassList(
715                                 pDiscoveryInfo->bt_class.major_service_class_mask));
716                 pDevImpl->SetServiceList(_BluetoothAdapterUtility::ConvertToServiceList(
717                                 pDiscoveryInfo->service_uuid, pDiscoveryInfo->service_count));
718                 pDevImpl->SetServiceUuidList(_BluetoothAdapterUtility::ConvertServiceUuidListN(
719                                 pDiscoveryInfo->service_uuid, pDiscoveryInfo->service_count), false);
720
721                 _BluetoothAdapterUtility::PrintDeviceInfo(foundDevice);
722
723                 while (pEnum->MoveNext() == E_SUCCESS)
724                 {
725                         pEnum->GetCurrent(pDevEventListener);
726                         pDevEventListener->OnBluetoothRemoteDeviceFound(foundDevice);
727                 }
728         }
729                 break;
730
731         case BT_ADAPTER_DEVICE_DISCOVERY_FINISHED:
732         {
733                 bool isCompleted = false;
734
735                 if (status == BT_ERROR_NONE)
736                 {
737                         isCompleted = true; // isCompleted is false in other cases including BT_ERROR_CANCEL
738                 }
739
740                 while (pEnum->MoveNext() == E_SUCCESS)
741                 {
742                         pEnum->GetCurrent(pDevEventListener);
743                         pDevEventListener->OnBluetoothDiscoveryDone(isCompleted);
744                 }
745         }
746                 break;
747
748         default:
749                 break;
750         }
751
752         delete pEnum;
753 }
754
755 void
756 _BluetoothGapSystemAdapter::OnServiceDiscoveryCompleted(int status, bt_device_sdp_info_s* pSdpInfo, void* pUserData)
757 {
758         result r = E_SUCCESS;
759         _IBluetoothDeviceEventListener* pDevEventListener = null;
760         IEnumeratorT<_IBluetoothDeviceEventListener*>* pEnum = null;
761         ByteBuffer deviceAddress;
762         deviceAddress.Construct(_BT_ADDRESS_LENGTH);
763         unsigned long serviceList = 0;
764         Tizen::Base::Collection::IList* pServiceUuidList= null;
765         _BluetoothGapSystemAdapter* pGapAdapter = _BluetoothGapSystemAdapter::GetInstance();
766
767         String tempDevAddr(pSdpInfo->remote_address);
768         r = _BluetoothDeviceImpl::GetAddressByteBuffer(tempDevAddr, L":", deviceAddress);
769
770         if (status != BT_ERROR_NONE)
771         {
772                 r = E_SYSTEM;
773         }
774         else
775         {
776                 pServiceUuidList = _BluetoothAdapterUtility::ConvertServiceUuidListN(
777                                 pSdpInfo->service_uuid, pSdpInfo->service_count);
778                 if (pServiceUuidList == null)
779                 {
780                         r = E_SYSTEM;
781                 }
782                 else
783                 {
784                         serviceList = _BluetoothAdapterUtility::ConvertToServiceList(pSdpInfo->service_uuid, pSdpInfo->service_count);
785                         SysLog(NID_NET_BT, "Searched Service List =================");
786                         _BluetoothAdapterUtility::PrintServiceList(serviceList);
787
788                         SysLog(NID_NET_BT, "Searched Service UUID List ============");
789                         _BluetoothAdapterUtility::PrintServiceUuidList(pServiceUuidList);
790                 }
791         }
792
793         pEnum = pGapAdapter->__devEvtListenerList.GetEnumeratorN();
794
795         while (pEnum->MoveNext() == E_SUCCESS)
796         {
797                 pEnum->GetCurrent(pDevEventListener);
798                 pDevEventListener->OnBluetoothServiceListReceived(deviceAddress, serviceList, pServiceUuidList, r);
799         }
800
801         delete pEnum;
802         // The ownership of UuId instances in the list is transferred to _BluetoothDeviceEventArg.
803         // Therefore, only the list except its elements is deleted here.
804         delete pServiceUuidList;
805 }
806
807 void
808 _BluetoothGapSystemAdapter::OnPairingCompleted(int status, bt_device_info_s* pDeviceInfo, void* pUserdata)
809 {
810         result r = E_SUCCESS;
811         _IBluetoothDeviceEventListener* pDevEventListener = null;
812         IEnumeratorT<_IBluetoothDeviceEventListener*>* pEnum = null;
813         BluetoothDevice pairingDevice;
814         _BluetoothGapSystemAdapter* pGapAdapter = _BluetoothGapSystemAdapter::GetInstance();
815         ByteBuffer deviceAddress;
816         deviceAddress.Construct(_BT_ADDRESS_LENGTH);
817         String convertedName;
818
819         SysTryReturnVoidResult(NID_NET_BT, pDeviceInfo != null, E_SYSTEM,
820                         "[E_SYSTEM] the input param, DeviceInfo on callback is null.");
821
822         String tempDevAddr(pDeviceInfo->remote_address);
823         (void) _BluetoothDeviceImpl::GetAddressByteBuffer(tempDevAddr, L":", deviceAddress);
824
825         // converts the UTF8 multibyte string to Unicode String
826         (void) StringUtil::Utf8ToString(pDeviceInfo->remote_name, convertedName);
827
828         _BluetoothDeviceImpl* pDevImpl = _BluetoothDeviceImpl::GetInstance(pairingDevice);
829
830         pDevImpl->SetAddress(deviceAddress);
831         pDevImpl->SetName(convertedName);
832         pDevImpl->SetPaired(true);
833         pDevImpl->SetRssi(0);
834         pDevImpl->SetMajorDeviceClassType(_BluetoothAdapterUtility::ConvertToMajorDeviceClassType(
835                         pDeviceInfo->bt_class.major_device_class));
836         pDevImpl->SetMinorDeviceClassType(_BluetoothAdapterUtility::ConvertToMinorDeviceClassType(
837                         pDeviceInfo->bt_class.major_device_class, pDeviceInfo->bt_class.minor_device_class));
838         pDevImpl->SetServiceClassList(_BluetoothAdapterUtility::ConvertToServiceClassList(
839                         pDeviceInfo->bt_class.major_service_class_mask));
840         pDevImpl->SetServiceList(_BluetoothAdapterUtility::ConvertToServiceList(
841                         pDeviceInfo->service_uuid, pDeviceInfo->service_count));
842         pDevImpl->SetServiceUuidList(_BluetoothAdapterUtility::ConvertServiceUuidListN(
843                         pDeviceInfo->service_uuid, pDeviceInfo->service_count), false);
844
845         switch (status)
846         {
847         case BT_ERROR_NONE:
848                 r = E_SUCCESS;
849                 break;
850         case BT_ERROR_CANCELLED:
851                 r = E_OPERATION_CANCELED;
852                 break;
853         case BT_ERROR_TIMED_OUT:
854                 r = E_TIMEOUT;
855                 break;
856         default:
857                 r = E_OPERATION_FAILED;
858                 break;
859         }
860
861         pEnum = pGapAdapter->__devEvtListenerList.GetEnumeratorN();
862         while (pEnum->MoveNext() == E_SUCCESS)
863         {
864                 pEnum->GetCurrent(pDevEventListener);
865                 pDevEventListener->OnBluetoothPaired(&pairingDevice, r);
866         }
867         delete pEnum;
868 }
869
870 void
871 _BluetoothGapSystemAdapter::OnPairedDeviceRemoved(int status, char* pRemoteAddress, void* pUserData)
872 {
873         _IBluetoothDeviceEventListener* pDevEventListener = null;
874         IEnumeratorT<_IBluetoothDeviceEventListener*>* pEnum = null;
875         _BluetoothGapSystemAdapter* pGapAdapter = _BluetoothGapSystemAdapter::GetInstance();
876         ByteBuffer deviceAddress;
877         deviceAddress.Construct(_BT_ADDRESS_LENGTH);
878
879         if (status == BT_ERROR_NONE)
880         {
881                 String tempDevAddr(pRemoteAddress);
882                 _BluetoothDeviceImpl::GetAddressByteBuffer(tempDevAddr, L":", deviceAddress);
883
884                 pEnum = pGapAdapter->__devEvtListenerList.GetEnumeratorN();
885
886                 while (pEnum->MoveNext() == E_SUCCESS)
887                 {
888                         pEnum->GetCurrent(pDevEventListener);
889                         pDevEventListener->OnBluetoothUnpaired(deviceAddress);
890                 }
891
892                 delete pEnum;
893         }
894         else
895         {
896                 SysLog(NID_NET_BT, "Error in removing the Paired Device is %d", status);
897         }
898 }
899
900 bool
901 _BluetoothGapSystemAdapter::OnPairedDeviceFound(bt_device_info_s* pDeviceInfo, void* pUserdata)
902 {
903         ArrayList* pPairedDeviceList = static_cast<ArrayList*>(pUserdata);
904
905         ByteBuffer btAddress;
906         btAddress.Construct(_BT_ADDRESS_LENGTH);
907         BluetoothDevice* pPairedDevice = null;
908         String convertedName;
909
910         pPairedDevice = new (std::nothrow) BluetoothDevice();
911         SysTryReturn(NID_NET_BT, pPairedDevice != null, false, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] The memory is insufficient.");
912
913         String tempDevAddr(pDeviceInfo->remote_address);
914         _BluetoothDeviceImpl::GetAddressByteBuffer(tempDevAddr, L":", btAddress);
915
916         // converts the UTF8 multibyte string to Unicode String
917         (void) StringUtil::Utf8ToString(pDeviceInfo->remote_name, convertedName);
918
919         SysLog(NID_NET_BT, "Paired Device - (name: %ls)", convertedName.GetPointer());
920
921         _BluetoothDeviceImpl* pDevImpl = _BluetoothDeviceImpl::GetInstance(*pPairedDevice);
922
923         pDevImpl->SetAddress(btAddress);
924         pDevImpl->SetName(convertedName);
925         pDevImpl->SetPaired(true);
926         pDevImpl->SetRssi(0);
927         pDevImpl->SetMajorDeviceClassType(_BluetoothAdapterUtility::ConvertToMajorDeviceClassType(
928                         pDeviceInfo->bt_class.major_device_class));
929         pDevImpl->SetMinorDeviceClassType(_BluetoothAdapterUtility::ConvertToMinorDeviceClassType(
930                         pDeviceInfo->bt_class.major_device_class, pDeviceInfo->bt_class.minor_device_class));
931         pDevImpl->SetServiceClassList(_BluetoothAdapterUtility::ConvertToServiceClassList(
932                         pDeviceInfo->bt_class.major_service_class_mask));
933         pDevImpl->SetServiceList(_BluetoothAdapterUtility::ConvertToServiceList(
934                         pDeviceInfo->service_uuid, pDeviceInfo->service_count));
935         pDevImpl->SetServiceUuidList(_BluetoothAdapterUtility::ConvertServiceUuidListN(
936                         pDeviceInfo->service_uuid, pDeviceInfo->service_count), false);
937
938         pPairedDeviceList->Add(*pPairedDevice);
939
940         return true;
941 }
942
943 void
944 _BluetoothGapSystemAdapter::OnConnectionStateChanged(bool isConnected, const char* pRemoteAddress, void* pUserdata)
945 {
946         _IBluetoothDeviceEventListener* pDevEventListener = null;
947         IEnumeratorT<_IBluetoothDeviceEventListener*>* pEnum = null;
948         _BluetoothGapSystemAdapter* pGapAdapter = _BluetoothGapSystemAdapter::GetInstance();
949         ByteBuffer deviceAddress;
950         deviceAddress.Construct(_BT_ADDRESS_LENGTH);
951
952         String tempDevAddr(pRemoteAddress);
953         _BluetoothDeviceImpl::GetAddressByteBuffer(tempDevAddr, L":", deviceAddress);
954
955         pEnum = pGapAdapter->__devEvtListenerList.GetEnumeratorN();
956
957         while (pEnum->MoveNext() == E_SUCCESS)
958         {
959                 pEnum->GetCurrent(pDevEventListener);
960                 if (isConnected)
961                 {
962                         pDevEventListener->OnBluetoothDeviceConnected(deviceAddress);
963                 }
964                 else
965                 {
966                         pDevEventListener->OnBluetoothDeviceDisconnected(deviceAddress);
967                 }
968         }
969
970         delete pEnum;
971 }
972
973 } } } // Tizen::Net::Bluetooth