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