API change , Retransmission Callback on expiry , remove glib source for dynamic linking
[platform/upstream/iotivity.git] / resource / csdk / connectivity / src / bt_edr_adapter / tizen / cabtmanager.c
1 /******************************************************************
2  *
3  * Copyright 2014 Samsung Electronics All Rights Reserved.
4  *
5  *
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  ******************************************************************/
20
21 /**
22  * @file  cabtmanager.c
23  * @brief  This file provides the APIs to control Bluetooth transport
24  */
25
26 #include "cabtmanager.h"
27 #include "cabtclient.h"
28 #include "cabtserver.h"
29 #include "cabtendpoint.h"
30 #include "cabtdevicelist.h"
31 #include "cabtutils.h"
32 #include "caadapterutils.h"
33 #include "caqueueingthread.h"
34 #include "camsgparser.h"
35
36 /**
37  * @struct CABTNetworkEvent
38  * @brief Structure to maintain the adapter information and its status.
39  */
40 typedef struct
41 {
42     CALocalConnectivity_t *info;
43     CANetworkStatus_t status;
44 } CABTNetworkEvent;
45
46 /**
47  * @struct CABTData
48  * @brief Structure to maintain the information of data in message queue.
49  */
50 typedef struct
51 {
52     CARemoteEndpoint_t *remoteEndpoint;
53     void *data;
54     uint32_t dataLen;
55 } CABTData;
56 /**
57  * @var gNetworkPacketReceivedCallback
58  * @brief Maintains the callback to be notified on receival of network packets from other
59  *          Bluetooth devices.
60  */
61 static CANetworkPacketReceivedCallback gNetworkPacketReceivedCallback = NULL;
62
63 /**
64  * @var gNetworkChangeCallback
65  * @brief Maintains the callback to be notified on local bluetooth adapter status change.
66  */
67 static CANetworkChangeCallback gNetworkChangeCallback = NULL;
68
69 /**
70  * @var gBTDeviceListMutex
71  * @brief Mutex to synchronize the access to Bluetooth device information list.
72  */
73 static u_mutex gBTDeviceListMutex = NULL;
74
75 /**
76  * @var gBTDeviceList
77  * @brief Peer Bluetooth device information list.
78  */
79 static BTDeviceList *gBTDeviceList = NULL;
80
81 /**
82  * @var gLocalConnectivity
83  * @brief Information of local Bluetooth adapter.
84  */
85 static CALocalConnectivity_t *gLocalConnectivity = NULL;
86
87 /**
88  * @var gBTThreadPool
89  * @brief Reference to threadpool.
90  */
91 static u_thread_pool_t gBTThreadPool = NULL;
92
93 /**
94  * @var isHeaderAvailable
95  * @brief to differentiate btw header and data packet.
96  */
97 static CABool_t isHeaderAvailable = false;
98
99 /**
100  * @var gSendQueueHandle
101  * @brief Queue handle for Send Data
102  */
103 static CAQueueingThread_t *gSendQueueHandle = NULL;
104
105 /**
106  * @var gRecvQueueHandle
107  * @brief Queue handle for Receive Data
108  */
109 static CAQueueingThread_t *gRecvQueueHandle = NULL;
110
111 /**
112  * @var gAdapterState
113  * @brief Storing Adapter state information
114  */
115 static CABool_t gAdapterState = TRUE;
116
117 /**
118  * @var gServerId
119  * @brief Storing RfcommserverUUID
120  */
121 static int32_t gServerId = -1;
122
123 /**
124  * @var gServerState
125  * @brief Storing Rfcommserver state information
126  */
127 static CABool_t gServerState = FALSE;
128
129 /**
130  * @fn CABTAdapterStateChangeCallback
131  * @brief This callback is registered to receive bluetooth adapter state changes.
132  */
133 static void CABTAdapterStateChangeCallback(int result, bt_adapter_state_e adapterState,
134         void *userData);
135
136 /**
137  * @fn CABTSocketConnectionStateCallback
138  * @brief This callback is registered to receive bluetooth RFCOMM connection state changes.
139  */
140 static void CABTSocketConnectionStateCallback(int result,
141         bt_socket_connection_state_e state,
142         bt_socket_connection_s *connection, void *userData);
143
144 /**
145  * @fn CABTDataRecvCallback
146  * @brief This callback is registered to recieve data on any open RFCOMM connection.
147  */
148 static void CABTDataRecvCallback(bt_socket_received_data_s *data, void *userData);
149
150 /**
151  * @fn CABTDeviceDiscoveryCallback
152  * @brief This callback is registered to recieve all bluetooth nearby devices when device
153  *           scan is initiated.
154  */
155 static void CABTDeviceDiscoveryCallback(int result,
156                                         bt_adapter_device_discovery_state_e state,
157                                         bt_adapter_device_discovery_info_s *discoveryInfo,
158                                         void *userData);
159
160 /**
161  * @fn CABTServiceSearchedCallback
162  * @brief This callback is registered to recieve all the services remote bluetooth device supports
163  *           when service search initiated.
164  */
165 static void CABTServiceSearchedCallback(int result, bt_device_sdp_info_s *sdpInfo,
166                                         void *userData);
167
168
169 /**
170  * @fn CABTManagerInitializeQueues
171  * @brief This function creates and initialize message queues.
172  */
173 static CAResult_t CABTManagerInitializeQueues(void);
174
175 /**
176  * @fn CABTManagerInitializeSendHandler
177  * @brief This function creates and initialize send message queue.
178  */
179 CAResult_t CABTManagerInitializeSendHandler(void);
180
181 /**
182  * @fn CABTManagerInitializeQueues
183  * @brief This function creates and initialize receive message queue.
184  */
185 CAResult_t CABTManagerInitializeReceiveHandler(void);
186 /**
187  * @fn CABTManagerTerminateQueues
188  * @brief This function terminates the send message queue.
189  */
190 static void CABTManagerTerminateQueues(void);
191
192 /**
193  * @fn CABTManagerInitializeMutex
194  * @brief This function creates mutex.
195  */
196 static void CABTManagerInitializeMutex(void);
197
198 /**
199  * @fn CABTManagerTerminateMutex
200  * @brief This function frees mutex.
201  */
202 static void CABTManagerTerminateMutex(void);
203
204 /**
205  * @fn CABTManagerDataSendHandler
206  * @brief This function handles data from send message queue.
207  */
208 static void CABTManagerDataSendHandler(void *context);
209
210 /**
211  * @fn CABTManagerDataReceiverHandler
212  * @brief This function handles data from recv message queue.
213  */
214 static void CABTManagerDataReceiverHandler(void *context);
215
216 /**
217  * @fn CABTManagerSendUnicastData
218  * @brief This function sends data to specified remote bluetooth device.
219  */
220 static CAResult_t CABTManagerSendUnicastData(const char *remoteAddress, const char *serviceUUID,
221         void *data, uint32_t dataLength, uint32_t *sentLength);
222
223 /**
224  * @fn CABTManagerSendMulticastData
225  * @brief This function sends data to all bluetooth devices running OIC service.
226  */
227 static CAResult_t CABTManagerSendMulticastData(const char *serviceUUID, void *data,
228         uint32_t dataLength, uint32_t *sentLength);
229
230 /**
231  * @fn CABTGetAdapterEnableState
232  * @brief This function gets bluetooth adatper enable state.
233  */
234 static CAResult_t CABTGetAdapterEnableState(bool *state);
235
236 /**
237  * @fn CABTStartDeviceDiscovery
238  * @brief This function starts device discovery.
239  */
240 static CAResult_t CABTStartDeviceDiscovery(void);
241
242 /**
243  * @fn CABTStopDeviceDiscovery
244  * @brief This function stops device discovery.
245  */
246 static CAResult_t CABTStopDeviceDiscovery(void);
247
248 /**
249  * @fn CABTStartServiceSearch
250  * @brief This function searches for OIC service for remote Bluetooth device.
251  */
252 static CAResult_t CABTStartServiceSearch(const char *remoteAddress);
253
254 /**
255  * @fn CABTStopServiceSearch
256  * @brief This function stops any ongoing service sevice search.
257  */
258 static CAResult_t CABTStopServiceSearch(void);
259
260 /**
261  * @fn CABTNotifyNetworkStauts
262  * @brief This function creates notification task for network adapter status and add it to thread pool.
263  */
264 static CAResult_t CABTNotifyNetworkStauts(CANetworkStatus_t status);
265
266 /**
267  * @fn CABTOnNetworkStautsChanged
268  * @brief This is task callback function for notifying network adapter status to upper layer.
269  */
270 static void CABTOnNetworkStautsChanged(void *context);
271
272 /**
273  * @fn CABTCreateNetworkEvent
274  * @brief Creates instance of CABTNetworkEvent.
275  */
276 static CABTNetworkEvent *CABTCreateNetworkEvent(CALocalConnectivity_t *connectivity,
277         CANetworkStatus_t status);
278
279 /**
280  * @fn CABTFreeNetworkEvent
281  * @brief Free the memory associated with @event.
282  */
283 static void CABTFreeNetworkEvent(CABTNetworkEvent *event);
284
285 /**
286  * @fn CABTManagerDisconnectAll
287  * @brief Closes all the client connection to peer bluetooth devices.
288  */
289 static void CABTManagerDisconnectAll(void);
290
291 /**
292  * @fn CACreateBTData
293  * @brief creating CABTData
294  */
295 static CABTData *CACreateBTData(const CARemoteEndpoint_t *remoteEndpoint, void *data,
296                                 uint32_t dataLength);
297
298 /**
299  * @fn CABTManagerDisconnectAll
300  * @brief freeing CABTData
301  */
302 static void CAFreeBTData(CABTData *btData);
303
304
305 CAResult_t CABTManagerInitialize(u_thread_pool_t threadPool)
306 {
307     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
308
309     int32_t err = BT_ERROR_NONE;
310
311     //Initialize Bluetooth service
312     if (BT_ERROR_NONE != (err = bt_initialize()))
313     {
314         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Bluetooth initialization failed!, error num [%x]",
315                   err);
316         return CA_STATUS_FAILED;
317     }
318
319     //Create and initialize the mutex
320     CABTManagerInitializeMutex();
321
322     if (NULL == gBTThreadPool)
323     {
324         gBTThreadPool = threadPool;
325     }
326
327     //Initialize Send/Receive data message queues
328     if (CA_STATUS_OK != CABTManagerInitializeQueues())
329     {
330         //Deinitialize the Bluetooth stack
331         bt_deinitialize();
332         return CA_STATUS_FAILED;
333     }
334
335     bt_adapter_set_state_changed_cb(CABTAdapterStateChangeCallback, NULL);
336
337     //Notity to upper layer
338     // CABTNotifyNetworkStauts(CA_INTERFACE_UP);
339
340     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
341     return CA_STATUS_OK;
342 }
343
344 void CABTManagerTerminate(void)
345 {
346     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
347
348     gNetworkPacketReceivedCallback = NULL;
349     gNetworkChangeCallback = NULL;
350
351     //Stop the adpater
352     CABTManagerStop();
353
354     //Unset bluetooth adapter callbacks
355     bt_adapter_unset_state_changed_cb();
356
357     //Terminate Bluetooth service
358     bt_deinitialize();
359
360     //Terminate thread pool
361     gBTThreadPool = NULL;
362
363     //Free LocalConnectivity information
364     CAAdapterFreeLocalEndpoint(gLocalConnectivity);
365     gLocalConnectivity = NULL;
366
367     //Free BTDevices list
368     if (gBTDeviceListMutex)
369     {
370         u_mutex_lock(gBTDeviceListMutex);
371         CADestroyBTDeviceList(&gBTDeviceList);
372         u_mutex_unlock(gBTDeviceListMutex);
373     }
374
375     //Free the mutex
376     CABTManagerTerminateMutex();
377
378     //Terminate Send/Receive data messages queues
379     CABTManagerTerminateQueues();
380
381     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
382 }
383
384 CAResult_t CABTManagerStart(void)
385 {
386     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
387
388     //Get Bluetooth adapter state
389     bool adapterState = false;
390     if (CA_STATUS_OK != CABTGetAdapterEnableState(&adapterState))
391     {
392         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to get adatper enable state");
393         return CA_STATUS_FAILED;
394     }
395
396     if (false == adapterState)
397     {
398         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Bluetooth adapter is disabled!");
399         gAdapterState = FALSE;
400         return CA_STATUS_OK;
401     }
402
403     //Register for discovery and rfcomm socket connection callbacks
404     bt_adapter_set_device_discovery_state_changed_cb(CABTDeviceDiscoveryCallback, NULL);
405     bt_device_set_service_searched_cb(CABTServiceSearchedCallback, NULL);
406     bt_socket_set_connection_state_changed_cb(CABTSocketConnectionStateCallback, NULL);
407     bt_socket_set_data_received_cb(CABTDataRecvCallback, NULL);
408
409     //Start device discovery
410     CABTStartDeviceDiscovery();
411
412     // Start send queue thread
413     if (CA_STATUS_OK != CAQueueingThreadStart(gSendQueueHandle))
414     {
415         OIC_LOG(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to Start Send Data Thread");
416         CABTManagerStop();
417         return CA_STATUS_FAILED;
418     }
419     // Start receive queue thread
420     if (CA_STATUS_OK != CAQueueingThreadStart(gRecvQueueHandle))
421     {
422         OIC_LOG(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to Start Receive Data Thread");
423         CABTManagerStop();
424         return CA_STATUS_FAILED;
425     }
426
427     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
428     return CA_STATUS_OK;
429 }
430
431 void CABTManagerStop(void)
432 {
433     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
434
435     //Stop service search
436     CABTStopServiceSearch();
437
438     //Stop the device discovery process
439     CABTStopDeviceDiscovery();
440
441     //Stop send queue thread
442     CAQueueingThreadStop(gSendQueueHandle);
443
444     //Stop receive queue thread
445     CAQueueingThreadStop(gRecvQueueHandle);
446
447     //reset bluetooth adapter callbacks
448     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "Resetting the callbacks");
449     bt_adapter_unset_device_discovery_state_changed_cb();
450     bt_device_unset_service_searched_cb();
451     bt_socket_unset_connection_state_changed_cb();
452     bt_socket_unset_data_received_cb();
453
454     //Disconnect all the client connections
455     CABTManagerDisconnectAll();
456
457     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
458 }
459
460 void CABTManagerSetPacketReceivedCallback(
461     CANetworkPacketReceivedCallback packetReceivedCallback)
462 {
463     gNetworkPacketReceivedCallback = packetReceivedCallback;
464 }
465
466 void CABTManagerSetNetworkChangeCallback(
467     CANetworkChangeCallback networkChangeCallback)
468 {
469     gNetworkChangeCallback = networkChangeCallback;
470 }
471
472 CAResult_t CABTManagerPushDataToReceiverQueue(const char *remoteAddress,
473         const char *serviceUUID, void *data, uint32_t dataLength, uint32_t *sentLength)
474 {
475     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
476
477     if (FALSE == gAdapterState)
478     {
479         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Bluetooth adapter is disabled!");
480         *sentLength = 0;
481         return CA_STATUS_OK;
482     }
483     //Input validation
484     VERIFY_NON_NULL(serviceUUID, BLUETOOTH_ADAPTER_TAG, "service UUID is null");
485     VERIFY_NON_NULL(data, BLUETOOTH_ADAPTER_TAG, "Data is null");
486     VERIFY_NON_NULL(sentLength, BLUETOOTH_ADAPTER_TAG, "Sent data length holder is null");
487
488     //Add message to data queue
489     CARemoteEndpoint_t *remoteEndpoint = CAAdapterCreateRemoteEndpoint(CA_EDR, remoteAddress,
490                                          serviceUUID);
491     if (NULL == remoteEndpoint)
492     {
493         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to create remote endpoint !");
494         return CA_STATUS_FAILED;
495     }
496
497     CABTData *btData =  CACreateBTData(remoteEndpoint, data, dataLength);
498     //Add message to data queue
499
500     CAQueueingThreadAddData(gRecvQueueHandle, btData, sizeof(btData));
501
502     *sentLength = dataLength;
503
504     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
505     return CA_STATUS_OK;
506 }
507 CAResult_t CABTManagerSendData(const char *remoteAddress, const char *serviceUUID,
508                                void *data, uint32_t dataLength, uint32_t *sentLength)
509 {
510     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
511
512     if (FALSE == gAdapterState)
513     {
514         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Bluetooth adapter is disabled!");
515         *sentLength = 0;
516         return CA_STATUS_OK;
517     }
518     //Input validation
519     VERIFY_NON_NULL(serviceUUID, BLUETOOTH_ADAPTER_TAG, "service UUID is null");
520     VERIFY_NON_NULL(data, BLUETOOTH_ADAPTER_TAG, "Data is null");
521     VERIFY_NON_NULL(sentLength, BLUETOOTH_ADAPTER_TAG, "Sent data length holder is null");
522
523     CARemoteEndpoint_t *remoteEndpoint = CAAdapterCreateRemoteEndpoint(CA_EDR, remoteAddress,
524                                          serviceUUID);
525     if (NULL == remoteEndpoint)
526     {
527         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to create remote endpoint !");
528         return CA_STATUS_FAILED;
529     }
530
531     CABTData *btData =  CACreateBTData(remoteEndpoint, data, dataLength);
532     //Add message to data queue
533
534     CAQueueingThreadAddData(gSendQueueHandle, btData, sizeof(btData));
535
536     *sentLength = dataLength;
537
538     //Signal message handler for processing data for sending
539     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
540     return CA_STATUS_OK;
541 }
542
543 CAResult_t CABTManagerStartServer(void)
544 {
545     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
546
547     if (FALSE == gAdapterState)
548     {
549         OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "Bluetooth adapter is disabled!");
550         //Setting gServerState for starting Rfcommserver when adapter starts
551         gServerState = TRUE;
552         return CA_STATUS_OK;
553     }
554
555     if (-1 < gServerId)
556     {
557         OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "Server is already in running state.");
558         return CA_STATUS_OK;
559     }
560     return CABTServerStart(OIC_BT_SERVICE_ID, &gServerId);
561 }
562
563 CAResult_t CABTManagerStopServer(void)
564 {
565     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
566
567     if (-1 == gServerId)
568     {
569         OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "No Server is in running state.");
570         return CA_STATUS_OK;
571     }
572
573     if (CA_STATUS_OK != CABTServerStop(gServerId))
574     {
575         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to close server socket!");
576         return CA_STATUS_FAILED;
577     }
578
579     gServerId = -1;
580     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
581     return CA_STATUS_OK;
582 }
583
584 CAResult_t CABTManagerGetInterface(CALocalConnectivity_t **info)
585 {
586     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
587
588     int32_t err = BT_ERROR_NONE;
589     char *localAddress = NULL;
590
591     //Input validation
592     VERIFY_NON_NULL(info, BLUETOOTH_ADAPTER_TAG, "LocalConnectivity info is null");
593
594     //Get the bluetooth adapter local address
595     if (BT_ERROR_NONE != (err = bt_adapter_get_address(&localAddress)))
596     {
597         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG,
598                   "Getting local adapter address failed!, error num [%x]",
599                   err);
600         return CA_STATUS_FAILED;
601     }
602
603     //Create network info
604     *info = CAAdapterCreateLocalEndpoint(CA_EDR, localAddress);
605     if (NULL == *info)
606     {
607         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to create LocalConnectivity instance!");
608
609         OICFree(localAddress);
610         return CA_MEMORY_ALLOC_FAILED;
611     }
612
613     OICFree(localAddress);
614
615     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
616     return CA_STATUS_OK;
617 }
618
619 CAResult_t CABTManagerReadData(void)
620 {
621     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
622     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
623     return CA_NOT_SUPPORTED;
624 }
625
626 CAResult_t CABTManagerInitializeQueues(void)
627 {
628     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
629
630     if (CA_STATUS_OK == CABTManagerInitializeSendHandler()
631         && CA_STATUS_OK == CABTManagerInitializeReceiveHandler())
632     {
633         OIC_LOG(DEBUG, BLUETOOTH_ADAPTER_TAG, "Queue is initialized!");
634         return CA_STATUS_OK;
635     }
636
637     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
638     return CA_STATUS_FAILED;
639 }
640
641 CAResult_t CABTManagerInitializeSendHandler(void)
642 {
643     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
644     // Check if the message queue is already initialized
645     if (gSendQueueHandle)
646     {
647         OIC_LOG(DEBUG, BLUETOOTH_ADAPTER_TAG, "Already queue is initialized!");
648         return CA_STATUS_OK;
649     }
650
651     gSendQueueHandle = OICMalloc(sizeof(CAQueueingThread_t));
652     if (!gSendQueueHandle)
653     {
654         OIC_LOG(ERROR, BLUETOOTH_ADAPTER_TAG, "Memory allocation failed!");
655         return CA_MEMORY_ALLOC_FAILED;
656     }
657
658     if (CA_STATUS_OK != CAQueueingThreadInitialize(gSendQueueHandle, gBTThreadPool,
659             CABTManagerDataSendHandler))
660     {
661         OIC_LOG(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to Initialize send queue thread");
662         return CA_STATUS_FAILED;
663     }
664     return CA_STATUS_OK;
665 }
666
667 CAResult_t CABTManagerInitializeReceiveHandler(void)
668 {
669     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
670     // Check if the message queue is already initialized
671     if (gRecvQueueHandle)
672     {
673         OIC_LOG(DEBUG, BLUETOOTH_ADAPTER_TAG, "Already queue is initialized!");
674         return CA_STATUS_OK;
675     }
676
677     gRecvQueueHandle = OICMalloc(sizeof(CAQueueingThread_t));
678     if (!gRecvQueueHandle)
679     {
680         OIC_LOG(ERROR, BLUETOOTH_ADAPTER_TAG, "Memory allocation failed!");
681         return CA_MEMORY_ALLOC_FAILED;
682     }
683
684     if (CA_STATUS_OK != CAQueueingThreadInitialize(gRecvQueueHandle, gBTThreadPool,
685             CABTManagerDataReceiverHandler))
686     {
687         OIC_LOG(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to Initialize send queue thread");
688         return CA_STATUS_FAILED;
689     }
690
691     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
692     return CA_STATUS_OK;
693 }
694
695 void CABTManagerTerminateQueues(void)
696 {
697     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
698
699     if (gSendQueueHandle)
700     {
701         CAQueueingThreadDestroy(gSendQueueHandle);
702         gSendQueueHandle = NULL;
703     }
704     if (gRecvQueueHandle)
705     {
706         CAQueueingThreadDestroy(gRecvQueueHandle);
707         gRecvQueueHandle = NULL;
708     }
709
710     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
711 }
712
713 void CABTManagerInitializeMutex(void)
714 {
715     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
716
717     u_mutex_init();
718
719     if (!gBTDeviceListMutex)
720     {
721         gBTDeviceListMutex = u_mutex_new();
722     }
723
724     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
725 }
726
727 void CABTManagerTerminateMutex(void)
728 {
729     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
730
731     if (gBTDeviceListMutex)
732     {
733         u_mutex_free(gBTDeviceListMutex);
734         gBTDeviceListMutex = NULL;
735     }
736
737     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
738 }
739
740
741 void CABTManagerDataReceiverHandler(void *context)
742 {
743     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
744
745
746     CABTData *message = (CABTData *) context;
747     if (message == NULL)
748     {
749         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to get message!");
750         return;
751     }
752     const char *remoteAddress = NULL;
753     const char *serviceUUID = NULL;
754     static uint32_t recvDataLen = 0;
755     static uint32_t totalDataLen = 0;
756     static char *defragData = NULL;
757     static CARemoteEndpoint_t *remoteEndpoint = NULL;
758
759     if (!isHeaderAvailable)
760     {
761         char *header = (char *) OICMalloc(sizeof(char) * CA_HEADER_LENGTH);
762
763         if (NULL == header)
764         {
765             OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Out of memory (header)!");
766             return;
767         }
768         memcpy(header, (char *)message->data, CA_HEADER_LENGTH);
769         totalDataLen = CAParseHeader(header);
770         OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "Total data to be accumulated [%d] bytes",
771                   totalDataLen);
772         defragData = NULL;
773         if (totalDataLen == 0)
774         {
775             OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, " totalDataLen is zero");
776             OICFree(header);
777             return;
778         }
779         defragData = (char *) OICMalloc(sizeof(char) * totalDataLen);
780         OICFree(header);
781
782         remoteAddress = message->remoteEndpoint->addressInfo.BT.btMacAddress;
783         serviceUUID = message->remoteEndpoint->resourceUri;
784
785         remoteEndpoint = CAAdapterCreateRemoteEndpoint(CA_EDR, remoteAddress,
786                          serviceUUID);
787
788         memcpy(defragData + recvDataLen, message->data + CA_HEADER_LENGTH,
789                message->dataLen - CA_HEADER_LENGTH);
790         recvDataLen += message->dataLen - CA_HEADER_LENGTH;
791         isHeaderAvailable = true;
792     }
793     else
794     {
795         memcpy(defragData + recvDataLen, message->data, message->dataLen);
796         recvDataLen += message->dataLen ;
797     }
798     CAFreeBTData(message);
799     if (totalDataLen == recvDataLen)
800     {
801         OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "Sending data up !");
802         gNetworkPacketReceivedCallback(remoteEndpoint, defragData, recvDataLen);
803         recvDataLen = 0;
804         totalDataLen = 0;
805         remoteEndpoint = NULL;
806         isHeaderAvailable = false;
807     }
808
809     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
810 }
811
812
813 void CABTManagerDataSendHandler(void *context)
814 {
815     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
816
817     CABTData *message = (CABTData *) context;
818     if (message == NULL)
819     {
820         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to get message!");
821         return;
822     }
823     const char *remoteAddress = NULL;
824     const char *serviceUUID = NULL;
825     uint32_t sentLength = 0;
826     int32_t headerAdded = 0;
827
828     remoteAddress = message->remoteEndpoint->addressInfo.BT.btMacAddress;
829     serviceUUID = message->remoteEndpoint->resourceUri;
830
831     char *dataSegment = NULL;
832     uint32_t offset = 0, ret = 1;
833     int32_t datalen = message->dataLen;
834     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "checking for fragmentation and the dataLen is %d",
835               datalen);
836     while ( 1)
837     {
838         OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "fragmenting the data DataLen [%d] Offset [%d]",
839                   datalen, offset);
840         ret = CAFragmentData((char *)message->data, &dataSegment, datalen, offset);
841         if (0 == ret)
842         {
843             break;
844         }
845         if (NULL == dataSegment)
846         {
847             OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to allocated memory fo dataSegment.");
848             break;
849         }
850         if (strlen(remoteAddress)) //Unicast data
851         {
852             if (CA_STATUS_OK != CABTManagerSendUnicastData(remoteAddress, serviceUUID,
853                     dataSegment, ret, &sentLength))
854             {
855                 OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to send unicast data !");
856             }
857         }
858         else
859         {
860             OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "sending multicast data");
861             if (CA_STATUS_OK != CABTManagerSendMulticastData(serviceUUID, dataSegment,
862                     ret, &sentLength))
863             {
864                 OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to send multicast data !");
865             }
866         }
867         OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "freeing dataSegment");
868
869         OICFree(dataSegment);
870         dataSegment = NULL;
871         offset += ret;
872         if (headerAdded == 0)
873         {
874             datalen -= offset - CA_HEADER_LENGTH;
875             offset = offset - CA_HEADER_LENGTH;
876             headerAdded = 1;
877         }
878         else
879         {
880             datalen -= ret;
881         }
882
883         if (datalen < 0)
884         {
885             datalen += ret ;
886         }
887         if (datalen == message->dataLen)
888         {
889             OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "All data has been fragmented and sent");
890             break;
891         }
892     }
893     //Free message
894     CAFreeBTData(message);
895
896     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
897 }
898
899 CAResult_t CABTManagerSendUnicastData(const char *remoteAddress, const char *serviceUUID,
900                                       void *data, uint32_t dataLength, uint32_t *sentLength)
901 {
902     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
903
904     BTDevice *device = NULL;
905
906     //Input validation
907     VERIFY_NON_NULL(remoteAddress, BLUETOOTH_ADAPTER_TAG, "Remote address is null");
908     VERIFY_NON_NULL(serviceUUID, BLUETOOTH_ADAPTER_TAG, "service UUID is null");
909     VERIFY_NON_NULL(data, BLUETOOTH_ADAPTER_TAG, "Data is null");
910     VERIFY_NON_NULL(sentLength, BLUETOOTH_ADAPTER_TAG, "Sent data length holder is null");
911
912     if (0 >= dataLength)
913     {
914         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Invalid input: Negative data length!");
915         return CA_STATUS_INVALID_PARAM;
916     }
917
918     //Check the connection existence with remote device
919     u_mutex_lock(gBTDeviceListMutex);
920     if (CA_STATUS_OK != CAGetBTDevice(gBTDeviceList, remoteAddress, &device))
921     {
922         //Create new device and add to list
923         if (CA_STATUS_OK != CACreateAndAddToDeviceList(&gBTDeviceList, remoteAddress,
924                 OIC_BT_SERVICE_ID, &device))
925         {
926             OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed create device and add to list!");
927
928             u_mutex_unlock(gBTDeviceListMutex);
929             return CA_STATUS_FAILED;
930         }
931
932         //Start the OIC service search newly created device
933         if (CA_STATUS_OK != CABTStartServiceSearch(remoteAddress))
934         {
935             OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to initiate service search!");
936
937             //Remove device from list
938             CARemoveBTDeviceFromList(&gBTDeviceList, remoteAddress);
939
940             u_mutex_unlock(gBTDeviceListMutex);
941             return CA_STATUS_FAILED;
942         }
943     }
944     u_mutex_unlock(gBTDeviceListMutex);
945
946     if (-1 == device->socketFD)
947     {
948         //Adding to pending list
949         if (CA_STATUS_OK != CAAddBTDataToList(&device->pendingDataList, data,
950                                               dataLength))
951         {
952             OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to add data to pending list!");
953
954             //Remove device from list
955             CARemoveBTDeviceFromList(&gBTDeviceList, remoteAddress);
956             return CA_STATUS_FAILED;
957         }
958
959         //Make a rfcomm connection with remote BT Device
960         if (1 == device->serviceSearched &&
961             CA_STATUS_OK != CABTClientConnect(remoteAddress, serviceUUID))
962         {
963             OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to make RFCOMM connection!");
964
965             //Remove device from list
966             CARemoveBTDeviceFromList(&gBTDeviceList, remoteAddress);
967             return CA_STATUS_FAILED;
968         }
969         *sentLength = dataLength;
970     }
971     else
972     {
973         if (CA_STATUS_OK != CABTSendData(device->socketFD, data, dataLength, sentLength))
974         {
975             OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to send data!");
976             return CA_STATUS_FAILED;
977         }
978     }
979
980     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
981     return CA_STATUS_OK;
982 }
983
984 CAResult_t CABTManagerSendMulticastData(const char *serviceUUID, void *data,
985                                         uint32_t dataLength, uint32_t *sentLength)
986 {
987     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
988
989     //Input validation
990     VERIFY_NON_NULL(serviceUUID, BLUETOOTH_ADAPTER_TAG, "service UUID is null");
991     VERIFY_NON_NULL(data, BLUETOOTH_ADAPTER_TAG, "Data is null");
992     VERIFY_NON_NULL(sentLength, BLUETOOTH_ADAPTER_TAG, "Sent data length holder is null");
993
994     if (0 >= dataLength)
995     {
996         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Invalid input: Negative data length!");
997         return CA_STATUS_INVALID_PARAM;
998     }
999
1000     *sentLength = dataLength;
1001
1002     //Send the packet to all OIC devices
1003     u_mutex_lock(gBTDeviceListMutex);
1004     BTDeviceList *curList = gBTDeviceList;
1005     while (curList != NULL)
1006     {
1007         BTDevice *device = curList->device;
1008         curList = curList->next;
1009
1010         if (!device)
1011         {
1012             OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "There is no device!");
1013             break;
1014         }
1015
1016         if (-1 == device->socketFD)
1017         {
1018             //Check if the device service search is finished
1019             if (0 == device->serviceSearched)
1020             {
1021                 OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Device services are still unknown!");
1022                 continue;
1023             }
1024
1025             //Adding to pendding list
1026             if (CA_STATUS_OK != CAAddBTDataToList(&device->pendingDataList, data,
1027                                                   dataLength))
1028             {
1029                 OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to add data to pending list !");
1030                 continue;
1031             }
1032
1033             //Make a rfcomm connection with remote BT Device
1034             if (CA_STATUS_OK != CABTClientConnect(device->remoteAddress, device->serviceUUID))
1035             {
1036                 OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to make RFCOMM connection !");
1037
1038                 //Remove the data which added to pending list
1039                 CARemoveBTDataFromList(&device->pendingDataList);
1040                 continue;
1041             }
1042         }
1043         else
1044         {
1045             if (CA_STATUS_OK != CABTSendData(device->socketFD, data, dataLength, sentLength))
1046             {
1047                 OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to send data to [%s] !",
1048                           device->remoteAddress);
1049             }
1050         }
1051     }
1052     u_mutex_unlock(gBTDeviceListMutex);
1053
1054     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
1055     return CA_STATUS_OK;
1056 }
1057
1058 CAResult_t CABTGetAdapterEnableState(bool *state)
1059 {
1060     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
1061
1062     //Input validation
1063     VERIFY_NON_NULL(state, BLUETOOTH_ADAPTER_TAG, "state holder is NULL!");
1064
1065     bt_error_e err = BT_ERROR_NONE;
1066     bt_adapter_state_e adapterState;
1067
1068     //Get Bluetooth adapter state
1069     if (BT_ERROR_NONE != (err = bt_adapter_get_state(&adapterState)))
1070     {
1071         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Bluetooth get state failed!, error num [%x]",
1072                   err);
1073
1074         return CA_STATUS_FAILED;
1075     }
1076
1077     *state = false;
1078     if (BT_ADAPTER_ENABLED == adapterState)
1079     {
1080         *state = true;
1081     }
1082
1083     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
1084     return CA_STATUS_OK;
1085 }
1086
1087 CAResult_t CABTStartDeviceDiscovery(void)
1088 {
1089     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
1090
1091     bt_error_e err = BT_ERROR_NONE;
1092     bool isDiscoveryStarted = false;
1093
1094     //Check the device discovery state
1095     if (BT_ERROR_NONE != (err = bt_adapter_is_discovering(&isDiscoveryStarted)))
1096     {
1097         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to get discovery state!, error num [%x]",
1098                   err);
1099         return CA_STATUS_FAILED;
1100     }
1101
1102     //Start device discovery if its not started
1103     if (false == isDiscoveryStarted)
1104     {
1105         if (BT_ERROR_NONE != (err = bt_adapter_start_device_discovery()))
1106         {
1107             OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Device discovery failed!, error num [%x]",
1108                       err);
1109             return CA_STATUS_FAILED;
1110         }
1111     }
1112
1113     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
1114     return CA_STATUS_OK;
1115 }
1116
1117 CAResult_t CABTStopDeviceDiscovery(void)
1118 {
1119     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
1120
1121     bt_error_e err = BT_ERROR_NONE;
1122     bool isDiscoveryStarted = false;
1123
1124     //Check the device discovery state
1125     if (BT_ERROR_NONE != (err = bt_adapter_is_discovering(&isDiscoveryStarted)))
1126     {
1127         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to get discovery state!, error num [%x]",
1128                   err);
1129         return CA_STATUS_FAILED;
1130     }
1131
1132     //stop the device discovery process
1133     if (true == isDiscoveryStarted)
1134     {
1135         OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "Stopping the device search process");
1136         if (BT_ERROR_NONE != (err = bt_adapter_stop_device_discovery()))
1137         {
1138             OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to stop discovery!, error num [%x]",
1139                       err);
1140         }
1141     }
1142
1143     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
1144     return CA_STATUS_OK;
1145 }
1146
1147 CAResult_t CABTStartServiceSearch(const char *remoteAddress)
1148 {
1149     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
1150
1151     bt_error_e err = BT_ERROR_NONE;
1152
1153     //Input validation
1154     VERIFY_NON_NULL(remoteAddress, BLUETOOTH_ADAPTER_TAG, "Remote address is null");
1155     if (0 == strlen(remoteAddress))
1156     {
1157         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Remote address is empty!");
1158         return CA_STATUS_INVALID_PARAM;
1159     }
1160
1161     //Start searching for OIC service
1162     if (BT_ERROR_NONE != (err = bt_device_start_service_search(remoteAddress)))
1163     {
1164         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Get bonded device failed!, error num [%x]",
1165                   err);
1166         return CA_STATUS_FAILED;
1167     }
1168
1169     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
1170     return CA_STATUS_OK;
1171 }
1172
1173 CAResult_t CABTStopServiceSearch(void)
1174 {
1175     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
1176
1177     bt_error_e err = BT_ERROR_NONE;
1178
1179     //Stop ongoing service search
1180     if (BT_ERROR_NONE != (err = bt_device_cancel_service_search()))
1181     {
1182         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Get bonded device failed!, error num [%x]",
1183                   err);
1184         return CA_STATUS_FAILED;
1185     }
1186
1187     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
1188     return CA_STATUS_OK;
1189 }
1190
1191 void CABTAdapterStateChangeCallback(int result, bt_adapter_state_e adapterState,
1192                                     void *userData)
1193 {
1194     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
1195
1196     if (BT_ADAPTER_ENABLED == adapterState)
1197     {
1198         // checking for adapter state. If not started then start.
1199         if (FALSE == gAdapterState)
1200         {
1201             CABTManagerStart();
1202             gAdapterState = TRUE;
1203             //starting RFcommserver
1204             if (gServerState == TRUE)
1205             {
1206                 CABTManagerStartServer();
1207                 gServerState = FALSE;
1208             }
1209         }
1210         //Notity to upper layer
1211         CABTNotifyNetworkStauts(CA_INTERFACE_UP);
1212     }
1213     else if (BT_ADAPTER_DISABLED == adapterState)
1214     {
1215         //Notity to upper layer
1216         CABTNotifyNetworkStauts(CA_INTERFACE_DOWN);
1217         gAdapterState = FALSE;
1218     }
1219
1220     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
1221 }
1222
1223 void CABTSocketConnectionStateCallback(int result, bt_socket_connection_state_e state,
1224                                        bt_socket_connection_s *connection, void *userData)
1225 {
1226     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
1227
1228     BTDevice *device = NULL;
1229
1230     if (BT_ERROR_NONE != result || NULL == connection)
1231     {
1232         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Invalid connection state!, error num [%x]",
1233                   result);
1234         return;
1235     }
1236
1237     switch (state)
1238     {
1239         case BT_SOCKET_CONNECTED:
1240             {
1241                 u_mutex_lock(gBTDeviceListMutex);
1242                 if (CA_STATUS_OK != CAGetBTDevice(gBTDeviceList, connection->remote_address,
1243                                                   &device))
1244                 {
1245                     //Create the deviceinfo and add to list
1246                     if (CA_STATUS_OK != CACreateAndAddToDeviceList(&gBTDeviceList,
1247                             connection->remote_address, OIC_BT_SERVICE_ID, &device))
1248                     {
1249                         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed add device to list!");
1250                         u_mutex_unlock(gBTDeviceListMutex);
1251                         return;
1252                     }
1253
1254                     device->socketFD = connection->socket_fd;
1255                     u_mutex_unlock(gBTDeviceListMutex);
1256                     return;
1257                 }
1258
1259                 device->socketFD = connection->socket_fd;
1260                 while (device->pendingDataList)
1261                 {
1262                     uint32_t sentData = 0;
1263                     BTData *btData = device->pendingDataList->data;
1264                     if (CA_STATUS_OK != CABTSendData(device->socketFD, btData->data,
1265                                                      btData->dataLength, &sentData))
1266                     {
1267                         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to send pending data [%s]",
1268                                   device->remoteAddress);
1269
1270                         //Remove all the data from pending list
1271                         CADestroyBTDataList(&device->pendingDataList);
1272                         break;
1273                     }
1274
1275                     //Remove the data which send from pending list
1276                     CARemoveBTDataFromList(&device->pendingDataList);
1277                 }
1278                 u_mutex_unlock(gBTDeviceListMutex);
1279             }
1280             break;
1281
1282         case BT_SOCKET_DISCONNECTED:
1283             {
1284                 u_mutex_lock(gBTDeviceListMutex);
1285                 CARemoveBTDeviceFromList(&gBTDeviceList, connection->remote_address);
1286                 u_mutex_unlock(gBTDeviceListMutex);
1287             }
1288             break;
1289     }
1290
1291     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
1292 }
1293
1294 void CABTDataRecvCallback(bt_socket_received_data_s *data, void *userData)
1295 {
1296     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
1297
1298     BTDevice *device = NULL;
1299
1300     if (NULL == data || 0 >= data->data_size)
1301     {
1302         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Data is null!");
1303         return;
1304     }
1305
1306     if (NULL == gNetworkPacketReceivedCallback)
1307     {
1308         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Callback is not registered!");
1309         return;
1310     }
1311
1312     //Get BT device from list
1313     u_mutex_lock(gBTDeviceListMutex);
1314     if (CA_STATUS_OK != CAGetBTDeviceBySocketId(gBTDeviceList, data->socket_fd, &device))
1315     {
1316         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Could not find the device!");
1317
1318         u_mutex_unlock(gBTDeviceListMutex);
1319         return;
1320     }
1321     u_mutex_unlock(gBTDeviceListMutex);
1322
1323     uint32_t sentLength = 0;
1324
1325     CAResult_t res = CABTManagerPushDataToReceiverQueue(device->remoteAddress, OIC_BT_SERVICE_ID,
1326                      data->data, (uint32_t)data->data_size, &sentLength);
1327
1328     OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "CABTManagerPushDataToReceiverQueue done [%d]", res);
1329
1330     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
1331 }
1332
1333 void CABTDeviceDiscoveryCallback(int result, bt_adapter_device_discovery_state_e state,
1334                                  bt_adapter_device_discovery_info_s *discoveryInfo, void *userData)
1335 {
1336     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
1337
1338     BTDevice *device = NULL;
1339
1340     if (BT_ERROR_NONE != result)
1341     {
1342         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Received bad state!, error num [%x]",
1343                   result);
1344         return;
1345     }
1346
1347     switch (state)
1348     {
1349         case BT_ADAPTER_DEVICE_DISCOVERY_STARTED:
1350             {
1351                 OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "Discovery started!");
1352             }
1353             break;
1354
1355         case BT_ADAPTER_DEVICE_DISCOVERY_FINISHED:
1356             {
1357                 OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "Discovery finished!");
1358             }
1359             break;
1360
1361         case BT_ADAPTER_DEVICE_DISCOVERY_FOUND:
1362             {
1363                 OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "Device discovered [%s]!",
1364                           discoveryInfo->remote_name);
1365                 if (true == CABTIsServiceSupported((const char **)discoveryInfo->service_uuid,
1366                                                    discoveryInfo->service_count,
1367                                                    OIC_BT_SERVICE_ID))
1368                 {
1369                     //Check if the deivce is already in the list
1370                     u_mutex_lock(gBTDeviceListMutex);
1371                     if (CA_STATUS_OK == CAGetBTDevice(gBTDeviceList, discoveryInfo->remote_address,
1372                                                       &device))
1373                     {
1374                         device->serviceSearched = 1;
1375                         u_mutex_unlock(gBTDeviceListMutex);
1376                         return;
1377                     }
1378
1379                     //Create the deviceinfo and add to list
1380                     if (CA_STATUS_OK != CACreateAndAddToDeviceList(&gBTDeviceList,
1381                             discoveryInfo->remote_address, OIC_BT_SERVICE_ID, &device))
1382                     {
1383                         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to add device to list!");
1384                         u_mutex_unlock(gBTDeviceListMutex);
1385                         return;
1386                     }
1387
1388                     device->serviceSearched = 1;
1389                     u_mutex_unlock(gBTDeviceListMutex);
1390                 }
1391                 else
1392                 {
1393                     OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Device does not support OIC service!");
1394                 }
1395             }
1396             break;
1397     }
1398
1399     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
1400 }
1401
1402 void CABTServiceSearchedCallback(int32_t result, bt_device_sdp_info_s *sdpInfo, void *userData)
1403 {
1404     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
1405
1406     if (NULL == sdpInfo)
1407     {
1408         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "SDP info is null!");
1409         return;
1410     }
1411
1412     u_mutex_lock(gBTDeviceListMutex);
1413
1414     BTDevice *device = NULL;
1415     if (CA_STATUS_OK == CAGetBTDevice(gBTDeviceList, sdpInfo->remote_address, &device)
1416         && NULL != device)
1417     {
1418         if (1 == device->serviceSearched)
1419         {
1420             OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "Service is already searched for this device!");
1421             u_mutex_unlock(gBTDeviceListMutex);
1422             return;
1423         }
1424
1425         if (true == CABTIsServiceSupported((const char **)sdpInfo->service_uuid,
1426                                            sdpInfo->service_count, OIC_BT_SERVICE_ID))
1427         {
1428             device->serviceSearched = 1;
1429             if (CA_STATUS_OK != CABTClientConnect(sdpInfo->remote_address, OIC_BT_SERVICE_ID))
1430             {
1431                 OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to make rfcomm connection!");
1432
1433                 //Remove the device from device list
1434                 CARemoveBTDeviceFromList(&gBTDeviceList, sdpInfo->remote_address);
1435             }
1436         }
1437         else
1438         {
1439             OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "Device does not contain OIC service!");
1440
1441             //Remove device from list as it does not support OIC service
1442             CARemoveBTDeviceFromList(&gBTDeviceList, sdpInfo->remote_address);
1443         }
1444     }
1445
1446     u_mutex_unlock(gBTDeviceListMutex);
1447
1448     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
1449 }
1450
1451 CAResult_t CABTNotifyNetworkStauts(CANetworkStatus_t status)
1452 {
1453     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
1454
1455     //Create localconnectivity
1456     if (NULL == gLocalConnectivity)
1457     {
1458         CABTManagerGetInterface(&gLocalConnectivity);
1459     }
1460
1461     //Notity to upper layer
1462     if (gNetworkChangeCallback && gLocalConnectivity && gBTThreadPool)
1463     {
1464         //Add notification task to thread pool
1465         CABTNetworkEvent *event = CABTCreateNetworkEvent(gLocalConnectivity, status);
1466         if (NULL != event)
1467         {
1468             if (CA_STATUS_OK != u_thread_pool_add_task(gBTThreadPool, CABTOnNetworkStautsChanged,
1469                     event))
1470             {
1471                 OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to create threadpool!");
1472                 return CA_STATUS_FAILED;
1473             }
1474         }
1475     }
1476
1477     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
1478     return CA_STATUS_OK;
1479 }
1480
1481 void CABTOnNetworkStautsChanged(void *context)
1482 {
1483     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
1484
1485     if (NULL == context)
1486     {
1487         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "context is NULL!");
1488         return;
1489     }
1490
1491     CABTNetworkEvent *networkEvent = (CABTNetworkEvent *) context;
1492
1493     //Notity to upper layer
1494     if (gNetworkChangeCallback)
1495     {
1496         gNetworkChangeCallback(networkEvent->info, networkEvent->status);
1497     }
1498
1499     //Free the created Network event
1500     CABTFreeNetworkEvent(networkEvent);
1501
1502     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
1503 }
1504
1505 CABTNetworkEvent *CABTCreateNetworkEvent(CALocalConnectivity_t *connectivity,
1506         CANetworkStatus_t status)
1507 {
1508     VERIFY_NON_NULL_RET(connectivity, BLUETOOTH_ADAPTER_TAG, "connectivity is NULL", NULL);
1509
1510     //Create CABTNetworkEvent
1511     CABTNetworkEvent *event = (CABTNetworkEvent *) OICMalloc(sizeof(CABTNetworkEvent));
1512     if (NULL == event)
1513     {
1514         OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to allocate memory to network event!");
1515         return NULL;
1516     }
1517
1518     //Create duplicate of Local connectivity
1519     event->info = CAAdapterCopyLocalEndpoint(connectivity);
1520     event->status = status;
1521     return event;
1522 }
1523
1524 void CABTFreeNetworkEvent(CABTNetworkEvent *event)
1525 {
1526     if (event)
1527     {
1528         CAAdapterFreeLocalEndpoint(event->info);
1529         OICFree(event);
1530     }
1531 }
1532
1533 void CABTManagerDisconnectAll(void)
1534 {
1535     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "IN");
1536
1537     u_mutex_lock(gBTDeviceListMutex);
1538
1539     BTDeviceList *cur = gBTDeviceList;
1540     while (cur != NULL)
1541     {
1542         BTDevice *device = cur->device;
1543         cur = cur->next;
1544
1545         if (device && 0 <= device->socketFD)
1546         {
1547             if (CA_STATUS_OK != CABTClientDisconnect(device->socketFD))
1548             {
1549                 OIC_LOG_V(ERROR, BLUETOOTH_ADAPTER_TAG, "Failed to disconnect with client :%s",
1550                           device->remoteAddress);
1551             }
1552
1553             device->socketFD = -1;
1554         }
1555     }
1556
1557     u_mutex_unlock(gBTDeviceListMutex);
1558
1559     OIC_LOG_V(DEBUG, BLUETOOTH_ADAPTER_TAG, "OUT");
1560 }
1561 CABTData *CACreateBTData(const CARemoteEndpoint_t *remoteEndpoint, void *data,
1562                          uint32_t dataLength)
1563 {
1564     CABTData *btData = (CABTData *) OICMalloc(sizeof(CABTData));
1565     if (!btData)
1566     {
1567         OIC_LOG(ERROR, BLUETOOTH_ADAPTER_TAG, "Memory allocation failed!");
1568         return NULL;
1569     }
1570
1571     btData->remoteEndpoint = CAAdapterCopyRemoteEndpoint(remoteEndpoint);
1572     btData->data = (void *)OICMalloc(dataLength);
1573     if (NULL == btData->data)
1574     {
1575         OIC_LOG(ERROR, BLUETOOTH_ADAPTER_TAG, "Memory allocation failed!");
1576         CAFreeBTData(btData);
1577         return NULL;
1578     }
1579     memcpy(btData->data, data, dataLength);
1580     btData->dataLen = dataLength;
1581
1582     return btData;
1583 }
1584
1585 void CAFreeBTData(CABTData *btData)
1586 {
1587     if (!btData)
1588         return;
1589
1590     CAAdapterFreeRemoteEndpoint(btData->remoteEndpoint);
1591     OICFree(btData->data);
1592     OICFree(btData);
1593 }