Imported Upstream version 1.1.1
[platform/upstream/iotivity.git] / resource / csdk / connectivity / src / bt_le_adapter / caleadapter.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 #include "caleadapter.h"
21
22 #include <stdio.h>
23 #include <stdlib.h>
24
25 #include "caleinterface.h"
26 #include "cacommon.h"
27 #include "camutex.h"
28 #include "caadapterutils.h"
29 #ifndef SINGLE_THREAD
30 #include "caqueueingthread.h"
31 #endif
32 #if defined(__TIZEN__) || defined(__ANDROID__)
33 #include "caleserver.h"
34 #include "caleclient.h"
35 #endif
36 #include "oic_malloc.h"
37 #include "oic_string.h"
38 #include "caremotehandler.h"
39 #include "pdu.h"
40
41 /**
42  * Logging tag for module name.
43  */
44 #define CALEADAPTER_TAG "OIC_CA_LE_ADAP"
45
46 /**
47  * The MTU supported for BLE adapter
48  */
49 #define CA_SUPPORTED_BLE_MTU_SIZE  20
50
51 /**
52  * Stores information of all the senders.
53  *
54  * This structure will be used to track and defragment all incoming
55  * data packet.
56  */
57 typedef struct
58 {
59     uint32_t recvDataLen;
60     uint32_t totalDataLen;
61     uint8_t *defragData;
62     CAEndpoint_t *remoteEndpoint;
63  } CABLESenderInfo_t;
64
65 typedef enum
66 {
67     ADAPTER_EMPTY = 1,
68     ADAPTER_BOTH_CLIENT_SERVER,
69     ADAPTER_CLIENT,
70     ADAPTER_SERVER
71 } CABLEAdapter_t;
72
73 /**
74  * Callback to provide the status of the network change to CA layer.
75  */
76 static CAAdapterChangeCallback g_networkCallback = NULL;
77
78 /**
79  * Callback to provide the status of the connection change to CA layer.
80  */
81 static CAConnectionChangeCallback g_connectionCallback = NULL;
82
83 /**
84  * bleAddress of the local adapter. Value will be initialized to zero,
85  * and will be updated later.
86  */
87 static char g_localBLEAddress[18] = { 0 };
88
89 /**
90  * Variable to differentiate btw GattServer and GattClient.
91  */
92 static CABLEAdapter_t g_adapterType = ADAPTER_EMPTY;
93
94 /**
95  * Mutex to synchronize the task to be executed on the GattServer
96  * function calls.
97  */
98 static ca_mutex g_bleIsServerMutex = NULL;
99
100 /**
101  * Mutex to synchronize the callback to be called for the network
102  * changes.
103  */
104 static ca_mutex g_bleNetworkCbMutex = NULL;
105
106 /**
107  * Mutex to synchronize the updates of the local LE address of the
108  * adapter.
109  */
110 static ca_mutex g_bleLocalAddressMutex = NULL;
111
112 /**
113  * Reference to thread pool.
114  */
115 static ca_thread_pool_t g_bleAdapterThreadPool = NULL;
116
117 /**
118  * Mutex to synchronize the task to be pushed to thread pool.
119  */
120 static ca_mutex g_bleAdapterThreadPoolMutex = NULL;
121
122 /**
123  * Mutex to synchronize the queing of the data from SenderQueue.
124  */
125 static ca_mutex g_bleClientSendDataMutex = NULL;
126
127 /**
128  * Mutex to synchronize the queing of the data from ReceiverQueue.
129  */
130 static ca_mutex g_bleReceiveDataMutex = NULL;
131
132 /**
133  * Mutex to synchronize the queing of the data from SenderQueue.
134  */
135 static ca_mutex g_bleServerSendDataMutex = NULL;
136
137 /**
138  * Mutex to synchronize the callback to be called for the
139  * adapterReqResponse.
140  */
141 static ca_mutex g_bleAdapterReqRespCbMutex = NULL;
142
143 /**
144  * Callback to be called when network packet received from either
145  * GattServer or GattClient.
146  */
147 static CANetworkPacketReceivedCallback g_networkPacketReceivedCallback = NULL;
148
149 /**
150  * Callback to notify error from the BLE adapter.
151  */
152 static CAErrorHandleCallback g_errorHandler = NULL;
153
154 /**
155  * Register network change notification callback.
156  *
157  * @param[in]  netCallback  CAAdapterChangeCallback callback which will
158  *                          be set for the change in adapter.
159  * @param[in]  connCallback CAConnectionChangeCallback callback which will
160  *                          be set for the change in connection.
161  *
162  * @return  0 on success otherwise a positive error value.
163  * @retval  ::CA_STATUS_OK  Successful.
164  * @retval  ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
165  * @retval  ::CA_STATUS_FAILED Operation failed.
166  *
167  */
168 static CAResult_t CALERegisterNetworkNotifications(CAAdapterChangeCallback netCallback,
169                                                    CAConnectionChangeCallback connCallback);
170
171 /**
172  * Set the thread pool handle which is required for spawning new
173  * thread.
174  *
175  * @param[in] handle Thread pool handle which is given by above layer
176  *                   for using thread creation task.
177  *
178  */
179 static void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle);
180
181 /**
182  * Call the callback to the upper layer when the adapter state gets
183  * changed.
184  *
185  * @param[in] adapter_state New state of the adapter to be notified to
186  *                          the upper layer.
187  */
188 static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state);
189
190 /**
191  * Call the callback to the upper layer when the device connection state gets
192  * changed.
193  *
194  * @param[in] address      LE address of the device to be notified to the upper layer.
195  * @param[in] isConnected  whether connection state is connected or not.
196  */
197 static void CALEConnectionStateChangedCb(CATransportAdapter_t adapter, const char* address,
198                                          bool isConnected);
199
200 /**
201  * Used to initialize all required mutex variable for LE Adapter
202  * implementation.
203  *
204  * @return  0 on success otherwise a positive error value.
205  * @retval  ::CA_STATUS_OK  Successful.
206  * @retval  ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
207  * @retval  ::CA_STATUS_FAILED Operation failed.
208  *
209  */
210 static CAResult_t CAInitLEAdapterMutex();
211
212 /**
213  * Terminate all required mutex variables for LE adapter
214  * implementation.
215  */
216 static void CATerminateLEAdapterMutex();
217
218 /**
219  * Prepares and notify error through error callback.
220  */
221 static void CALEErrorHandler(const char *remoteAddress,
222                              const uint8_t *data,
223                              uint32_t dataLen,
224                              CAResult_t result);
225
226 #ifndef SINGLE_THREAD
227 /**
228  * Stop condition of recvhandler.
229  */
230 static bool g_dataBleReceiverHandlerState = false;
231
232 /**
233  * Sender information.
234  */
235 static u_arraylist_t *g_bleServerSenderInfo = NULL;
236
237 static u_arraylist_t *g_bleClientSenderInfo = NULL;
238
239 /**
240  * Queue to process the outgoing packets from GATTClient.
241  */
242 static CAQueueingThread_t *g_bleClientSendQueueHandle = NULL;
243
244 /**
245  * Queue to process the incoming packets.
246  */
247 static CAQueueingThread_t *g_bleReceiverQueue = NULL;
248
249 /**
250  * Queue to process the outgoing packets from GATTServer.
251  */
252 static CAQueueingThread_t *g_bleServerSendQueueHandle = NULL;
253
254 /**
255  * This function will be associated with the sender queue for
256  * GattServer.
257  *
258  * This function will fragment the data to the MTU of the transport
259  * and send the data in fragments to the adapters. The function will
260  * be blocked until all data is sent out from the adapter.
261  *
262  * @param[in] threadData Data pushed to the queue which contains the
263  *                       info about RemoteEndpoint and Data.
264  */
265 static void CALEServerSendDataThread(void *threadData);
266
267 /**
268  * This function will be associated with the sender queue for
269  * GattClient.
270  *
271  * This function will fragment the data to the MTU of the transport
272  * and send the data in fragments to the adapters. The function will
273  * be blocked until all data is sent out from the adapter.
274  *
275  * @param[in] threadData Data pushed to the queue which contains the
276  *                       info about RemoteEndpoint and Data.
277  */
278 static void CALEClientSendDataThread(void *threadData);
279
280 /**
281  * This function will be associated with the receiver queue.
282  *
283  * This function will defragment the received data from each sender
284  * respectively and will send it up to CA layer.  Respective sender's
285  * header will provide the length of the data sent.
286  *
287  * @param[in] threadData Data pushed to the queue which contains the
288  *                       info about RemoteEndpoint and Data.
289  */
290 static void CALEDataReceiverHandler(void *threadData);
291
292 /**
293  * This function will stop all queues created for GattServer and
294  * GattClient. All four queues will be be stopped with this function
295  * invocations.
296  */
297 static void CAStopLEQueues();
298
299 /**
300  * This function will terminate all queues created for GattServer and
301  * GattClient. All four queues will be be terminated with this
302  * function invocations.
303  */
304 static void CATerminateLEQueues();
305
306 /**
307  * This function will initalize the Receiver and Sender queues for
308  * GattServer. This function will in turn call the functions
309  * CAInitBleServerReceiverQueue() and CAInitBleServerSenderQueue() to
310  * initialize the queues.
311  *
312  * @return ::CA_STATUS_OK or Appropriate error code.
313  * @retval ::CA_STATUS_OK  Successful.
314  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
315  * @retval ::CA_STATUS_FAILED Operation failed.
316  */
317 static CAResult_t CAInitLEServerQueues();
318
319 /**
320  * This function will initalize the Receiver and Sender queues for
321  * GattClient. This function will inturn call the functions
322  * CAInitBleClientReceiverQueue() and CAInitBleClientSenderQueue() to
323  * initialize the queues.
324  *
325  * @return ::CA_STATUS_OK or Appropriate error code.
326  * @retval ::CA_STATUS_OK  Successful.
327  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
328  * @retval ::CA_STATUS_FAILED Operation failed.
329  *
330  */
331 static CAResult_t CAInitLEClientQueues();
332
333 /**
334  * This function will initalize the Receiver queue for
335  * GattServer. This will initialize the queue to process the function
336  * CABLEServerSendDataThread() when ever the task is added to this
337  * queue.
338  *
339  * @return ::CA_STATUS_OK or Appropriate error code.
340  * @retval ::CA_STATUS_OK  Successful.
341  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
342  * @retval ::CA_STATUS_FAILED Operation failed.
343  */
344 static CAResult_t CAInitLEServerSenderQueue();
345
346 /**
347  * This function will initalize the Receiver queue for
348  * GattClient. This will initialize the queue to process the function
349  * CABLEClientSendDataThread() when ever the task is added to this
350  * queue.
351  *
352  * @return ::CA_STATUS_OK or Appropriate error code.
353  * @retval ::CA_STATUS_OK  Successful.
354  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
355  * @retval ::CA_STATUS_FAILED Operation failed.
356  */
357 static CAResult_t CAInitLEClientSenderQueue();
358
359 /**
360  * This function will initialize the Receiver queue for
361  * LEAdapter. This will initialize the queue to process the function
362  * CABLEDataReceiverHandler() when ever the task is added to this
363  * queue.
364  *
365  * @return ::CA_STATUS_OK or Appropriate error code
366  * @retval ::CA_STATUS_OK  Successful
367  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments
368  * @retval ::CA_STATUS_FAILED Operation failed
369  *
370  */
371 static CAResult_t CAInitLEReceiverQueue();
372
373 /**
374  * This function will create the Data required to send it in the
375  * queue.
376  *
377  * @param[in] remoteEndpoint Remote endpoint information of the
378  *                           server.
379  * @param[in] data           Data to be transmitted from LE.
380  * @param[in] dataLength     Length of the Data being transmitted.
381  *
382  * @return ::CA_STATUS_OK or Appropriate error code.
383  * @retval ::CA_STATUS_OK  Successful.
384  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
385  * @retval ::CA_STATUS_FAILED Operation failed.
386  */
387 static CALEData_t *CACreateLEData(const CAEndpoint_t *remoteEndpoint,
388                                   const uint8_t *data,
389                                   uint32_t dataLength,
390                                   u_arraylist_t *senderInfo);
391
392 /**
393  * Used to free the BLE information stored in the sender/receiver
394  * queues.
395  *
396  * @param[in] bleData Information for a particular data segment.
397  */
398 static void CAFreeLEData(CALEData_t *bleData);
399
400 /**
401  * Free data.
402  */
403 static void CALEDataDestroyer(void *data, uint32_t size);
404
405 #ifndef SINGLE_THREAD
406 /**
407  * remove request or response data of send queue.
408  *
409  * @param[in] queueHandle    queue to process the outgoing packets.
410  * @param[in] mutex          mutex related to sender for client / server.
411  * @param[in] address        target address to remove data in queue.
412  */
413 static void CALERemoveSendQueueData(CAQueueingThread_t *queueHandle,
414                                     ca_mutex mutex,
415                                     const char* address);
416
417 /**
418  * remove all received data of data list from receive queue.
419  *
420  * @param[in] dataInfoList   received data list to remove for client / server.
421  * @param[in] address        target address to remove data in queue.
422  */
423 static void CALERemoveReceiveQueueData(u_arraylist_t *dataInfoList,
424                                        const char* address);
425 #endif
426
427 static CAResult_t CAInitLEServerQueues()
428 {
429     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
430
431     ca_mutex_lock(g_bleAdapterThreadPoolMutex);
432
433     CAResult_t result = CAInitLEServerSenderQueue();
434     if (CA_STATUS_OK != result)
435     {
436         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleServerSenderQueue failed");
437         ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
438         return CA_STATUS_FAILED;
439     }
440
441     g_bleServerSenderInfo = u_arraylist_create();
442     if (!g_bleServerSenderInfo)
443     {
444         OIC_LOG(ERROR, CALEADAPTER_TAG, "memory allocation failed!");
445         ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
446         return CA_MEMORY_ALLOC_FAILED;
447     }
448
449     result = CAInitLEReceiverQueue();
450     if (CA_STATUS_OK != result)
451     {
452         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEReceiverQueue failed");
453         u_arraylist_free(&g_bleServerSenderInfo);
454         ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
455         return CA_STATUS_FAILED;
456     }
457
458     g_dataBleReceiverHandlerState = true;
459
460     ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
461
462     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
463     return CA_STATUS_OK;
464 }
465
466 static CAResult_t CAInitLEClientQueues()
467 {
468     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
469
470     ca_mutex_lock(g_bleAdapterThreadPoolMutex);
471
472     CAResult_t result = CAInitLEClientSenderQueue();
473     if (CA_STATUS_OK != result)
474     {
475         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientSenderQueue failed");
476         ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
477         return CA_STATUS_FAILED;
478     }
479
480     g_bleClientSenderInfo = u_arraylist_create();
481     if (!g_bleClientSenderInfo)
482     {
483         OIC_LOG(ERROR, CALEADAPTER_TAG, "memory allocation failed!");
484         ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
485         return CA_MEMORY_ALLOC_FAILED;
486     }
487
488     result = CAInitLEReceiverQueue();
489     if (CA_STATUS_OK != result)
490     {
491         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEReceiverQueue failed");
492         u_arraylist_free(&g_bleClientSenderInfo);
493         ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
494         return CA_STATUS_FAILED;
495     }
496
497     g_dataBleReceiverHandlerState = true;
498
499     ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
500
501     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
502     return CA_STATUS_OK;
503 }
504
505 static CAResult_t CAInitLEReceiverQueue()
506 {
507     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CAInitLEReceiverQueue");
508     // Check if the message queue is already initialized
509     if (g_bleReceiverQueue)
510     {
511         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
512         return CA_STATUS_OK;
513     }
514
515     // Create recv message queue
516     g_bleReceiverQueue = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
517     if (!g_bleReceiverQueue)
518     {
519         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
520         return CA_MEMORY_ALLOC_FAILED;
521     }
522
523     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleReceiverQueue,
524                                                    g_bleAdapterThreadPool,
525                                                    CALEDataReceiverHandler,
526                                                    CALEDataDestroyer))
527     {
528         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
529         OICFree(g_bleReceiverQueue);
530         g_bleReceiverQueue = NULL;
531         return CA_STATUS_FAILED;
532     }
533
534     if (CA_STATUS_OK != CAQueueingThreadStart(g_bleReceiverQueue))
535     {
536         OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
537         OICFree(g_bleReceiverQueue);
538         g_bleReceiverQueue = NULL;
539         return CA_STATUS_FAILED;
540     }
541
542     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
543     return CA_STATUS_OK;
544 }
545
546 static CAResult_t CAInitLEServerSenderQueue()
547 {
548     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CAInitLEServerSenderQueue");
549     // Check if the message queue is already initialized
550     if (g_bleServerSendQueueHandle)
551     {
552         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Queue is already initialized!");
553         return CA_STATUS_OK;
554     }
555
556     // Create send message queue
557     g_bleServerSendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
558     if (!g_bleServerSendQueueHandle)
559     {
560         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
561         return CA_MEMORY_ALLOC_FAILED;
562     }
563
564     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleServerSendQueueHandle,
565                                                    g_bleAdapterThreadPool,
566                                                    CALEServerSendDataThread,
567                                                    CALEDataDestroyer))
568     {
569         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
570         OICFree(g_bleServerSendQueueHandle);
571         g_bleServerSendQueueHandle = NULL;
572         return CA_STATUS_FAILED;
573     }
574
575     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
576     return CA_STATUS_OK;
577 }
578
579 static void CALEClearSenderInfoImpl(u_arraylist_t ** list)
580 {
581     const size_t length = u_arraylist_length(*list);
582     for (size_t i = 0; i < length; ++i)
583     {
584         CABLESenderInfo_t * const info =
585                 (CABLESenderInfo_t *) u_arraylist_get(*list, i);
586         if (info)
587          {
588              OICFree(info->defragData);
589              CAFreeEndpoint(info->remoteEndpoint);
590              OICFree(info);
591          }
592     }
593     u_arraylist_free(list);
594 }
595
596 static void CALEClearSenderInfo()
597 {
598     CALEClearSenderInfoImpl(&g_bleServerSenderInfo);
599     CALEClearSenderInfoImpl(&g_bleClientSenderInfo);
600 }
601
602 static CAResult_t CAInitLEClientSenderQueue()
603 {
604     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CAInitLEClientSenderQueue");
605
606     if (g_bleClientSendQueueHandle)
607     {
608         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
609         return CA_STATUS_OK;
610     }
611
612     // Create send message queue
613     g_bleClientSendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
614     if (!g_bleClientSendQueueHandle)
615     {
616         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
617         return CA_MEMORY_ALLOC_FAILED;
618     }
619
620     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleClientSendQueueHandle,
621                                                    g_bleAdapterThreadPool,
622                                                    CALEClientSendDataThread, CALEDataDestroyer))
623     {
624         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
625         OICFree(g_bleClientSendQueueHandle);
626         g_bleClientSendQueueHandle = NULL;
627         return CA_STATUS_FAILED;
628     }
629
630     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CAInitLEClientSenderQueue");
631     return CA_STATUS_OK;
632 }
633
634 static void CAStopLEQueues()
635 {
636     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CAStopLEQueues");
637
638     ca_mutex_lock(g_bleReceiveDataMutex);
639     if (NULL != g_bleReceiverQueue)
640     {
641         CAQueueingThreadStop(g_bleReceiverQueue);
642     }
643     ca_mutex_unlock(g_bleReceiveDataMutex);
644
645     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CAStopLEQueues");
646 }
647
648 static void CATerminateLEQueues()
649 {
650     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
651
652     CAQueueingThreadDestroy(g_bleClientSendQueueHandle);
653     OICFree(g_bleClientSendQueueHandle);
654     g_bleClientSendQueueHandle = NULL;
655
656     CAQueueingThreadDestroy(g_bleServerSendQueueHandle);
657     OICFree(g_bleServerSendQueueHandle);
658     g_bleServerSendQueueHandle = NULL;
659
660     CAQueueingThreadDestroy(g_bleReceiverQueue);
661     OICFree(g_bleReceiverQueue);
662     g_bleReceiverQueue = NULL;
663
664     CALEClearSenderInfo();
665
666     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
667 }
668
669 static CAResult_t CALEGetSenderInfo(const char *leAddress,
670                                     u_arraylist_t *senderInfoList,
671                                     CABLESenderInfo_t **senderInfo,
672                                     uint32_t *senderIndex)
673 {
674     VERIFY_NON_NULL_RET(leAddress,
675                         CALEADAPTER_TAG,
676                         "NULL BLE address argument",
677                         CA_STATUS_INVALID_PARAM);
678     VERIFY_NON_NULL_RET(senderIndex,
679                         CALEADAPTER_TAG,
680                         "NULL index argument",
681                         CA_STATUS_INVALID_PARAM);
682
683     const uint32_t listLength = u_arraylist_length(senderInfoList);
684     const uint32_t addrLength = strlen(leAddress);
685     for (uint32_t index = 0; index < listLength; index++)
686     {
687         CABLESenderInfo_t *info = (CABLESenderInfo_t *) u_arraylist_get(senderInfoList, index);
688         if(!info || !(info->remoteEndpoint))
689         {
690             continue;
691         }
692
693         if(!strncmp(info->remoteEndpoint->addr, leAddress, addrLength))
694         {
695             *senderIndex = index;
696             if(senderInfo)
697             {
698                 *senderInfo = info;
699             }
700             return CA_STATUS_OK;
701         }
702     }
703
704     return CA_STATUS_FAILED;
705 }
706
707 static void CALEDataReceiverHandler(void *threadData)
708 {
709     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CALEDataReceiverHandler");
710
711     ca_mutex_lock(g_bleReceiveDataMutex);
712
713     if (g_dataBleReceiverHandlerState)
714     {
715         OIC_LOG(DEBUG, CALEADAPTER_TAG, "checking for DE Fragmentation");
716
717         CALEData_t *bleData = (CALEData_t *) threadData;
718         if (!bleData)
719         {
720             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bleData!");
721             ca_mutex_unlock(g_bleReceiveDataMutex);
722             return;
723         }
724
725         if (!(bleData->senderInfo))
726         {
727             OIC_LOG(ERROR, CALEADAPTER_TAG, "sender info is not available");
728             ca_mutex_unlock(g_bleReceiveDataMutex);
729             return;
730         }
731
732         if (!(bleData->remoteEndpoint))
733         {
734             OIC_LOG(ERROR, CALEADAPTER_TAG, "Client RemoteEndPoint NULL!!");
735             ca_mutex_unlock(g_bleReceiveDataMutex);
736             return;
737         }
738
739         CABLESenderInfo_t *senderInfo = NULL;
740         uint32_t senderIndex = 0;
741
742         if(CA_STATUS_OK != CALEGetSenderInfo(bleData->remoteEndpoint->addr,
743                                              bleData->senderInfo,
744                                              &senderInfo, &senderIndex))
745         {
746             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "This is a new client [%s]",
747                       bleData->remoteEndpoint->addr);
748         }
749
750         if(!senderInfo)
751         {
752             CABLESenderInfo_t *newSender = OICMalloc(sizeof(CABLESenderInfo_t));
753             if(!newSender)
754             {
755                 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed for new sender");
756                 ca_mutex_unlock(g_bleReceiveDataMutex);
757                 return;
758             }
759             newSender->recvDataLen = 0;
760             newSender->totalDataLen = 0;
761             newSender->defragData = NULL;
762             newSender->remoteEndpoint = NULL;
763
764             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Parsing the header");
765
766             newSender->totalDataLen = coap_get_total_message_length(bleData->data, bleData->dataLen);
767
768             if(!(newSender->totalDataLen))
769             {
770                 OIC_LOG(ERROR, CALEADAPTER_TAG, "Total Data Length is parsed as 0!!!");
771                 OICFree(newSender);
772                 ca_mutex_unlock(g_bleReceiveDataMutex);
773                 return;
774             }
775
776             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Total data to be accumulated [%u] bytes",
777                       newSender->totalDataLen);
778             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "data received in the first packet [%u] bytes",
779                       bleData->dataLen);
780
781             newSender->defragData = OICCalloc(newSender->totalDataLen + 1,
782                                               sizeof(*newSender->defragData));
783
784             if (NULL == newSender->defragData)
785             {
786                 OIC_LOG(ERROR, CALEADAPTER_TAG, "defragData is NULL!");
787                 OICFree(newSender);
788                 ca_mutex_unlock(g_bleReceiveDataMutex);
789                 return;
790             }
791
792             const char *remoteAddress = bleData->remoteEndpoint->addr;
793             newSender->remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
794                                                                CA_ADAPTER_GATT_BTLE,
795                                                                remoteAddress,
796                                                                0);
797             if (NULL == newSender->remoteEndpoint)
798             {
799                 OIC_LOG(ERROR, CALEADAPTER_TAG, "remoteEndpoint is NULL!");
800                 OICFree(newSender->defragData);
801                 OICFree(newSender);
802                 ca_mutex_unlock(g_bleReceiveDataMutex);
803                 return;
804             }
805
806             if (newSender->recvDataLen + bleData->dataLen > newSender->totalDataLen)
807             {
808                 OIC_LOG(ERROR, CALEADAPTER_TAG, "buffer is smaller than received data");
809                 OICFree(newSender->defragData);
810                 CAFreeEndpoint(newSender->remoteEndpoint);
811                 OICFree(newSender);
812                 ca_mutex_unlock(g_bleReceiveDataMutex);
813                 return;
814             }
815             memcpy(newSender->defragData, bleData->data, bleData->dataLen);
816             newSender->recvDataLen += bleData->dataLen;
817
818             u_arraylist_add(bleData->senderInfo,(void *)newSender);
819
820             //Getting newSender index position in bleSenderInfo array list
821             if(CA_STATUS_OK !=
822                 CALEGetSenderInfo(newSender->remoteEndpoint->addr, bleData->senderInfo,
823                                   NULL, &senderIndex))
824             {
825                 OIC_LOG(ERROR, CALEADAPTER_TAG, "Existing sender index not found!!");
826                 OICFree(newSender->defragData);
827                 CAFreeEndpoint(newSender->remoteEndpoint);
828                 OICFree(newSender);
829                 ca_mutex_unlock(g_bleReceiveDataMutex);
830                 return;
831             }
832             senderInfo = newSender;
833         }
834         else
835         {
836             if(senderInfo->recvDataLen + bleData->dataLen > senderInfo->totalDataLen)
837             {
838                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
839                           "Data Length exceeding error!! Receiving [%d] total length [%d]",
840                           senderInfo->recvDataLen + bleData->dataLen, senderInfo->totalDataLen);
841                 u_arraylist_remove(bleData->senderInfo, senderIndex);
842                 OICFree(senderInfo->defragData);
843                 OICFree(senderInfo);
844                 ca_mutex_unlock(g_bleReceiveDataMutex);
845                 return;
846             }
847             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Copying the data of length [%d]",
848                       bleData->dataLen);
849             memcpy(senderInfo->defragData + senderInfo->recvDataLen, bleData->data,
850                    bleData->dataLen);
851             senderInfo->recvDataLen += bleData->dataLen ;
852             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "totalDatalength  [%d] received Datalen [%d]",
853                                                 senderInfo->totalDataLen, senderInfo->recvDataLen);
854         }
855
856         if (senderInfo->totalDataLen == senderInfo->recvDataLen)
857         {
858             ca_mutex_lock(g_bleAdapterReqRespCbMutex);
859             if (NULL == g_networkPacketReceivedCallback)
860             {
861                 OIC_LOG(ERROR, CALEADAPTER_TAG, "gReqRespCallback is NULL!");
862
863                 u_arraylist_remove(bleData->senderInfo, senderIndex);
864                 OICFree(senderInfo->defragData);
865                 OICFree(senderInfo);
866                 ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
867                 ca_mutex_unlock(g_bleReceiveDataMutex);
868                 return;
869             }
870
871             OIC_LOG(DEBUG, CALEADAPTER_TAG, "[CALEDataReceiverHandler] Sending data up !");
872
873             const CASecureEndpoint_t tmp =
874                 {
875                     .endpoint = *senderInfo->remoteEndpoint
876                 };
877
878             g_networkPacketReceivedCallback(&tmp,
879                                             senderInfo->defragData,
880                                             senderInfo->recvDataLen);
881             ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
882             u_arraylist_remove(bleData->senderInfo, senderIndex);
883             senderInfo->remoteEndpoint = NULL;
884             senderInfo->defragData = NULL;
885             OICFree(senderInfo);
886         }
887     }
888     ca_mutex_unlock(g_bleReceiveDataMutex);
889     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
890 }
891
892 static void CALEServerSendDataThread(void *threadData)
893 {
894     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CALEServerSendDataThread");
895
896     CALEData_t * const bleData = (CALEData_t *) threadData;
897     if (!bleData)
898     {
899         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bledata!");
900         return;
901     }
902
903     const uint32_t totalLength = bleData->dataLen;
904
905     OIC_LOG_V(DEBUG,
906               CALEADAPTER_TAG,
907               "Server total Data length with header is [%u]",
908               totalLength);
909
910     uint8_t * const dataSegment = OICCalloc(totalLength, 1);
911
912     if (NULL == dataSegment)
913     {
914         OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failed");
915         return;
916     }
917
918     uint32_t length = 0;
919     if (CA_SUPPORTED_BLE_MTU_SIZE > totalLength)
920     {
921         length = totalLength;
922         memcpy(dataSegment, bleData->data, bleData->dataLen);
923     }
924     else
925     {
926         length =  CA_SUPPORTED_BLE_MTU_SIZE;
927         memcpy(dataSegment, bleData->data, CA_SUPPORTED_BLE_MTU_SIZE);
928     }
929
930     uint32_t iter = totalLength / CA_SUPPORTED_BLE_MTU_SIZE;
931     uint32_t index = 0;
932     CAResult_t result = CA_STATUS_FAILED;
933
934     // Send the first segment with the header.
935     if (NULL != bleData->remoteEndpoint) // Sending Unicast Data
936     {
937         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Unicast Data");
938
939         result = CAUpdateCharacteristicsToGattClient(
940                     bleData->remoteEndpoint->addr, dataSegment, length);
941
942         if (CA_STATUS_OK != result)
943         {
944             OIC_LOG_V(ERROR,
945                       CALEADAPTER_TAG,
946                       "Update characteristics failed, result [%d]",
947                       result);
948
949             g_errorHandler(bleData->remoteEndpoint,
950                            bleData->data,
951                            bleData->dataLen,
952                            result);
953             OICFree(dataSegment);
954             return;
955         }
956
957         OIC_LOG_V(DEBUG,
958                   CALEADAPTER_TAG,
959                   "Server Sent data length [%u]",
960                   length);
961         for (index = 1; index < iter; index++)
962         {
963             // Send the remaining header.
964             OIC_LOG_V(DEBUG,
965                       CALEADAPTER_TAG,
966                       "Sending the chunk number [%u]",
967                       index);
968
969             result =
970                 CAUpdateCharacteristicsToGattClient(
971                     bleData->remoteEndpoint->addr,
972                     bleData->data + ((index * CA_SUPPORTED_BLE_MTU_SIZE)),
973                     CA_SUPPORTED_BLE_MTU_SIZE);
974
975             if (CA_STATUS_OK != result)
976             {
977                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
978                             "Update characteristics failed, result [%d]", result);
979                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
980                 OICFree(dataSegment);
981                 return;
982             }
983             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]",
984                                                CA_SUPPORTED_BLE_MTU_SIZE);
985         }
986
987         const uint32_t remainingLen =
988             totalLength % CA_SUPPORTED_BLE_MTU_SIZE;
989
990         if (remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
991         {
992             // send the last segment of the data (Ex: 22 bytes of 622
993             // bytes of data when MTU is 200)
994             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
995
996             result = CAUpdateCharacteristicsToGattClient(
997                          bleData->remoteEndpoint->addr,
998                          bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE),
999                          remainingLen);
1000
1001             if (CA_STATUS_OK != result)
1002             {
1003                 OIC_LOG_V(ERROR,
1004                           CALEADAPTER_TAG,
1005                           "Update characteristics failed, result [%d]",
1006                           result);
1007                 g_errorHandler(bleData->remoteEndpoint,
1008                                bleData->data,
1009                                bleData->dataLen,
1010                                result);
1011                 OICFree(dataSegment);
1012                 return;
1013             }
1014             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", remainingLen);
1015         }
1016      }
1017     else
1018     {
1019         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Multicast data");
1020         result = CAUpdateCharacteristicsToAllGattClients(dataSegment, length);
1021         if (CA_STATUS_OK != result)
1022         {
1023             OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1024                       result);
1025             CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
1026             OICFree(dataSegment);
1027             return;
1028         }
1029         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", length);
1030         for (index = 1; index < iter; index++)
1031         {
1032             // Send the remaining header.
1033             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Sending the chunk number [%d]", index);
1034
1035             result = CAUpdateCharacteristicsToAllGattClients(
1036                          bleData->data + ((index * CA_SUPPORTED_BLE_MTU_SIZE)),
1037                          CA_SUPPORTED_BLE_MTU_SIZE);
1038
1039             if (CA_STATUS_OK != result)
1040             {
1041                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1042                           result);
1043                 CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
1044                 OICFree(dataSegment);
1045                 return;
1046             }
1047             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%u]",
1048                       CA_SUPPORTED_BLE_MTU_SIZE);
1049         }
1050
1051         const uint32_t remainingLen = totalLength % CA_SUPPORTED_BLE_MTU_SIZE;
1052         if (remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
1053         {
1054             // send the last segment of the data
1055             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
1056
1057             result = CAUpdateCharacteristicsToAllGattClients(
1058                          bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE),
1059                          remainingLen);
1060
1061             if (CA_STATUS_OK != result)
1062             {
1063                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1064                           result);
1065                 CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
1066                 OICFree(dataSegment);
1067                 return;
1068             }
1069             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", remainingLen);
1070         }
1071     }
1072     OICFree(dataSegment);
1073
1074     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CALEServerSendDataThread");
1075 }
1076
1077 static void CALEClientSendDataThread(void *threadData)
1078 {
1079     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CALEClientSendDataThread");
1080
1081     CALEData_t *bleData = (CALEData_t *) threadData;
1082     if (!bleData)
1083     {
1084         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bledata!");
1085         return;
1086     }
1087
1088     const uint32_t totalLength = bleData->dataLen;
1089
1090     uint8_t *dataSegment = OICCalloc(totalLength, 1);
1091     if (NULL == dataSegment)
1092     {
1093         OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failed");
1094         return;
1095     }
1096
1097     uint32_t length = 0;
1098     if (CA_SUPPORTED_BLE_MTU_SIZE > totalLength)
1099     {
1100         length = totalLength;
1101         memcpy(dataSegment,
1102                bleData->data,
1103                bleData->dataLen);
1104     }
1105     else
1106     {
1107         length = CA_SUPPORTED_BLE_MTU_SIZE;
1108         memcpy(dataSegment,
1109                bleData->data,
1110                CA_SUPPORTED_BLE_MTU_SIZE);
1111     }
1112
1113     CAResult_t result = CA_STATUS_FAILED;
1114     const uint32_t iter = totalLength / CA_SUPPORTED_BLE_MTU_SIZE;
1115     uint32_t index = 0;
1116     if (NULL != bleData->remoteEndpoint) //Sending Unicast Data
1117     {
1118         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending Unicast Data");
1119         // Send the first segment with the header.
1120         result =
1121             CAUpdateCharacteristicsToGattServer(
1122                 bleData->remoteEndpoint->addr,
1123                 dataSegment,
1124                 length,
1125                 LE_UNICAST,
1126                 0);
1127
1128         if (CA_STATUS_OK != result)
1129         {
1130             OIC_LOG_V(ERROR,
1131                       CALEADAPTER_TAG,
1132                       "Update characteristics failed, result [%d]",
1133                       result);
1134             g_errorHandler(bleData->remoteEndpoint,
1135                            bleData->data,
1136                            bleData->dataLen,
1137                            result);
1138             OICFree(dataSegment);
1139             return;
1140         }
1141
1142         OIC_LOG_V(DEBUG,
1143                   CALEADAPTER_TAG,
1144                   "Client Sent Data length  is [%u]",
1145                   length);
1146
1147         for (index = 1; index < iter; index++)
1148         {
1149             // Send the remaining header.
1150             result = CAUpdateCharacteristicsToGattServer(
1151                      bleData->remoteEndpoint->addr,
1152                      bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE),
1153                      CA_SUPPORTED_BLE_MTU_SIZE,
1154                      LE_UNICAST, 0);
1155
1156             if (CA_STATUS_OK != result)
1157             {
1158                 OIC_LOG_V(ERROR,
1159                           CALEADAPTER_TAG,
1160                           "Update characteristics failed, result [%d]",
1161                           result);
1162                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1163                 OICFree(dataSegment);
1164                 return;
1165             }
1166             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]",
1167                                                CA_SUPPORTED_BLE_MTU_SIZE);
1168         }
1169
1170         const uint32_t remainingLen = totalLength % CA_SUPPORTED_BLE_MTU_SIZE;
1171         if (remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
1172         {
1173             // send the last segment of the data (Ex: 22 bytes of 622
1174             // bytes of data when MTU is 200)
1175             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
1176
1177             result = CAUpdateCharacteristicsToGattServer(
1178                      bleData->remoteEndpoint->addr,
1179                      bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE),
1180                      remainingLen,
1181                      LE_UNICAST, 0);
1182
1183             if (CA_STATUS_OK != result)
1184             {
1185                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1186                                                    result);
1187                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
1188                 OICFree(dataSegment);
1189                 return;
1190             }
1191             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]", remainingLen);
1192         }
1193     }
1194     else
1195     {
1196         //Sending Mulitcast Data
1197         // Send the first segment with the header.
1198         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending Multicast Data");
1199         result = CAUpdateCharacteristicsToAllGattServers(dataSegment, length);
1200         if (CA_STATUS_OK != result)
1201         {
1202             OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1203                       "Update characteristics (all) failed, result [%d]", result);
1204             CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
1205             OICFree(dataSegment);
1206             return ;
1207         }
1208         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]", length);
1209         // Send the remaining header.
1210         for (index = 1; index < iter; index++)
1211         {
1212             result = CAUpdateCharacteristicsToAllGattServers(
1213                          bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE),
1214                          CA_SUPPORTED_BLE_MTU_SIZE);
1215
1216             if (CA_STATUS_OK != result)
1217             {
1218                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
1219                           result);
1220                 CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
1221                 OICFree(dataSegment);
1222                 return;
1223             }
1224             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]",
1225                       CA_SUPPORTED_BLE_MTU_SIZE);
1226         }
1227
1228         uint32_t remainingLen = totalLength % CA_SUPPORTED_BLE_MTU_SIZE;
1229         if (remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
1230         {
1231             // send the last segment of the data (Ex: 22 bytes of 622
1232             // bytes of data when MTU is 200)
1233             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
1234             result =
1235                 CAUpdateCharacteristicsToAllGattServers(
1236                     bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE),
1237                     remainingLen);
1238
1239             if (CA_STATUS_OK != result)
1240             {
1241                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1242                           "Update characteristics (all) failed, result [%d]", result);
1243                 CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
1244                 OICFree(dataSegment);
1245                 return;
1246             }
1247             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]", remainingLen);
1248         }
1249
1250     }
1251
1252     OICFree(dataSegment);
1253
1254     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CABLEClientSendDataThread");
1255 }
1256
1257 static CALEData_t *CACreateLEData(const CAEndpoint_t *remoteEndpoint,
1258                                   const uint8_t *data,
1259                                   uint32_t dataLength,
1260                                   u_arraylist_t *senderInfo)
1261 {
1262     CALEData_t * const bleData = OICMalloc(sizeof(CALEData_t));
1263
1264     if (!bleData)
1265     {
1266         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
1267         return NULL;
1268     }
1269
1270     bleData->remoteEndpoint = CACloneEndpoint(remoteEndpoint);
1271     bleData->data = OICCalloc(dataLength + 1, 1);
1272
1273     if (NULL == bleData->data)
1274     {
1275         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
1276         CAFreeLEData(bleData);
1277         return NULL;
1278     }
1279
1280     memcpy(bleData->data, data, dataLength);
1281     bleData->dataLen = dataLength;
1282     if (senderInfo)
1283     {
1284         bleData->senderInfo = senderInfo;
1285     }
1286
1287     return bleData;
1288 }
1289
1290 static void CAFreeLEData(CALEData_t *bleData)
1291 {
1292     VERIFY_NON_NULL_VOID(bleData, CALEADAPTER_TAG, "Param bleData is NULL");
1293
1294     CAFreeEndpoint(bleData->remoteEndpoint);
1295     OICFree(bleData->data);
1296     OICFree(bleData);
1297 }
1298
1299 static void CALEDataDestroyer(void *data, uint32_t size)
1300 {
1301     if ((size_t)size < sizeof(CALEData_t *))
1302     {
1303         OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1304                   "Destroy data too small %p %d", data, size);
1305     }
1306     CALEData_t *ledata = (CALEData_t *) data;
1307
1308     CAFreeLEData(ledata);
1309 }
1310 #endif
1311
1312 static CAResult_t CAInitLEAdapterMutex()
1313 {
1314     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CAInitLEAdapterMutex");
1315
1316     if (NULL == g_bleIsServerMutex)
1317     {
1318         g_bleIsServerMutex = ca_mutex_new();
1319         if (NULL == g_bleIsServerMutex)
1320         {
1321             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1322             return CA_STATUS_FAILED;
1323         }
1324     }
1325
1326     if (NULL == g_bleNetworkCbMutex)
1327     {
1328         g_bleNetworkCbMutex = ca_mutex_new();
1329         if (NULL == g_bleNetworkCbMutex)
1330         {
1331             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1332             CATerminateLEAdapterMutex();
1333             return CA_STATUS_FAILED;
1334         }
1335     }
1336
1337     if (NULL == g_bleLocalAddressMutex)
1338     {
1339         g_bleLocalAddressMutex = ca_mutex_new();
1340         if (NULL == g_bleLocalAddressMutex)
1341         {
1342             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1343             CATerminateLEAdapterMutex();
1344             return CA_STATUS_FAILED;
1345         }
1346     }
1347
1348     if (NULL == g_bleAdapterThreadPoolMutex)
1349     {
1350         g_bleAdapterThreadPoolMutex = ca_mutex_new();
1351         if (NULL == g_bleAdapterThreadPoolMutex)
1352         {
1353             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1354             CATerminateLEAdapterMutex();
1355             return CA_STATUS_FAILED;
1356         }
1357     }
1358
1359     if (NULL == g_bleClientSendDataMutex)
1360     {
1361         g_bleClientSendDataMutex = ca_mutex_new();
1362         if (NULL == g_bleClientSendDataMutex)
1363         {
1364             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1365             CATerminateLEAdapterMutex();
1366             return CA_STATUS_FAILED;
1367         }
1368     }
1369
1370     if (NULL == g_bleServerSendDataMutex)
1371     {
1372         g_bleServerSendDataMutex = ca_mutex_new();
1373         if (NULL == g_bleServerSendDataMutex)
1374         {
1375             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1376             CATerminateLEAdapterMutex();
1377             return CA_STATUS_FAILED;
1378         }
1379     }
1380
1381     if (NULL == g_bleAdapterReqRespCbMutex)
1382     {
1383         g_bleAdapterReqRespCbMutex = ca_mutex_new();
1384         if (NULL == g_bleAdapterReqRespCbMutex)
1385         {
1386             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1387             CATerminateLEAdapterMutex();
1388             return CA_STATUS_FAILED;
1389         }
1390     }
1391
1392     if (NULL == g_bleReceiveDataMutex)
1393     {
1394         g_bleReceiveDataMutex = ca_mutex_new();
1395         if (NULL == g_bleReceiveDataMutex)
1396         {
1397             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1398             return CA_STATUS_FAILED;
1399         }
1400     }
1401
1402     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1403     return CA_STATUS_OK;
1404 }
1405
1406 static void CATerminateLEAdapterMutex()
1407 {
1408     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CATerminateLEAdapterMutex");
1409
1410     ca_mutex_free(g_bleIsServerMutex);
1411     g_bleIsServerMutex = NULL;
1412
1413     ca_mutex_free(g_bleNetworkCbMutex);
1414     g_bleNetworkCbMutex = NULL;
1415
1416     ca_mutex_free(g_bleLocalAddressMutex);
1417     g_bleLocalAddressMutex = NULL;
1418
1419     ca_mutex_free(g_bleAdapterThreadPoolMutex);
1420     g_bleAdapterThreadPoolMutex = NULL;
1421
1422     ca_mutex_free(g_bleClientSendDataMutex);
1423     g_bleClientSendDataMutex = NULL;
1424
1425     ca_mutex_free(g_bleServerSendDataMutex);
1426     g_bleServerSendDataMutex = NULL;
1427
1428     ca_mutex_free(g_bleAdapterReqRespCbMutex);
1429     g_bleAdapterReqRespCbMutex = NULL;
1430
1431     ca_mutex_free(g_bleReceiveDataMutex);
1432     g_bleReceiveDataMutex = NULL;
1433
1434     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1435 }
1436
1437 /**
1438  * Starting LE connectivity adapters.
1439  *
1440  * As its peer to peer it does not require to start any servers.
1441  *
1442  * @return ::CA_STATUS_OK or Appropriate error code.
1443  */
1444 static CAResult_t CAStartLE();
1445
1446 /**
1447  * Start listening server for receiving multicast search requests.
1448  *
1449  * Transport Specific Behavior:
1450  *   LE  Starts GATT Server with prefixed UUID and Characteristics
1451  *   per OIC Specification.
1452  * @return  ::CA_STATUS_OK or Appropriate error code.
1453  */
1454 static CAResult_t CAStartLEListeningServer();
1455
1456 /**
1457  * Stops listening server from receiving multicast search requests.
1458  *
1459  * Transport Specific Behavior:
1460  *   LE  Starts GATT Server with prefixed UUID and Characteristics
1461  *   per OIC Specification.
1462  * @return  ::CA_STATUS_OK or Appropriate error code.
1463  */
1464 static CAResult_t CAStopLEListeningServer();
1465
1466 /**
1467  * Sarting discovery of servers for receiving multicast
1468  * advertisements.
1469  *
1470  * Transport Specific Behavior:
1471  *   LE  Starts GATT Server with prefixed UUID and Characteristics
1472  *   per OIC Specification.
1473  *
1474  * @return ::CA_STATUS_OK or Appropriate error code
1475  */
1476 static CAResult_t CAStartLEDiscoveryServer();
1477
1478 /**
1479  * Send data to the endpoint using the adapter connectivity.
1480  *
1481  * @param[in] endpoint Remote Endpoint information (like MAC address,
1482  *                     reference URI and connectivity type) to which
1483  *                     the unicast data has to be sent.
1484  * @param[in] data     Data which required to be sent.
1485  * @param[in] dataLen  Size of data to be sent.
1486  *
1487  * @note  dataLen must be > 0.
1488  *
1489  * @return The number of bytes sent on the network, or -1 on error.
1490  */
1491 static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
1492                                    const void *data,
1493                                    uint32_t dataLen);
1494
1495 /**
1496  * Send multicast data to the endpoint using the LE connectivity.
1497  *
1498  * @param[in] endpoint Remote Endpoint information to which the
1499  *                     multicast data has to be sent.
1500  * @param[in] data     Data which required to be sent.
1501  * @param[in] dataLen  Size of data to be sent.
1502  *
1503  * @note  dataLen must be > 0.
1504  *
1505  * @return The number of bytes sent on the network, or -1 on error.
1506  */
1507 static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
1508                                      const void *data,
1509                                      uint32_t dataLen);
1510
1511 /**
1512  * Get LE Connectivity network information.
1513  *
1514  * @param[out] info Local connectivity information structures.
1515  * @param[out] size Number of local connectivity structures.
1516  *
1517  * @return ::CA_STATUS_OK or Appropriate error code.
1518  */
1519 static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info,
1520                                               uint32_t *size);
1521
1522 /**
1523  * Read Synchronous API callback.
1524  *
1525  * @return  ::CA_STATUS_OK or Appropriate error code.
1526  */
1527 static CAResult_t CAReadLEData();
1528
1529 /**
1530  * Stopping the adapters and close socket connections.
1531  *
1532  * LE Stops all GATT servers and GATT Clients.
1533  *
1534  * @return ::CA_STATUS_OK or Appropriate error code.
1535  */
1536 static CAResult_t CAStopLE();
1537
1538 /**
1539  * Terminate the LE connectivity adapter.
1540  *
1541  * Configuration information will be deleted from further use.
1542  */
1543 static void CATerminateLE();
1544
1545 /**
1546  * This function will receive the data from the GattServer and add the
1547  * data to the Server receiver queue.
1548  *
1549  * @param[in] remoteAddress Remote address of the device from where
1550  *                          data is received.
1551  * @param[in] data          Actual data received from the remote
1552  *                          device.
1553  * @param[in] dataLength    Length of the data received from the
1554  *                          remote device.
1555  * @param[in] sentLength    Length of the data sent from the remote
1556  *                          device.
1557  *
1558  * @return ::CA_STATUS_OK or Appropriate error code.
1559  * @retval ::CA_STATUS_OK  Successful.
1560  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
1561  * @retval ::CA_STATUS_FAILED Operation failed.
1562  *
1563  */
1564 static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
1565                                                 const uint8_t *data,
1566                                                 uint32_t dataLength,
1567                                                 uint32_t *sentLength);
1568
1569 /**
1570  * This function will receive the data from the GattClient and add the
1571  * data into the Client receiver queue.
1572  *
1573  * @param[in] remoteAddress Remote address of the device from where
1574  *                          data is received.
1575  * @param[in] data          Actual data recevied from the remote
1576  *                          device.
1577  * @param[in] dataLength    Length of the data received from the
1578  *                          remote device.
1579  * @param[in] sentLength    Length of the data sent from the remote
1580  *                          device.
1581  *
1582  * @return ::CA_STATUS_OK or Appropriate error code.
1583  * @retval ::CA_STATUS_OK  Successful.
1584  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
1585  * @retval ::CA_STATUS_FAILED Operation failed.
1586  */
1587 static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
1588                                                 const uint8_t *data,
1589                                                 uint32_t dataLength,
1590                                                 uint32_t *sentLength);
1591
1592 /**
1593  * Set the NetworkPacket received callback to CA layer from adapter
1594  * layer.
1595  *
1596  * @param[in] callback Callback handle sent from the upper layer.
1597  */
1598 static void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback);
1599
1600 /**
1601  * Push the data from CA layer to the Sender processor queue.
1602  *
1603  * @param[in] remoteEndpoint Remote endpoint information of the
1604  *                           server.
1605  * @param[in] data           Data to be transmitted from LE.
1606  * @param[in] dataLen        Length of the Data being transmitted.
1607  *
1608  * @return ::CA_STATUS_OK or Appropriate error code.
1609  * @retval ::CA_STATUS_OK  Successful.
1610  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
1611  * @retval ::CA_STATUS_FAILED Operation failed.
1612  */
1613 static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
1614                                             const uint8_t *data,
1615                                             uint32_t dataLen);
1616
1617 /**
1618  * Push the data from CA layer to the Sender processor queue.
1619  *
1620  * @param[in] remoteEndpoint Remote endpoint information of the
1621  *                           server.
1622  * @param[in] data           Data to be transmitted from LE.
1623  * @param[in] dataLen        Length of the Data being transmitted.
1624  *
1625  * @return ::CA_STATUS_OK or Appropriate error code.
1626  * @retval ::CA_STATUS_OK  Successful.
1627  * @retval ::CA_STATUS_INVALID_PARAM  Invalid input arguments.
1628  * @retval ::CA_STATUS_FAILED Operation failed.
1629  */
1630 static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
1631                                             const uint8_t *data,
1632                                             uint32_t dataLen);
1633
1634 static CAResult_t CALEAdapterGattServerStart()
1635 {
1636     OIC_LOG(DEBUG, CALEADAPTER_TAG, "Before CAStartLEGattServer");
1637
1638     CAResult_t result = CAStartLEGattServer();
1639
1640 #ifndef SINGLE_THREAD
1641     /*
1642       Don't start the server side sending queue thread until the
1643       server itself has actually started.
1644     */
1645     if (CA_STATUS_OK == result)
1646     {
1647         ca_mutex_lock(g_bleServerSendDataMutex);
1648         result = CAQueueingThreadStart(g_bleServerSendQueueHandle);
1649         ca_mutex_unlock(g_bleServerSendDataMutex);
1650
1651         if (CA_STATUS_OK != result)
1652         {
1653             OIC_LOG_V(ERROR,
1654                       CALEADAPTER_TAG,
1655                       "Unable to start server queuing thread (%d)",
1656                       result);
1657         }
1658     }
1659 #endif
1660
1661     return result;
1662 }
1663
1664 static CAResult_t CALEAdapterGattServerStop()
1665 {
1666 #ifndef SINGLE_THREAD
1667     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEAdapterGattServerStop");
1668
1669     CAResult_t result = CAStopLEGattServer();
1670     ca_mutex_lock(g_bleServerSendDataMutex);
1671     if (CA_STATUS_OK == result)
1672     {
1673         result = CAQueueingThreadStop(g_bleServerSendQueueHandle);
1674     }
1675     ca_mutex_unlock(g_bleServerSendDataMutex);
1676
1677     return result;
1678 #else
1679     return CAStopLEGattServer();
1680 #endif
1681 }
1682
1683 static CAResult_t CALEAdapterGattClientStart()
1684 {
1685     OIC_LOG(DEBUG, CALEADAPTER_TAG, "Before CAStartLEGattClient");
1686
1687     CAResult_t result = CAStartLEGattClient();
1688
1689 #ifndef SINGLE_THREAD
1690     /*
1691       Don't start the client side sending queue thread until the
1692       client itself has actually started.
1693     */
1694     if (CA_STATUS_OK == result)
1695     {
1696         ca_mutex_lock(g_bleClientSendDataMutex);
1697         result = CAQueueingThreadStart(g_bleClientSendQueueHandle);
1698         ca_mutex_unlock(g_bleClientSendDataMutex);
1699
1700         if (CA_STATUS_OK != result)
1701         {
1702             OIC_LOG(ERROR,
1703                     CALEADAPTER_TAG,
1704                     "Unable to start client queuing thread");
1705         }
1706     }
1707 #endif
1708
1709     return result;
1710 }
1711
1712 static CAResult_t CALEAdapterGattClientStop()
1713 {
1714 #ifndef SINGLE_THREAD
1715     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEAdapterGattClientStop");
1716     CAStopLEGattClient();
1717
1718     ca_mutex_lock(g_bleClientSendDataMutex);
1719     CAResult_t result = CAQueueingThreadStop(g_bleClientSendQueueHandle);
1720     ca_mutex_unlock(g_bleClientSendDataMutex);
1721
1722     return result;
1723 #else
1724     CAStopLEGattClient();
1725
1726     return CA_STATUS_OK;
1727 #endif
1728 }
1729
1730 CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
1731                           CANetworkPacketReceivedCallback reqRespCallback,
1732                           CAAdapterChangeCallback netCallback,
1733                           CAConnectionChangeCallback connCallback,
1734                           CAErrorHandleCallback errorCallback,
1735                           ca_thread_pool_t handle)
1736 {
1737     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1738
1739     //Input validation
1740     VERIFY_NON_NULL(registerCallback, CALEADAPTER_TAG, "RegisterConnectivity callback is null");
1741     VERIFY_NON_NULL(reqRespCallback, CALEADAPTER_TAG, "PacketReceived Callback is null");
1742     VERIFY_NON_NULL(netCallback, CALEADAPTER_TAG, "NetworkChange Callback is null");
1743     VERIFY_NON_NULL(connCallback, CALEADAPTER_TAG, "ConnectionChange Callback is null");
1744
1745     CAResult_t result = CA_STATUS_OK;
1746     result = CAInitLEAdapterMutex();
1747     if (CA_STATUS_OK != result)
1748     {
1749         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleAdapterMutex failed!");
1750         return CA_STATUS_FAILED;
1751     }
1752
1753     result = CAInitializeLENetworkMonitor();
1754     if (CA_STATUS_OK != result)
1755     {
1756         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLENetworkMonitor() failed");
1757         return CA_STATUS_FAILED;
1758     }
1759     CAInitializeLEAdapter();
1760
1761     CASetLEClientThreadPoolHandle(handle);
1762
1763     result = CAInitializeLEGattClient();
1764     if (CA_STATUS_OK != result)
1765     {
1766         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLEGattClient() failed");
1767         return CA_STATUS_FAILED;
1768     }
1769
1770     CASetLEReqRespClientCallback(CALEAdapterClientReceivedData);
1771     CASetLEServerThreadPoolHandle(handle);
1772     result = CAInitializeLEGattServer();
1773     if (CA_STATUS_OK != result)
1774     {
1775         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLEGattServer() failed");
1776         return CA_STATUS_FAILED;
1777     }
1778
1779     CASetLEAdapterThreadPoolHandle(handle);
1780     CASetLEReqRespServerCallback(CALEAdapterServerReceivedData);
1781     CASetLEReqRespAdapterCallback(reqRespCallback);
1782
1783     CASetBLEClientErrorHandleCallback(CALEErrorHandler);
1784     CASetBLEServerErrorHandleCallback(CALEErrorHandler);
1785     CALERegisterNetworkNotifications(netCallback, connCallback);
1786
1787     g_errorHandler = errorCallback;
1788
1789     static const CAConnectivityHandler_t connHandler =
1790         {
1791             .startAdapter = CAStartLE,
1792             .stopAdapter = CAStopLE,
1793             .startListenServer = CAStartLEListeningServer,
1794             .stopListenServer = CAStopLEListeningServer,
1795             .startDiscoveryServer = CAStartLEDiscoveryServer,
1796             .sendData = CASendLEUnicastData,
1797             .sendDataToAll = CASendLEMulticastData,
1798             .GetnetInfo = CAGetLEInterfaceInformation,
1799             .readData = CAReadLEData,
1800             .terminate = CATerminateLE,
1801             .cType = CA_ADAPTER_GATT_BTLE
1802         };
1803
1804     registerCallback(connHandler);
1805
1806     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1807
1808     return CA_STATUS_OK;
1809 }
1810
1811 static CAResult_t CAStartLE()
1812 {
1813     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CAStartLE");
1814
1815     return CAStartLEAdapter();
1816 }
1817
1818 static CAResult_t CAStopLE()
1819 {
1820     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1821 #ifndef SINGLE_THREAD
1822     CAStopLEQueues();
1823 #endif
1824
1825     ca_mutex_lock(g_bleIsServerMutex);
1826     switch (g_adapterType)
1827     {
1828         case ADAPTER_SERVER:
1829             CALEAdapterGattServerStop();
1830             break;
1831         case ADAPTER_CLIENT:
1832             CALEAdapterGattClientStop();
1833             break;
1834         case ADAPTER_BOTH_CLIENT_SERVER:
1835             CALEAdapterGattServerStop();
1836             CALEAdapterGattClientStop();
1837             break;
1838         default:
1839             break;
1840     }
1841     ca_mutex_unlock(g_bleIsServerMutex);
1842
1843     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1844
1845     return CAStopLEAdapter();
1846 }
1847
1848 static void CATerminateLE()
1849 {
1850     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1851
1852     CASetLEReqRespServerCallback(NULL);
1853     CASetLEReqRespClientCallback(NULL);
1854     CALERegisterNetworkNotifications(NULL, NULL);
1855     CASetLEReqRespAdapterCallback(NULL);
1856     CATerminateLENetworkMonitor();
1857
1858     ca_mutex_lock(g_bleIsServerMutex);
1859     switch (g_adapterType)
1860     {
1861         case ADAPTER_SERVER:
1862             CATerminateLEGattServer();
1863             break;
1864         case ADAPTER_CLIENT:
1865             CATerminateLEGattClient();
1866             break;
1867         case ADAPTER_BOTH_CLIENT_SERVER:
1868             CATerminateLEGattServer();
1869             CATerminateLEGattClient();
1870             break;
1871         default:
1872             break;
1873     }
1874     g_adapterType = ADAPTER_EMPTY;
1875     ca_mutex_unlock(g_bleIsServerMutex);
1876
1877 #ifndef SINGLE_THREAD
1878     CATerminateLEQueues();
1879 #endif
1880     CATerminateLEAdapterMutex();
1881
1882     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1883 }
1884
1885 static CAResult_t CAStartLEListeningServer()
1886 {
1887     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CAStartLEListeningServer");
1888 #ifndef ROUTING_GATEWAY
1889     CAResult_t result = CA_STATUS_OK;
1890 #ifndef SINGLE_THREAD
1891     result = CAInitLEServerQueues();
1892     if (CA_STATUS_OK != result)
1893     {
1894         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEServerQueues failed");
1895         return result;
1896     }
1897 #endif
1898
1899     ca_mutex_lock(g_bleIsServerMutex);
1900     switch (g_adapterType)
1901     {
1902         case ADAPTER_CLIENT:
1903             g_adapterType = ADAPTER_BOTH_CLIENT_SERVER;
1904             break;
1905         case ADAPTER_BOTH_CLIENT_SERVER:
1906             break;
1907         default:
1908             g_adapterType = ADAPTER_SERVER;
1909     }
1910     ca_mutex_unlock(g_bleIsServerMutex);
1911
1912     result = CAGetLEAdapterState();
1913     if (CA_STATUS_OK != result)
1914     {
1915         if (CA_ADAPTER_NOT_ENABLED == result)
1916         {
1917             OIC_LOG(DEBUG,
1918                     CALEADAPTER_TAG,
1919                     "Listen Server will be started once BT Adapter is enabled");
1920             result = CA_STATUS_OK;
1921         }
1922     }
1923     else
1924     {
1925         result = CALEAdapterGattServerStart();
1926     }
1927
1928     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1929     return result;
1930 #else
1931     // Routing Gateway only supports BLE client mode.
1932     OIC_LOG(ERROR, CALEADAPTER_TAG, "LE server not supported in Routing Gateway");
1933     return CA_NOT_SUPPORTED;
1934 #endif
1935 }
1936
1937 static CAResult_t CAStopLEListeningServer()
1938 {
1939     OIC_LOG(ERROR, CALEADAPTER_TAG, "Listen server stop not supported.");
1940     return CA_NOT_SUPPORTED;
1941 }
1942
1943 static CAResult_t CAStartLEDiscoveryServer()
1944 {
1945     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CAStartLEDiscoveryServer");
1946     CAResult_t result = CA_STATUS_OK;
1947 #ifndef SINGLE_THREAD
1948     result = CAInitLEClientQueues();
1949     if (CA_STATUS_OK != result)
1950     {
1951         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEClientQueues failed");
1952         return result;
1953     }
1954 #endif
1955
1956     ca_mutex_lock(g_bleIsServerMutex);
1957     switch (g_adapterType)
1958     {
1959         case ADAPTER_SERVER:
1960             g_adapterType = ADAPTER_BOTH_CLIENT_SERVER;
1961             break;
1962         case ADAPTER_BOTH_CLIENT_SERVER:
1963             break;
1964         default:
1965             g_adapterType = ADAPTER_CLIENT;
1966     }
1967     ca_mutex_unlock(g_bleIsServerMutex);
1968
1969     result = CAGetLEAdapterState();
1970     if (CA_STATUS_OK != result)
1971     {
1972         if (CA_ADAPTER_NOT_ENABLED == result)
1973         {
1974             OIC_LOG(DEBUG,
1975                     CALEADAPTER_TAG,
1976                     "Discovery Server will be started once BT Adapter is enabled");
1977             result = CA_STATUS_OK;
1978         }
1979     }
1980     else
1981     {
1982         result = CALEAdapterGattClientStart();
1983     }
1984
1985     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1986     return result;
1987 }
1988
1989 static CAResult_t CAReadLEData()
1990 {
1991     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1992 #ifdef SINGLE_THREAD
1993     CACheckLEData();
1994 #endif
1995     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1996     return CA_STATUS_OK;
1997 }
1998
1999 static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
2000                                    const void *data,
2001                                    uint32_t dataLen)
2002 {
2003     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CASendLEUnicastData");
2004
2005     //Input validation
2006     VERIFY_NON_NULL_RET(endpoint, CALEADAPTER_TAG, "Remote endpoint is null", -1);
2007     VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
2008
2009     CAResult_t result = CA_STATUS_FAILED;
2010
2011     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "g_adapterType: %d", g_adapterType);
2012     if (ADAPTER_EMPTY == g_adapterType)
2013     {
2014         OIC_LOG(ERROR, CALEADAPTER_TAG, "g_adapterType is Empty");
2015     }
2016
2017     ca_mutex_lock(g_bleIsServerMutex);
2018     if (ADAPTER_SERVER == g_adapterType || ADAPTER_BOTH_CLIENT_SERVER == g_adapterType)
2019     {
2020         result = CALEAdapterServerSendData(endpoint, data, dataLen);
2021         if (CA_STATUS_OK != result)
2022         {
2023             ca_mutex_unlock(g_bleIsServerMutex);
2024             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for server failed");
2025             if (g_errorHandler)
2026             {
2027                 g_errorHandler(endpoint, data, dataLen, result);
2028             }
2029
2030             return -1;
2031         }
2032     }
2033
2034     if (ADAPTER_CLIENT == g_adapterType || ADAPTER_BOTH_CLIENT_SERVER == g_adapterType)
2035     {
2036         result = CALEAdapterClientSendData(endpoint, data, dataLen);
2037         if (CA_STATUS_OK != result)
2038         {
2039             ca_mutex_unlock(g_bleIsServerMutex);
2040             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for client failed" );
2041
2042              if (g_errorHandler)
2043              {
2044                  g_errorHandler(endpoint, data, dataLen, result);
2045              }
2046             return -1;
2047         }
2048     }
2049     ca_mutex_unlock(g_bleIsServerMutex);
2050
2051     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2052     return dataLen;
2053 }
2054
2055 static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
2056                                      const void *data,
2057                                      uint32_t dataLen)
2058 {
2059     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CASendLEMulticastData");
2060
2061     //Input validation
2062     VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
2063
2064     if (0 >= dataLen)
2065     {
2066         OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid Parameter");
2067         return -1;
2068     }
2069
2070     CAResult_t result = CA_STATUS_FAILED;
2071
2072     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "g_adapterType: %d", g_adapterType);
2073     if (ADAPTER_EMPTY == g_adapterType)
2074     {
2075         OIC_LOG(ERROR, CALEADAPTER_TAG, "g_adapterType is Empty");
2076     }
2077
2078     ca_mutex_lock(g_bleIsServerMutex);
2079     if (ADAPTER_SERVER == g_adapterType || ADAPTER_BOTH_CLIENT_SERVER == g_adapterType)
2080     {
2081         result = CALEAdapterServerSendData(NULL, data, dataLen);
2082         if (CA_STATUS_OK != result)
2083         {
2084             ca_mutex_unlock(g_bleIsServerMutex);
2085
2086             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send multicast data for server failed" );
2087
2088             if (g_errorHandler)
2089             {
2090                 g_errorHandler(endpoint, data, dataLen, result);
2091             }
2092             return -1;
2093         }
2094     }
2095
2096     if (ADAPTER_CLIENT == g_adapterType || ADAPTER_BOTH_CLIENT_SERVER == g_adapterType)
2097     {
2098         result = CALEAdapterClientSendData(NULL, data, dataLen);
2099         if (CA_STATUS_OK != result)
2100         {
2101             ca_mutex_unlock(g_bleIsServerMutex);
2102
2103             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send Multicast data for client failed" );
2104
2105             if (g_errorHandler)
2106             {
2107                 g_errorHandler(endpoint, data, dataLen, result);
2108             }
2109             return -1;
2110         }
2111     }
2112     ca_mutex_unlock(g_bleIsServerMutex);
2113
2114     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CASendLEMulticastData");
2115     return dataLen;
2116 }
2117
2118 static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
2119 {
2120     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2121
2122     VERIFY_NON_NULL(info, CALEADAPTER_TAG, "CALocalConnectivity info is null");
2123
2124     char *local_address = NULL;
2125
2126     CAResult_t res = CAGetLEAddress(&local_address);
2127     if (CA_STATUS_OK != res)
2128     {
2129         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAGetLEAddress has failed");
2130         return res;
2131     }
2132
2133     if (NULL == local_address)
2134     {
2135         OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is NULL");
2136         return CA_STATUS_FAILED;
2137     }
2138
2139     *size = 0;
2140     (*info) = (CAEndpoint_t *) OICCalloc(1, sizeof(CAEndpoint_t));
2141     if (NULL == (*info))
2142     {
2143         OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failure!");
2144         OICFree(local_address);
2145         return CA_STATUS_FAILED;
2146     }
2147
2148     size_t local_address_len = strlen(local_address);
2149
2150     if(local_address_len >= sizeof(g_localBLEAddress) ||
2151             local_address_len >= MAX_ADDR_STR_SIZE_CA - 1)
2152     {
2153         OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is too long");
2154         OICFree(*info);
2155         OICFree(local_address);
2156         return CA_STATUS_FAILED;
2157     }
2158
2159     OICStrcpy((*info)->addr, sizeof((*info)->addr), local_address);
2160     ca_mutex_lock(g_bleLocalAddressMutex);
2161     OICStrcpy(g_localBLEAddress, sizeof(g_localBLEAddress), local_address);
2162     ca_mutex_unlock(g_bleLocalAddressMutex);
2163
2164     (*info)->adapter = CA_ADAPTER_GATT_BTLE;
2165     *size = 1;
2166     OICFree(local_address);
2167
2168     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2169     return CA_STATUS_OK;
2170 }
2171
2172 static CAResult_t CALERegisterNetworkNotifications(CAAdapterChangeCallback netCallback,
2173                                                    CAConnectionChangeCallback connCallback)
2174 {
2175     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2176
2177     ca_mutex_lock(g_bleNetworkCbMutex);
2178     g_networkCallback = netCallback;
2179     g_connectionCallback = connCallback;
2180     ca_mutex_unlock(g_bleNetworkCbMutex);
2181     CAResult_t res = CA_STATUS_OK;
2182     if (netCallback)
2183     {
2184         res = CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCb);
2185         if (CA_STATUS_OK != res)
2186         {
2187             OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
2188         }
2189     }
2190     else
2191     {
2192         res = CAUnSetLEAdapterStateChangedCb();
2193         if (CA_STATUS_OK != res)
2194         {
2195             OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
2196         }
2197     }
2198
2199     if (g_connectionCallback)
2200     {
2201         res = CASetLENWConnectionStateChangedCb(CALEConnectionStateChangedCb);
2202         if (CA_STATUS_OK != res)
2203         {
2204             OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLENWConnectionStateChangedCb failed!");
2205         }
2206     }
2207
2208     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2209     return res;
2210 }
2211
2212 static void CALEConnectionStateChangedCb(CATransportAdapter_t adapter, const char* address,
2213                                          bool isConnected)
2214 {
2215     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CALEConnectionStateChangedCb");
2216
2217     VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
2218     (void)adapter;
2219
2220 #ifdef __TIZEN__
2221     ca_mutex_lock(g_bleIsServerMutex);
2222     switch (g_adapterType)
2223     {
2224         case ADAPTER_SERVER:
2225             CALEGattServerConnectionStateChanged(isConnected, address);
2226             break;
2227         case ADAPTER_CLIENT:
2228             CALEGattConnectionStateChanged(isConnected, address);
2229             break;
2230         case ADAPTER_BOTH_CLIENT_SERVER:
2231             CALEGattConnectionStateChanged(isConnected, address);
2232             CALEGattServerConnectionStateChanged(isConnected, address);
2233             break;
2234         default:
2235             break;
2236     }
2237     ca_mutex_unlock(g_bleIsServerMutex);
2238 #endif
2239
2240     if(!isConnected)
2241     {
2242 #ifndef SINGLE_THREAD
2243         if(g_bleClientSenderInfo)
2244         {
2245             CALERemoveReceiveQueueData(g_bleClientSenderInfo, address);
2246         }
2247
2248         if(g_bleServerSenderInfo)
2249         {
2250             CALERemoveReceiveQueueData(g_bleServerSenderInfo, address);
2251         }
2252
2253         // remove data of send queue.
2254         if (g_bleClientSendQueueHandle)
2255         {
2256             CALERemoveSendQueueData(g_bleClientSendQueueHandle,
2257                                     g_bleClientSendDataMutex,
2258                                     address);
2259         }
2260
2261         if (g_bleServerSendQueueHandle)
2262         {
2263             CALERemoveSendQueueData(g_bleServerSendQueueHandle,
2264                                     g_bleServerSendDataMutex,
2265                                     address);
2266         }
2267 #endif
2268     }
2269
2270     CAEndpoint_t localEndpoint = { .adapter = CA_ADAPTER_GATT_BTLE };
2271     OICStrcpy(localEndpoint.addr, sizeof(localEndpoint.addr), address);
2272
2273     ca_mutex_lock(g_bleNetworkCbMutex);
2274     if (g_connectionCallback)
2275     {
2276         g_connectionCallback(&localEndpoint, isConnected);
2277     }
2278     ca_mutex_unlock(g_bleNetworkCbMutex);
2279
2280     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2281 }
2282
2283 static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state)
2284 {
2285     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CALEDeviceStateChangedCb");
2286
2287     if (CA_ADAPTER_ENABLED == adapter_state)
2288     {
2289         ca_mutex_lock(g_bleIsServerMutex);
2290         switch (g_adapterType)
2291         {
2292             case ADAPTER_SERVER:
2293                 CALEAdapterGattServerStart();
2294                 break;
2295             case ADAPTER_CLIENT:
2296                 CALEAdapterGattClientStart();
2297                 break;
2298             case ADAPTER_BOTH_CLIENT_SERVER:
2299                 CALEAdapterGattServerStart();
2300                 CALEAdapterGattClientStart();
2301                 break;
2302             default:
2303                 break;
2304         }
2305         ca_mutex_unlock(g_bleIsServerMutex);
2306     }
2307     else
2308     {
2309         ca_mutex_lock(g_bleIsServerMutex);
2310         switch (g_adapterType)
2311         {
2312             case ADAPTER_SERVER:
2313                 CALEAdapterGattServerStop();
2314                 break;
2315             case ADAPTER_CLIENT:
2316                 CALEAdapterGattClientStop();
2317                 break;
2318             case ADAPTER_BOTH_CLIENT_SERVER:
2319                 CALEAdapterGattServerStop();
2320                 CALEAdapterGattClientStop();
2321                 break;
2322             default:
2323                 break;
2324         }
2325         ca_mutex_unlock(g_bleIsServerMutex);
2326     }
2327
2328     ca_mutex_lock(g_bleNetworkCbMutex);
2329     if (NULL != g_networkCallback)
2330     {
2331         g_networkCallback(CA_ADAPTER_GATT_BTLE, adapter_state);
2332     }
2333     else
2334     {
2335         OIC_LOG(ERROR, CALEADAPTER_TAG, "g_networkCallback is NULL");
2336     }
2337     ca_mutex_unlock(g_bleNetworkCbMutex);
2338
2339     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2340 }
2341
2342 static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
2343                                             const uint8_t *data,
2344                                             uint32_t dataLen)
2345 {
2346     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2347
2348     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
2349 #ifndef SINGLE_THREAD
2350     VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG,
2351                         "g_bleClientSendQueueHandle is  NULL",
2352                         CA_STATUS_FAILED);
2353     VERIFY_NON_NULL_RET(g_bleClientSendDataMutex, CALEADAPTER_TAG,
2354                         "g_bleClientSendDataMutex is NULL",
2355                         CA_STATUS_FAILED);
2356
2357     VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG,
2358                         "g_bleClientSendQueueHandle",
2359                         CA_STATUS_FAILED);
2360
2361     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%u]", dataLen);
2362
2363     CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLen, NULL);
2364     if (!bleData)
2365     {
2366         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
2367         return CA_MEMORY_ALLOC_FAILED;
2368     }
2369     // Add message to send queue
2370     ca_mutex_lock(g_bleClientSendDataMutex);
2371     CAQueueingThreadAddData(g_bleClientSendQueueHandle, bleData, sizeof(CALEData_t));
2372     ca_mutex_unlock(g_bleClientSendDataMutex);
2373 #endif
2374     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2375     return CA_STATUS_OK;
2376 }
2377
2378 static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
2379                                             const uint8_t *data,
2380                                             uint32_t dataLen)
2381 {
2382     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2383
2384     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
2385
2386 #ifdef SINGLE_THREAD
2387     if (!CAIsLEConnected())
2388     {
2389         OIC_LOG(ERROR, CALEADAPTER_TAG, "le not conn");
2390         return CA_STATUS_FAILED;
2391     }
2392
2393     CAResult_t result = CA_STATUS_OK;
2394     const uint32_t dataLimit = dataLen / CA_SUPPORTED_BLE_MTU_SIZE;
2395     for (uint32_t iter = 0; iter < dataLimit; iter++)
2396     {
2397         result =
2398             CAUpdateCharacteristicsToAllGattClients(
2399                 data + (iter * CA_SUPPORTED_BLE_MTU_SIZE),
2400                 CA_SUPPORTED_BLE_MTU_SIZE);
2401
2402         if (CA_STATUS_OK != result)
2403         {
2404             OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2405             return CA_STATUS_FAILED;
2406         }
2407
2408         CALEDoEvents();
2409     }
2410
2411     const uint32_t remainingLen = dataLen % CA_SUPPORTED_BLE_MTU_SIZE;
2412     if (remainingLen)
2413     {
2414         result =
2415             CAUpdateCharacteristicsToAllGattClients(
2416                 data + (dataLimit * CA_SUPPORTED_BLE_MTU_SIZE),
2417                 remainingLen);
2418         if (CA_STATUS_OK != result)
2419         {
2420             OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2421             return CA_STATUS_FAILED;
2422         }
2423         CALEDoEvents();
2424     }
2425 #else
2426     VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG,
2427                         "BleClientReceiverQueue is NULL",
2428                         CA_STATUS_FAILED);
2429     VERIFY_NON_NULL_RET(g_bleServerSendDataMutex, CALEADAPTER_TAG,
2430                         "BleClientSendDataMutex is NULL",
2431                         CA_STATUS_FAILED);
2432
2433     VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG, "sendQueueHandle",
2434                         CA_STATUS_FAILED);
2435
2436     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%d]", dataLen);
2437
2438     CALEData_t * const bleData =
2439         CACreateLEData(remoteEndpoint, data, dataLen, NULL);
2440
2441     if (!bleData)
2442     {
2443         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
2444         return CA_MEMORY_ALLOC_FAILED;
2445     }
2446
2447     // Add message to send queue
2448     ca_mutex_lock(g_bleServerSendDataMutex);
2449     CAQueueingThreadAddData(g_bleServerSendQueueHandle,
2450                             bleData,
2451                             sizeof(CALEData_t));
2452     ca_mutex_unlock(g_bleServerSendDataMutex);
2453 #endif
2454     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2455     return CA_STATUS_OK;
2456 }
2457
2458 static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
2459                                                 const uint8_t *data,
2460                                                 uint32_t dataLength,
2461                                                 uint32_t *sentLength)
2462 {
2463     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2464
2465     //Input validation
2466     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
2467     VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
2468
2469 #ifdef SINGLE_THREAD
2470     if(g_networkPacketReceivedCallback)
2471     {
2472         // will be filled by upper layer
2473         const CASecureEndpoint_t endpoint =
2474             { .endpoint = { .adapter = CA_ADAPTER_GATT_BTLE } };
2475
2476
2477         g_networkPacketReceivedCallback(&endpoint, data, dataLength);
2478     }
2479 #else
2480     VERIFY_NON_NULL_RET(g_bleReceiverQueue,
2481                         CALEADAPTER_TAG,
2482                         "g_bleReceiverQueue",
2483                         CA_STATUS_FAILED);
2484
2485     //Add message to data queue
2486     CAEndpoint_t * const remoteEndpoint =
2487         CACreateEndpointObject(CA_DEFAULT_FLAGS,
2488                                CA_ADAPTER_GATT_BTLE,
2489                                remoteAddress,
2490                                0);
2491
2492     if (NULL == remoteEndpoint)
2493     {
2494         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
2495         return CA_STATUS_FAILED;
2496     }
2497
2498     // Create bleData to add to queue
2499     OIC_LOG_V(DEBUG,
2500               CALEADAPTER_TAG,
2501               "Data received from LE layer [%d]",
2502               dataLength);
2503
2504     CALEData_t * const bleData =
2505         CACreateLEData(remoteEndpoint, data, dataLength, g_bleServerSenderInfo);
2506
2507     if (!bleData)
2508     {
2509         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
2510         CAFreeEndpoint(remoteEndpoint);
2511         return CA_MEMORY_ALLOC_FAILED;
2512     }
2513
2514     CAFreeEndpoint(remoteEndpoint);
2515     // Add message to receiver queue
2516     CAQueueingThreadAddData(g_bleReceiverQueue, bleData, sizeof(CALEData_t));
2517
2518     *sentLength = dataLength;
2519 #endif
2520     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2521     return CA_STATUS_OK;
2522 }
2523
2524 static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
2525                                                 const uint8_t *data,
2526                                                 uint32_t dataLength,
2527                                                 uint32_t *sentLength)
2528 {
2529     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2530
2531     //Input validation
2532     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
2533     VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
2534 #ifndef SINGLE_THREAD
2535     VERIFY_NON_NULL_RET(g_bleReceiverQueue, CALEADAPTER_TAG,
2536                         "g_bleReceiverQueue",
2537                         CA_STATUS_FAILED);
2538
2539     //Add message to data queue
2540     CAEndpoint_t *remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
2541                                                           CA_ADAPTER_GATT_BTLE,
2542                                                           remoteAddress, 0);
2543     if (NULL == remoteEndpoint)
2544     {
2545         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
2546         return CA_STATUS_FAILED;
2547     }
2548
2549     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data received from LE layer [%u]", dataLength);
2550
2551     // Create bleData to add to queue
2552     CALEData_t *bleData = CACreateLEData(remoteEndpoint, data,
2553                                          dataLength, g_bleClientSenderInfo);
2554     if (!bleData)
2555     {
2556         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
2557         CAFreeEndpoint(remoteEndpoint);
2558         return CA_MEMORY_ALLOC_FAILED;
2559     }
2560
2561     CAFreeEndpoint(remoteEndpoint);
2562     // Add message to receiver queue
2563     CAQueueingThreadAddData(g_bleReceiverQueue, bleData, sizeof(CALEData_t));
2564
2565     *sentLength = dataLength;
2566 #endif
2567     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2568     return CA_STATUS_OK;
2569 }
2570
2571 static void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle)
2572 {
2573     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2574
2575     ca_mutex_lock(g_bleAdapterThreadPoolMutex);
2576     g_bleAdapterThreadPool = handle;
2577     ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
2578
2579     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2580 }
2581
2582 static void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback)
2583 {
2584     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2585
2586     ca_mutex_lock(g_bleAdapterReqRespCbMutex);
2587
2588     g_networkPacketReceivedCallback = callback;
2589
2590     ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
2591
2592     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2593 }
2594
2595 static void CALEErrorHandler(const char *remoteAddress,
2596                              const uint8_t *data,
2597                              uint32_t dataLen,
2598                              CAResult_t result)
2599 {
2600     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEErrorHandler IN");
2601
2602     VERIFY_NON_NULL_VOID(data, CALEADAPTER_TAG, "Data is null");
2603
2604     CAEndpoint_t *rep = CACreateEndpointObject(CA_DEFAULT_FLAGS,
2605                                                CA_ADAPTER_GATT_BTLE,
2606                                                remoteAddress,
2607                                                0);
2608
2609     // if required, will be used to build remote endpoint
2610     g_errorHandler(rep, data, dataLen, result);
2611
2612     CAFreeEndpoint(rep);
2613
2614     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEErrorHandler OUT");
2615 }
2616
2617 #ifndef SINGLE_THREAD
2618 static void CALERemoveSendQueueData(CAQueueingThread_t *queueHandle, ca_mutex mutex,
2619                                     const char* address)
2620 {
2621     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALERemoveSendQueueData");
2622
2623     VERIFY_NON_NULL_VOID(queueHandle, CALEADAPTER_TAG, "queueHandle");
2624     VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
2625
2626     ca_mutex_lock(mutex);
2627     while (u_queue_get_size(queueHandle->dataQueue) > 0)
2628     {
2629         OIC_LOG(DEBUG, CALEADAPTER_TAG, "get data from queue");
2630         u_queue_message_t *message = u_queue_get_element(queueHandle->dataQueue);
2631         if (NULL != message)
2632         {
2633             CALEData_t *bleData = (CALEData_t *) message->msg;
2634             if (bleData && bleData->remoteEndpoint)
2635             {
2636                 if (!strcmp(bleData->remoteEndpoint->addr, address))
2637                 {
2638                     OIC_LOG(DEBUG, CALEADAPTER_TAG, "found the message of disconnected device");
2639                     if (NULL != queueHandle->destroy)
2640                     {
2641                         queueHandle->destroy(message->msg, message->size);
2642                     }
2643                     else
2644                     {
2645                         OICFree(message->msg);
2646                     }
2647
2648                     OICFree(message);
2649                 }
2650             }
2651         }
2652     }
2653     ca_mutex_unlock(mutex);
2654 }
2655
2656 static void CALERemoveReceiveQueueData(u_arraylist_t *dataInfoList, const char* address)
2657 {
2658     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALERemoveSendQueueData");
2659
2660     VERIFY_NON_NULL_VOID(dataInfoList, CALEADAPTER_TAG, "dataInfoList");
2661     VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
2662
2663     CABLESenderInfo_t *senderInfo = NULL;
2664     uint32_t senderIndex = 0;
2665
2666     if(CA_STATUS_OK == CALEGetSenderInfo(address, dataInfoList, &senderInfo,
2667                                          &senderIndex))
2668     {
2669         u_arraylist_remove(dataInfoList, senderIndex);
2670         OICFree(senderInfo->defragData);
2671         OICFree(senderInfo->remoteEndpoint);
2672         OICFree(senderInfo);
2673
2674         OIC_LOG(DEBUG, CALEADAPTER_TAG, "SenderInfo is removed for disconnection");
2675     }
2676     else
2677     {
2678         OIC_LOG(DEBUG, CALEADAPTER_TAG, "SenderInfo doesn't exist");
2679     }
2680 }
2681 #endif