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