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