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