Fix in LE adapter to return CA_STATUS_OK when BT is not enabled
[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             result = CA_STATUS_OK;
1917         }
1918     }
1919     else
1920     {
1921         result = CALEAdapterGattServerStart();
1922     }
1923
1924     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1925     return result;
1926 #else
1927     // Routing Gateway only supports BLE client mode.
1928     OIC_LOG(ERROR, CALEADAPTER_TAG, "LE server not supported in Routing Gateway");
1929     return CA_NOT_SUPPORTED;
1930 #endif
1931 }
1932
1933 static CAResult_t CAStopLEListeningServer()
1934 {
1935     OIC_LOG(ERROR, CALEADAPTER_TAG, "Listen server stop not supported.");
1936     return CA_NOT_SUPPORTED;
1937 }
1938
1939 static CAResult_t CAStartLEDiscoveryServer()
1940 {
1941     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CAStartLEDiscoveryServer");
1942     CAResult_t result = CA_STATUS_OK;
1943 #ifndef SINGLE_THREAD
1944     result = CAInitLEClientQueues();
1945     if (CA_STATUS_OK != result)
1946     {
1947         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEClientQueues failed");
1948         return result;
1949     }
1950 #endif
1951
1952     ca_mutex_lock(g_bleIsServerMutex);
1953     switch (g_adapterType)
1954     {
1955         case ADAPTER_SERVER:
1956             g_adapterType = ADAPTER_BOTH_CLIENT_SERVER;
1957             break;
1958         case ADAPTER_BOTH_CLIENT_SERVER:
1959             break;
1960         default:
1961             g_adapterType = ADAPTER_CLIENT;
1962     }
1963     ca_mutex_unlock(g_bleIsServerMutex);
1964
1965     result = CAGetLEAdapterState();
1966     if (CA_STATUS_OK != result)
1967     {
1968         if (CA_ADAPTER_NOT_ENABLED == result)
1969         {
1970             OIC_LOG(DEBUG,
1971                     CALEADAPTER_TAG,
1972                     "Discovery Server will be started once BT Adapter is enabled");
1973             result = CA_STATUS_OK;
1974         }
1975     }
1976     else
1977     {
1978         result = CALEAdapterGattClientStart();
1979     }
1980
1981     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1982     return result;
1983 }
1984
1985 static CAResult_t CAReadLEData()
1986 {
1987     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1988 #ifdef SINGLE_THREAD
1989     CACheckLEData();
1990 #endif
1991     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1992     return CA_STATUS_OK;
1993 }
1994
1995 static int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint,
1996                                    const void *data,
1997                                    uint32_t dataLen)
1998 {
1999     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CASendLEUnicastData");
2000
2001     //Input validation
2002     VERIFY_NON_NULL_RET(endpoint, CALEADAPTER_TAG, "Remote endpoint is null", -1);
2003     VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
2004
2005     CAResult_t result = CA_STATUS_FAILED;
2006
2007     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "g_adapterType: %d", g_adapterType);
2008     if (ADAPTER_EMPTY == g_adapterType)
2009     {
2010         OIC_LOG(ERROR, CALEADAPTER_TAG, "g_adapterType is Empty");
2011     }
2012
2013     ca_mutex_lock(g_bleIsServerMutex);
2014     if (ADAPTER_SERVER == g_adapterType || ADAPTER_BOTH_CLIENT_SERVER == g_adapterType)
2015     {
2016         result = CALEAdapterServerSendData(endpoint, data, dataLen);
2017         if (CA_STATUS_OK != result)
2018         {
2019             ca_mutex_unlock(g_bleIsServerMutex);
2020             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for server failed");
2021             if (g_errorHandler)
2022             {
2023                 g_errorHandler(endpoint, data, dataLen, result);
2024             }
2025
2026             return -1;
2027         }
2028     }
2029
2030     if (ADAPTER_CLIENT == g_adapterType || ADAPTER_BOTH_CLIENT_SERVER == g_adapterType)
2031     {
2032         result = CALEAdapterClientSendData(endpoint, data, dataLen);
2033         if (CA_STATUS_OK != result)
2034         {
2035             ca_mutex_unlock(g_bleIsServerMutex);
2036             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data for client failed" );
2037
2038              if (g_errorHandler)
2039              {
2040                  g_errorHandler(endpoint, data, dataLen, result);
2041              }
2042             return -1;
2043         }
2044     }
2045     ca_mutex_unlock(g_bleIsServerMutex);
2046
2047     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2048     return dataLen;
2049 }
2050
2051 static int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint,
2052                                      const void *data,
2053                                      uint32_t dataLen)
2054 {
2055     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CASendLEMulticastData");
2056
2057     //Input validation
2058     VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
2059
2060     if (0 >= dataLen)
2061     {
2062         OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid Parameter");
2063         return -1;
2064     }
2065
2066     CAResult_t result = CA_STATUS_FAILED;
2067
2068     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "g_adapterType: %d", g_adapterType);
2069     if (ADAPTER_EMPTY == g_adapterType)
2070     {
2071         OIC_LOG(ERROR, CALEADAPTER_TAG, "g_adapterType is Empty");
2072     }
2073
2074     ca_mutex_lock(g_bleIsServerMutex);
2075     if (ADAPTER_SERVER == g_adapterType || ADAPTER_BOTH_CLIENT_SERVER == g_adapterType)
2076     {
2077         result = CALEAdapterServerSendData(NULL, data, dataLen);
2078         if (CA_STATUS_OK != result)
2079         {
2080             ca_mutex_unlock(g_bleIsServerMutex);
2081
2082             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send multicast data for server failed" );
2083
2084             if (g_errorHandler)
2085             {
2086                 g_errorHandler(endpoint, data, dataLen, result);
2087             }
2088             return -1;
2089         }
2090     }
2091
2092     if (ADAPTER_CLIENT == g_adapterType || ADAPTER_BOTH_CLIENT_SERVER == g_adapterType)
2093     {
2094         result = CALEAdapterClientSendData(NULL, data, dataLen);
2095         if (CA_STATUS_OK != result)
2096         {
2097             ca_mutex_unlock(g_bleIsServerMutex);
2098
2099             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send Multicast data for client failed" );
2100
2101             if (g_errorHandler)
2102             {
2103                 g_errorHandler(endpoint, data, dataLen, result);
2104             }
2105             return -1;
2106         }
2107     }
2108     ca_mutex_unlock(g_bleIsServerMutex);
2109
2110     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CASendLEMulticastData");
2111     return dataLen;
2112 }
2113
2114 static CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
2115 {
2116     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2117
2118     VERIFY_NON_NULL(info, CALEADAPTER_TAG, "CALocalConnectivity info is null");
2119
2120     char *local_address = NULL;
2121
2122     CAResult_t res = CAGetLEAddress(&local_address);
2123     if (CA_STATUS_OK != res)
2124     {
2125         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAGetLEAddress has failed");
2126         return res;
2127     }
2128
2129     if (NULL == local_address)
2130     {
2131         OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is NULL");
2132         return CA_STATUS_FAILED;
2133     }
2134
2135     *size = 0;
2136     (*info) = (CAEndpoint_t *) OICCalloc(1, sizeof(CAEndpoint_t));
2137     if (NULL == (*info))
2138     {
2139         OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failure!");
2140         OICFree(local_address);
2141         return CA_STATUS_FAILED;
2142     }
2143
2144     size_t local_address_len = strlen(local_address);
2145
2146     if(local_address_len >= sizeof(g_localBLEAddress) ||
2147             local_address_len >= MAX_ADDR_STR_SIZE_CA - 1)
2148     {
2149         OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is too long");
2150         OICFree(*info);
2151         OICFree(local_address);
2152         return CA_STATUS_FAILED;
2153     }
2154
2155     OICStrcpy((*info)->addr, sizeof((*info)->addr), local_address);
2156     ca_mutex_lock(g_bleLocalAddressMutex);
2157     OICStrcpy(g_localBLEAddress, sizeof(g_localBLEAddress), local_address);
2158     ca_mutex_unlock(g_bleLocalAddressMutex);
2159
2160     (*info)->adapter = CA_ADAPTER_GATT_BTLE;
2161     *size = 1;
2162     OICFree(local_address);
2163
2164     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2165     return CA_STATUS_OK;
2166 }
2167
2168 static CAResult_t CALERegisterNetworkNotifications(CAAdapterChangeCallback netCallback,
2169                                                    CAConnectionChangeCallback connCallback)
2170 {
2171     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2172
2173     ca_mutex_lock(g_bleNetworkCbMutex);
2174     g_networkCallback = netCallback;
2175     g_connectionCallback = connCallback;
2176     ca_mutex_unlock(g_bleNetworkCbMutex);
2177     CAResult_t res = CA_STATUS_OK;
2178     if (netCallback)
2179     {
2180         res = CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCb);
2181         if (CA_STATUS_OK != res)
2182         {
2183             OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
2184         }
2185     }
2186     else
2187     {
2188         res = CAUnSetLEAdapterStateChangedCb();
2189         if (CA_STATUS_OK != res)
2190         {
2191             OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
2192         }
2193     }
2194
2195     if (g_connectionCallback)
2196     {
2197         res = CASetLENWConnectionStateChangedCb(CALEConnectionStateChangedCb);
2198         if (CA_STATUS_OK != res)
2199         {
2200             OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLENWConnectionStateChangedCb failed!");
2201         }
2202     }
2203
2204     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2205     return res;
2206 }
2207
2208 static void CALEConnectionStateChangedCb(CATransportAdapter_t adapter, const char* address,
2209                                          bool isConnected)
2210 {
2211     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CALEConnectionStateChangedCb");
2212
2213     VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
2214     (void)adapter;
2215
2216 #ifdef __TIZEN__
2217     ca_mutex_lock(g_bleIsServerMutex);
2218     switch (g_adapterType)
2219     {
2220         case ADAPTER_SERVER:
2221             CALEGattServerConnectionStateChanged(isConnected, address);
2222             break;
2223         case ADAPTER_CLIENT:
2224             CALEGattConnectionStateChanged(isConnected, address);
2225             break;
2226         case ADAPTER_BOTH_CLIENT_SERVER:
2227             CALEGattConnectionStateChanged(isConnected, address);
2228             CALEGattServerConnectionStateChanged(isConnected, address);
2229             break;
2230         default:
2231             break;
2232     }
2233     ca_mutex_unlock(g_bleIsServerMutex);
2234 #endif
2235
2236     if(!isConnected)
2237     {
2238 #ifndef SINGLE_THREAD
2239         if(g_bleClientSenderInfo)
2240         {
2241             CALERemoveReceiveQueueData(g_bleClientSenderInfo, address);
2242         }
2243
2244         if(g_bleServerSenderInfo)
2245         {
2246             CALERemoveReceiveQueueData(g_bleServerSenderInfo, address);
2247         }
2248
2249         // remove data of send queue.
2250         if (g_bleClientSendQueueHandle)
2251         {
2252             CALERemoveSendQueueData(g_bleClientSendQueueHandle,
2253                                     g_bleClientSendDataMutex,
2254                                     address);
2255         }
2256
2257         if (g_bleServerSendQueueHandle)
2258         {
2259             CALERemoveSendQueueData(g_bleServerSendQueueHandle,
2260                                     g_bleServerSendDataMutex,
2261                                     address);
2262         }
2263 #endif
2264     }
2265
2266     CAEndpoint_t localEndpoint = { .adapter = CA_ADAPTER_GATT_BTLE };
2267     OICStrcpy(localEndpoint.addr, sizeof(localEndpoint.addr), address);
2268
2269     ca_mutex_lock(g_bleNetworkCbMutex);
2270     if (g_connectionCallback)
2271     {
2272         g_connectionCallback(&localEndpoint, isConnected);
2273     }
2274     ca_mutex_unlock(g_bleNetworkCbMutex);
2275
2276     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2277 }
2278
2279 static void CALEDeviceStateChangedCb(CAAdapterState_t adapter_state)
2280 {
2281     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN - CALEDeviceStateChangedCb");
2282
2283     if (CA_ADAPTER_ENABLED == adapter_state)
2284     {
2285         ca_mutex_lock(g_bleIsServerMutex);
2286         switch (g_adapterType)
2287         {
2288             case ADAPTER_SERVER:
2289                 CALEAdapterGattServerStart();
2290                 break;
2291             case ADAPTER_CLIENT:
2292                 CALEAdapterGattClientStart();
2293                 break;
2294             case ADAPTER_BOTH_CLIENT_SERVER:
2295                 CALEAdapterGattServerStart();
2296                 CALEAdapterGattClientStart();
2297                 break;
2298             default:
2299                 break;
2300         }
2301         ca_mutex_unlock(g_bleIsServerMutex);
2302     }
2303     else
2304     {
2305         ca_mutex_lock(g_bleIsServerMutex);
2306         switch (g_adapterType)
2307         {
2308             case ADAPTER_SERVER:
2309                 CALEAdapterGattServerStop();
2310                 break;
2311             case ADAPTER_CLIENT:
2312                 CALEAdapterGattClientStop();
2313                 break;
2314             case ADAPTER_BOTH_CLIENT_SERVER:
2315                 CALEAdapterGattServerStop();
2316                 CALEAdapterGattClientStop();
2317                 break;
2318             default:
2319                 break;
2320         }
2321         ca_mutex_unlock(g_bleIsServerMutex);
2322     }
2323
2324     ca_mutex_lock(g_bleNetworkCbMutex);
2325     if (NULL != g_networkCallback)
2326     {
2327         g_networkCallback(CA_ADAPTER_GATT_BTLE, adapter_state);
2328     }
2329     else
2330     {
2331         OIC_LOG(ERROR, CALEADAPTER_TAG, "g_networkCallback is NULL");
2332     }
2333     ca_mutex_unlock(g_bleNetworkCbMutex);
2334
2335     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2336 }
2337
2338 static CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
2339                                             const uint8_t *data,
2340                                             uint32_t dataLen)
2341 {
2342     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2343
2344     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
2345 #ifndef SINGLE_THREAD
2346     VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG,
2347                         "g_bleClientSendQueueHandle is  NULL",
2348                         CA_STATUS_FAILED);
2349     VERIFY_NON_NULL_RET(g_bleClientSendDataMutex, CALEADAPTER_TAG,
2350                         "g_bleClientSendDataMutex is NULL",
2351                         CA_STATUS_FAILED);
2352
2353     VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG,
2354                         "g_bleClientSendQueueHandle",
2355                         CA_STATUS_FAILED);
2356
2357     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%u]", dataLen);
2358
2359     CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLen, NULL);
2360     if (!bleData)
2361     {
2362         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
2363         return CA_MEMORY_ALLOC_FAILED;
2364     }
2365     // Add message to send queue
2366     ca_mutex_lock(g_bleClientSendDataMutex);
2367     CAQueueingThreadAddData(g_bleClientSendQueueHandle, bleData, sizeof(CALEData_t));
2368     ca_mutex_unlock(g_bleClientSendDataMutex);
2369 #endif
2370     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2371     return CA_STATUS_OK;
2372 }
2373
2374 static CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
2375                                             const uint8_t *data,
2376                                             uint32_t dataLen)
2377 {
2378     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2379
2380     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
2381
2382 #ifdef SINGLE_THREAD
2383     if (!CAIsLEConnected())
2384     {
2385         OIC_LOG(ERROR, CALEADAPTER_TAG, "le not conn");
2386         return CA_STATUS_FAILED;
2387     }
2388
2389     CAResult_t result = CA_STATUS_OK;
2390     const uint32_t dataLimit = dataLen / CA_SUPPORTED_BLE_MTU_SIZE;
2391     for (uint32_t iter = 0; iter < dataLimit; iter++)
2392     {
2393         result =
2394             CAUpdateCharacteristicsToAllGattClients(
2395                 data + (iter * CA_SUPPORTED_BLE_MTU_SIZE),
2396                 CA_SUPPORTED_BLE_MTU_SIZE);
2397
2398         if (CA_STATUS_OK != result)
2399         {
2400             OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2401             return CA_STATUS_FAILED;
2402         }
2403
2404         CALEDoEvents();
2405     }
2406
2407     const uint32_t remainingLen = dataLen % CA_SUPPORTED_BLE_MTU_SIZE;
2408     if (remainingLen)
2409     {
2410         result =
2411             CAUpdateCharacteristicsToAllGattClients(
2412                 data + (dataLimit * CA_SUPPORTED_BLE_MTU_SIZE),
2413                 remainingLen);
2414         if (CA_STATUS_OK != result)
2415         {
2416             OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
2417             return CA_STATUS_FAILED;
2418         }
2419         CALEDoEvents();
2420     }
2421 #else
2422     VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG,
2423                         "BleClientReceiverQueue is NULL",
2424                         CA_STATUS_FAILED);
2425     VERIFY_NON_NULL_RET(g_bleServerSendDataMutex, CALEADAPTER_TAG,
2426                         "BleClientSendDataMutex is NULL",
2427                         CA_STATUS_FAILED);
2428
2429     VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG, "sendQueueHandle",
2430                         CA_STATUS_FAILED);
2431
2432     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%d]", dataLen);
2433
2434     CALEData_t * const bleData =
2435         CACreateLEData(remoteEndpoint, data, dataLen, NULL);
2436
2437     if (!bleData)
2438     {
2439         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
2440         return CA_MEMORY_ALLOC_FAILED;
2441     }
2442
2443     // Add message to send queue
2444     ca_mutex_lock(g_bleServerSendDataMutex);
2445     CAQueueingThreadAddData(g_bleServerSendQueueHandle,
2446                             bleData,
2447                             sizeof(CALEData_t));
2448     ca_mutex_unlock(g_bleServerSendDataMutex);
2449 #endif
2450     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2451     return CA_STATUS_OK;
2452 }
2453
2454 static CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress,
2455                                                 const uint8_t *data,
2456                                                 uint32_t dataLength,
2457                                                 uint32_t *sentLength)
2458 {
2459     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2460
2461     //Input validation
2462     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
2463     VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
2464
2465 #ifdef SINGLE_THREAD
2466     if(g_networkPacketReceivedCallback)
2467     {
2468         // will be filled by upper layer
2469         const CASecureEndpoint_t endpoint =
2470             { .endpoint = { .adapter = CA_ADAPTER_GATT_BTLE } };
2471
2472
2473         g_networkPacketReceivedCallback(&endpoint, data, dataLength);
2474     }
2475 #else
2476     VERIFY_NON_NULL_RET(g_bleReceiverQueue,
2477                         CALEADAPTER_TAG,
2478                         "g_bleReceiverQueue",
2479                         CA_STATUS_FAILED);
2480
2481     //Add message to data queue
2482     CAEndpoint_t * const remoteEndpoint =
2483         CACreateEndpointObject(CA_DEFAULT_FLAGS,
2484                                CA_ADAPTER_GATT_BTLE,
2485                                remoteAddress,
2486                                0);
2487
2488     if (NULL == remoteEndpoint)
2489     {
2490         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
2491         return CA_STATUS_FAILED;
2492     }
2493
2494     // Create bleData to add to queue
2495     OIC_LOG_V(DEBUG,
2496               CALEADAPTER_TAG,
2497               "Data received from LE layer [%d]",
2498               dataLength);
2499
2500     CALEData_t * const bleData =
2501         CACreateLEData(remoteEndpoint, data, dataLength, g_bleServerSenderInfo);
2502
2503     if (!bleData)
2504     {
2505         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
2506         CAFreeEndpoint(remoteEndpoint);
2507         return CA_MEMORY_ALLOC_FAILED;
2508     }
2509
2510     CAFreeEndpoint(remoteEndpoint);
2511     // Add message to receiver queue
2512     CAQueueingThreadAddData(g_bleReceiverQueue, bleData, sizeof(CALEData_t));
2513
2514     *sentLength = dataLength;
2515 #endif
2516     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2517     return CA_STATUS_OK;
2518 }
2519
2520 static CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress,
2521                                                 const uint8_t *data,
2522                                                 uint32_t dataLength,
2523                                                 uint32_t *sentLength)
2524 {
2525     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2526
2527     //Input validation
2528     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
2529     VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
2530 #ifndef SINGLE_THREAD
2531     VERIFY_NON_NULL_RET(g_bleReceiverQueue, CALEADAPTER_TAG,
2532                         "g_bleReceiverQueue",
2533                         CA_STATUS_FAILED);
2534
2535     //Add message to data queue
2536     CAEndpoint_t *remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
2537                                                           CA_ADAPTER_GATT_BTLE,
2538                                                           remoteAddress, 0);
2539     if (NULL == remoteEndpoint)
2540     {
2541         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
2542         return CA_STATUS_FAILED;
2543     }
2544
2545     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data received from LE layer [%u]", dataLength);
2546
2547     // Create bleData to add to queue
2548     CALEData_t *bleData = CACreateLEData(remoteEndpoint, data,
2549                                          dataLength, g_bleClientSenderInfo);
2550     if (!bleData)
2551     {
2552         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
2553         CAFreeEndpoint(remoteEndpoint);
2554         return CA_MEMORY_ALLOC_FAILED;
2555     }
2556
2557     CAFreeEndpoint(remoteEndpoint);
2558     // Add message to receiver queue
2559     CAQueueingThreadAddData(g_bleReceiverQueue, bleData, sizeof(CALEData_t));
2560
2561     *sentLength = dataLength;
2562 #endif
2563     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2564     return CA_STATUS_OK;
2565 }
2566
2567 static void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle)
2568 {
2569     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2570
2571     ca_mutex_lock(g_bleAdapterThreadPoolMutex);
2572     g_bleAdapterThreadPool = handle;
2573     ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
2574
2575     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2576 }
2577
2578 static void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback)
2579 {
2580     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
2581
2582     ca_mutex_lock(g_bleAdapterReqRespCbMutex);
2583
2584     g_networkPacketReceivedCallback = callback;
2585
2586     ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
2587
2588     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
2589 }
2590
2591 static void CALEErrorHandler(const char *remoteAddress,
2592                              const uint8_t *data,
2593                              uint32_t dataLen,
2594                              CAResult_t result)
2595 {
2596     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEErrorHandler IN");
2597
2598     VERIFY_NON_NULL_VOID(data, CALEADAPTER_TAG, "Data is null");
2599
2600     CAEndpoint_t *rep = CACreateEndpointObject(CA_DEFAULT_FLAGS,
2601                                                CA_ADAPTER_GATT_BTLE,
2602                                                remoteAddress,
2603                                                0);
2604
2605     // if required, will be used to build remote endpoint
2606     g_errorHandler(rep, data, dataLen, result);
2607
2608     CAFreeEndpoint(rep);
2609
2610     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEErrorHandler OUT");
2611 }
2612
2613 #ifndef SINGLE_THREAD
2614 static void CALERemoveSendQueueData(CAQueueingThread_t *queueHandle, ca_mutex mutex,
2615                                     const char* address)
2616 {
2617     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALERemoveSendQueueData");
2618
2619     VERIFY_NON_NULL_VOID(queueHandle, CALEADAPTER_TAG, "queueHandle");
2620     VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
2621
2622     ca_mutex_lock(mutex);
2623     while (u_queue_get_size(queueHandle->dataQueue) > 0)
2624     {
2625         OIC_LOG(DEBUG, CALEADAPTER_TAG, "get data from queue");
2626         u_queue_message_t *message = u_queue_get_element(queueHandle->dataQueue);
2627         if (NULL != message)
2628         {
2629             CALEData_t *bleData = (CALEData_t *) message->msg;
2630             if (bleData && bleData->remoteEndpoint)
2631             {
2632                 if (!strcmp(bleData->remoteEndpoint->addr, address))
2633                 {
2634                     OIC_LOG(DEBUG, CALEADAPTER_TAG, "found the message of disconnected device");
2635                     if (NULL != queueHandle->destroy)
2636                     {
2637                         queueHandle->destroy(message->msg, message->size);
2638                     }
2639                     else
2640                     {
2641                         OICFree(message->msg);
2642                     }
2643
2644                     OICFree(message);
2645                 }
2646             }
2647         }
2648     }
2649     ca_mutex_unlock(mutex);
2650 }
2651
2652 static void CALERemoveReceiveQueueData(u_arraylist_t *dataInfoList, const char* address)
2653 {
2654     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALERemoveReceiveQueueData");
2655
2656     VERIFY_NON_NULL_VOID(dataInfoList, CALEADAPTER_TAG, "dataInfoList");
2657     VERIFY_NON_NULL_VOID(address, CALEADAPTER_TAG, "address");
2658
2659     CABLESenderInfo_t *senderInfo = NULL;
2660     uint32_t senderIndex = 0;
2661
2662     if(CA_STATUS_OK == CALEGetSenderInfo(address, dataInfoList, &senderInfo,
2663                                          &senderIndex))
2664     {
2665         u_arraylist_remove(dataInfoList, senderIndex);
2666         OICFree(senderInfo->defragData);
2667         OICFree(senderInfo->remoteEndpoint);
2668         OICFree(senderInfo);
2669
2670         OIC_LOG(DEBUG, CALEADAPTER_TAG, "SenderInfo is removed for disconnection");
2671     }
2672     else
2673     {
2674         OIC_LOG(DEBUG, CALEADAPTER_TAG, "SenderInfo doesn't exist");
2675     }
2676 }
2677 #endif