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