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