BLE De-fragmentation changes and optimization for receiver handler
[platform/upstream/iotivity.git] / resource / csdk / connectivity / src / bt_le_adapter / caleadapter.c
1 /* ****************************************************************
2  *
3  * Copyright 2014 Samsung Electronics All Rights Reserved.
4  *
5  *
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  ******************************************************************/
20 #include "caleadapter.h"
21
22 #include <stdio.h>
23 #include <stdlib.h>
24
25 #include "caleinterface.h"
26 #include "cacommon.h"
27 #include "camutex.h"
28 #include "caadapterutils.h"
29 #ifndef SINGLE_THREAD
30 #include "caqueueingthread.h"
31 #endif
32 #include "cafragmentation.h"
33 #include "oic_malloc.h"
34 #include "oic_string.h"
35 #include "caremotehandler.h"
36
37 /**
38  * Logging tag for module name.
39  */
40 #define CALEADAPTER_TAG "LAD"
41
42 /**
43  * Callback to provide the status of the network change to CA layer.
44  */
45 static CANetworkChangeCallback g_networkCallback = NULL;
46
47 /**
48  * bleAddress of the local adapter. Value will be initialized to zero, and will
49  *        be updated later.
50  */
51 static char g_localBLEAddress[18] = {0};
52
53 /**
54  * Variable to differentiate btw GattServer and GattClient.
55  */
56 static bool g_isServer = false;
57
58 /**
59  * Mutex to synchronize the task to be executed on the GattServer function
60  * calls.
61  */
62 static ca_mutex g_bleIsServerMutex = NULL;
63
64 /**
65  * Mutex to synchronize the callback to be called for the network changes.
66  */
67 static ca_mutex g_bleNetworkCbMutex = NULL;
68
69 /**
70  * Mutex to synchronize the updation of the local LE address of the adapter.
71  */
72 static ca_mutex g_bleLocalAddressMutex = NULL;
73
74 /**
75  * reference to threadpool.
76  */
77 static ca_thread_pool_t g_bleAdapterThreadPool = NULL;
78
79 /**
80  * Mutex to synchronize the task to be pushed to thread pool.
81  */
82 static ca_mutex g_bleAdapterThreadPoolMutex = NULL;
83
84 /**
85  * Mutex to synchronize the queing of the data from SenderQueue.
86  */
87 static ca_mutex g_bleClientSendDataMutex = NULL;
88
89 /**
90  * Mutex to synchronize the queing of the data from ReceiverQueue.
91  */
92 static ca_mutex g_bleClientReceiveDataMutex = NULL;
93
94
95 /**
96  * Mutex to synchronize the queing of the data from SenderQueue.
97  */
98 static ca_mutex g_bleServerSendDataMutex = NULL;
99
100 /**
101  * Mutex to synchronize the queing of the data from ReceiverQueue.
102  */
103 static ca_mutex g_bleServerReceiveDataMutex = NULL;
104
105 /**
106  * Mutex to synchronize the callback to be called for the adapterReqResponse.
107  */
108 static ca_mutex g_bleAdapterReqRespCbMutex = NULL;
109
110 /**
111  * Callback to be called when network packet recieved from either
112  * GattServer or GattClient.
113  */
114 static CANetworkPacketReceivedCallback g_networkPacketReceivedCallback = NULL;
115
116 /**
117  * Callback to notify error from the BLE adapter.
118  */
119 static CAErrorHandleCallback g_errorHandler = NULL;
120
121 /**
122  * Storing Adapter state information.
123  */
124 static CAAdapterState_t g_bleAdapterState = CA_ADAPTER_DISABLED;
125
126 /**
127  * status of BLE Server Status.
128  * This ENUM provides information of LE Adapter Server status.
129  */
130 typedef enum
131 {
132     CA_SERVER_NOTSTARTED = 0,
133     CA_LISTENING_SERVER,
134     CA_DISCOVERY_SERVER
135 } CALeServerStatus;
136
137 /**
138  * structure to maintain the status of the server.
139  */
140 static CALeServerStatus gLeServerStatus = CA_SERVER_NOTSTARTED;
141
142 /**
143 * This function is used to register network change notification callback.
144 *
145 * @param[in]  netCallback CANetworkChangeCallback callback which will be
146 * set for the change in nwk.
147 *
148 * @return  0 on success otherwise a positive error value.
149 * @retval  CA_STATUS_OK  Successful.
150 * @retval  CA_STATUS_INVALID_PARAM  Invalid input argumets.
151 * @retval  CA_STATUS_FAILED Operation failed.
152 *
153 */
154 CAResult_t CALERegisterNetworkNotifications(CANetworkChangeCallback netCallback);
155
156 /**
157 * Used to Set the gThreadPool handle which is required for spawning new thread.
158 *
159 * @param[in] handle - Thread pool handle which is given by above layer for
160 * using thread creation task.
161 *
162 */
163 void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle);
164
165 /**
166 * This function is used to call the callback to the upper layer when the
167 * device state gets changed.
168 *
169 * @param[in]  adapter_state New state of the adapter to be notified to the
170 * upper layer.
171 *
172 */
173 void CALEDeviceStateChangedCb( CAAdapterState_t adapter_state);
174
175 /**
176 * Used to initialize all required mutex variable for LE Adapter implementation.
177 *
178 * @return  0 on success otherwise a positive error value.
179 * @retval  CA_STATUS_OK  Successful.
180 * @retval  CA_STATUS_INVALID_PARAM  Invalid input argumets.
181 * @retval  CA_STATUS_FAILED Operation failed.
182 *
183 */
184 CAResult_t CAInitLEAdapterMutex();
185
186 /**
187 * Used to terminate all required mutex variable for LE adapter implementation.
188 *
189 */
190 void CATerminateLEAdapterMutex();
191
192 /**
193 * prepares and notify error through error callback.
194 *
195 */
196 static void CALEErrorHandler(const char *remoteAddress, const void *data, uint32_t dataLen,
197                              CAResult_t result);
198
199 #ifndef SINGLE_THREAD
200 /**
201  * Stop condition of recvhandler.
202  */
203 static bool g_dataReceiverHandlerState = false;
204
205 /**
206  * Sender informations to be stored here
207  */
208 static u_arraylist_t *g_senderInfo = NULL;
209
210 /**
211  * Queue to process the outgoing packets from GATTClient.
212  */
213 static CAQueueingThread_t *g_bleClientSendQueueHandle = NULL;
214
215 /**
216  * Queue to process the incoming packets to GATT Client.
217  */
218 static CAQueueingThread_t *g_bleReceiverQueue = NULL;
219
220 /**
221  * Queue to process the outgoing packets from GATTServer.
222  */
223 static CAQueueingThread_t *g_bleServerSendQueueHandle = NULL;
224
225 /**
226  * Mutex to synchronize the incoming data packets to receiver
227  */
228 static ca_mutex g_bleReceiveDataMutex = NULL;
229
230 /**
231 * Used to free data.
232 *
233 */
234 static void CALEDataDestroyer(void *data, uint32_t size);
235
236 void CAInitLEQueues()
237 {
238     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
239
240     CAResult_t result = CAInitLEServerQueues();
241     if (CA_STATUS_OK != result)
242     {
243         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleServerQueues failed");
244         return;
245     }
246
247     result = CAInitLEClientQueues();
248     if (CA_STATUS_OK != result)
249     {
250         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientQueues failed");
251         return;
252     }
253
254     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
255 }
256
257 CAResult_t CAInitLEServerQueues()
258 {
259     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
260
261     ca_mutex_lock(g_bleAdapterThreadPoolMutex);
262
263     CAResult_t result = CAInitLEServerSenderQueue();
264     if (CA_STATUS_OK != result)
265     {
266         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleServerSenderQueue failed");
267         ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
268         return CA_STATUS_FAILED;
269     }
270
271     result = CAInitLEReceiverQueue();
272     if (CA_STATUS_OK != result)
273     {
274         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleServerReceiverQueue failed");
275         ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
276         return CA_STATUS_FAILED;
277     }
278
279     g_dataReceiverHandlerState = true;
280
281     ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
282
283     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
284     return CA_STATUS_OK;
285 }
286
287 CAResult_t CAInitLEClientQueues()
288 {
289     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
290
291     ca_mutex_lock(g_bleAdapterThreadPoolMutex);
292
293     CAResult_t result = CAInitLEClientSenderQueue();
294     if (CA_STATUS_OK != result)
295     {
296         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientSenderQueue failed");
297         ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
298         return CA_STATUS_FAILED;
299     }
300
301     result = CAInitLEReceiverQueue();
302     if (CA_STATUS_OK != result)
303     {
304         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientReceiverQueue failed");
305         ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
306         return CA_STATUS_FAILED;
307     }
308
309     g_dataReceiverHandlerState = true;
310
311     ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
312
313     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
314     return CA_STATUS_OK;
315 }
316
317 CAResult_t CAInitLEReceiverQueue()
318 {
319     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
320     // Check if the message queue is already initialized
321     if (g_bleReceiverQueue)
322     {
323         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
324         return CA_STATUS_OK;
325     }
326
327     // Create recv message queue
328     g_bleReceiverQueue = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
329     if (!g_bleReceiverQueue)
330     {
331         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
332         return CA_MEMORY_ALLOC_FAILED;
333     }
334
335     g_senderInfo = u_arraylist_create();
336     if (!g_senderInfo)
337     {
338         OIC_LOG(ERROR, CALEADAPTER_TAG, "ClientInfo memory allcation failed!");
339         OICFree(g_bleReceiverQueue);
340         g_bleReceiverQueue = NULL;
341         return CA_MEMORY_ALLOC_FAILED;
342     }
343
344     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleReceiverQueue, g_bleAdapterThreadPool,
345             CALEDataReceiverHandler, CALEDataDestroyer))
346     {
347         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
348         OICFree(g_bleReceiverQueue);
349         g_bleReceiverQueue = NULL;
350         u_arraylist_free(&g_senderInfo);
351         return CA_STATUS_FAILED;
352     }
353
354     if (CA_STATUS_OK != CAQueueingThreadStart(g_bleReceiverQueue))
355     {
356         OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
357         OICFree(g_bleReceiverQueue);
358         g_bleReceiverQueue = NULL;
359         u_arraylist_free(&g_senderInfo);
360         return CA_STATUS_FAILED;
361     }
362
363     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
364     return CA_STATUS_OK;
365 }
366
367 CAResult_t CAInitLEServerSenderQueue()
368 {
369     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
370     // Check if the message queue is already initialized
371     if (g_bleServerSendQueueHandle)
372     {
373         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Queue is already initialized!");
374         return CA_STATUS_OK;
375     }
376
377     // Create send message queue
378     g_bleServerSendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
379     if (!g_bleServerSendQueueHandle)
380     {
381         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
382         return CA_MEMORY_ALLOC_FAILED;
383     }
384
385     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleServerSendQueueHandle,
386                                                    g_bleAdapterThreadPool,
387                                                    CALEServerSendDataThread, CALEDataDestroyer))
388     {
389         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
390         OICFree(g_bleServerSendQueueHandle);
391         g_bleServerSendQueueHandle = NULL;
392         return CA_STATUS_FAILED;
393     }
394
395     if (CA_STATUS_OK != CAQueueingThreadStart(g_bleServerSendQueueHandle))
396     {
397         OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
398         OICFree(g_bleServerSendQueueHandle);
399         g_bleServerSendQueueHandle = NULL;
400         return CA_STATUS_FAILED;
401     }
402
403     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
404     return CA_STATUS_OK;
405 }
406
407 void CALEClearSenderInfo()
408 {
409     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
410
411     uint32_t listIndex = 0;
412     uint32_t listLength = u_arraylist_length(g_senderInfo);
413     for (listIndex = 0; listIndex < listLength; listIndex++)
414     {
415         CABLESenderInfo_t *info = (CABLESenderInfo_t *) u_arraylist_get(g_senderInfo, listIndex);
416         if(!info)
417         {
418             continue;
419         }
420
421         OICFree(info->defragData);
422         CAFreeEndpoint(info->remoteEndpoint);
423         OICFree(info);
424     }
425     u_arraylist_free(&g_senderInfo);
426     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
427 }
428
429 CAResult_t CAInitLEClientSenderQueue()
430 {
431     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
432
433     if (g_bleClientSendQueueHandle)
434     {
435         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
436         return CA_STATUS_OK;
437     }
438
439     // Create send message queue
440     g_bleClientSendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
441     if (!g_bleClientSendQueueHandle)
442     {
443         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
444         return CA_MEMORY_ALLOC_FAILED;
445     }
446
447     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleClientSendQueueHandle,
448                                                    g_bleAdapterThreadPool,
449                                                    CALEClientSendDataThread, CALEDataDestroyer))
450     {
451         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
452         OICFree(g_bleClientSendQueueHandle);
453         g_bleClientSendQueueHandle = NULL;
454         return CA_STATUS_FAILED;
455     }
456
457     if (CA_STATUS_OK != CAQueueingThreadStart(g_bleClientSendQueueHandle))
458     {
459         OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
460         OICFree(g_bleClientSendQueueHandle);
461         g_bleClientSendQueueHandle = NULL;
462         return CA_STATUS_FAILED;
463     }
464
465     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
466     return CA_STATUS_OK;
467 }
468
469 void CAStopLEQueues()
470 {
471     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
472
473     ca_mutex_lock(g_bleClientSendDataMutex);
474     if (NULL != g_bleClientSendQueueHandle)
475     {
476         CAQueueingThreadStop(g_bleClientSendQueueHandle);
477     }
478     ca_mutex_unlock(g_bleClientSendDataMutex);
479
480     ca_mutex_lock(g_bleServerSendDataMutex);
481     if (NULL != g_bleServerSendQueueHandle)
482     {
483         CAQueueingThreadStop(g_bleServerSendQueueHandle);
484     }
485     ca_mutex_unlock(g_bleServerSendDataMutex);
486
487     ca_mutex_lock(g_bleReceiveDataMutex);
488     if (NULL != g_bleReceiverQueue)
489     {
490         CAQueueingThreadStop(g_bleReceiverQueue);
491     }
492     ca_mutex_unlock(g_bleReceiveDataMutex);
493
494     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
495 }
496
497 void CATerminateLEQueues()
498 {
499     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
500
501     CAQueueingThreadDestroy(g_bleClientSendQueueHandle);
502     OICFree(g_bleClientSendQueueHandle);
503     g_bleClientSendQueueHandle = NULL;
504
505     CAQueueingThreadDestroy(g_bleServerSendQueueHandle);
506     OICFree(g_bleServerSendQueueHandle);
507     g_bleServerSendQueueHandle = NULL;
508
509     CAQueueingThreadDestroy(g_bleReceiverQueue);
510     OICFree(g_bleReceiverQueue);
511     g_bleReceiverQueue = NULL;
512
513     CALEClearSenderInfo();
514
515     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
516 }
517
518 CAResult_t CALEGetSenderInfo(char *leAddress, CABLESenderInfo_t **senderInfo,
519                                         uint32_t *senderIndex)
520 {
521     VERIFY_NON_NULL_RET(leAddress, CALEADAPTER_TAG, "Ble-Address in-param NULL", CA_STATUS_FAILED);
522     VERIFY_NON_NULL_RET(senderIndex, CALEADAPTER_TAG, "Index in-param NULL", CA_STATUS_FAILED);
523
524     uint32_t listLength = u_arraylist_length(g_senderInfo);
525     uint32_t addrLength = strlen(leAddress);
526     for (uint32_t index = 0; index < listLength; index++)
527     {
528         CABLESenderInfo_t *info = (CABLESenderInfo_t *) u_arraylist_get(g_senderInfo, index);
529         if(!info || !(info->remoteEndpoint))
530         {
531             continue;
532         }
533
534         if(!strncmp(info->remoteEndpoint->addr, leAddress, addrLength))
535         {
536             *senderIndex = index;
537             if(senderInfo)
538             {
539                 *senderInfo = info;
540             }
541             return CA_STATUS_OK;
542         }
543     }
544
545     return CA_STATUS_FAILED;
546 }
547
548 void CALEDataReceiverHandler(void *threadData)
549 {
550     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
551
552     ca_mutex_lock(g_bleReceiveDataMutex);
553
554     if (g_dataReceiverHandlerState)
555     {
556         OIC_LOG(DEBUG, CALEADAPTER_TAG, "checking for DE Fragmentation");
557
558         CALEData_t *bleData = (CALEData_t *) threadData;
559         if (!bleData)
560         {
561             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bleData!");
562             ca_mutex_unlock(g_bleReceiveDataMutex);
563             return;
564         }
565
566         if(!(bleData->remoteEndpoint))
567         {
568             OIC_LOG(ERROR, CALEADAPTER_TAG, "Client RemoteEndPoint NULL!!");
569             ca_mutex_unlock(g_bleReceiveDataMutex);
570             return;
571         }
572
573         CABLESenderInfo_t *senderInfo = NULL;
574         uint32_t senderIndex = 0;
575
576         if(CA_STATUS_OK != CALEGetSenderInfo(bleData->remoteEndpoint->addr,
577                                                 &senderInfo, &senderIndex))
578         {
579             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "This is a new client [%s]",
580                                                 bleData->remoteEndpoint->addr);
581         }
582
583         if(!senderInfo)
584         {
585             CABLESenderInfo_t *newSender = (CABLESenderInfo_t*)OICMalloc(sizeof(CABLESenderInfo_t));
586             if(!newSender)
587             {
588                 OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed for new sender");
589                 ca_mutex_unlock(g_bleReceiveDataMutex);
590                 return;
591             }
592             newSender->recvDataLen = 0;
593             newSender->totalDataLen = 0;
594             newSender->defragData = NULL;
595             newSender->remoteEndpoint = NULL;
596
597             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Parsing the header");
598             newSender->totalDataLen = CAParseHeader((char*)bleData->data);
599             if(!(newSender->totalDataLen))
600             {
601                 OIC_LOG(ERROR, CALEADAPTER_TAG, "Total Data Length is parsed as 0!!!");
602                 OICFree(newSender);
603                 ca_mutex_unlock(g_bleReceiveDataMutex);
604                 return;
605             }
606
607             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Total data to be accumulated [%u] bytes",
608                                                 newSender->totalDataLen);
609             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "data received in the first packet [%u] bytes",
610                                                 bleData->dataLen);
611
612             newSender->defragData = (char *) OICCalloc(newSender->totalDataLen + 1, sizeof(char));
613
614             if (NULL == newSender->defragData)
615             {
616                 OIC_LOG(ERROR, CALEADAPTER_TAG, "defragData is NULL!");
617                 OICFree(newSender);
618                 ca_mutex_unlock(g_bleReceiveDataMutex);
619                 return;
620             }
621
622             const char *remoteAddress = bleData->remoteEndpoint->addr;
623             newSender->remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
624                                                             CA_ADAPTER_GATT_BTLE, remoteAddress, 0);
625             if (NULL == newSender->remoteEndpoint)
626             {
627                 OIC_LOG(ERROR, CALEADAPTER_TAG, "remoteEndpoint is NULL!");
628                 OICFree(newSender->defragData);
629                 OICFree(newSender);
630                 ca_mutex_unlock(g_bleReceiveDataMutex);
631                 return;
632             }
633             memcpy(newSender->defragData, bleData->data + CA_HEADER_LENGTH,
634                     bleData->dataLen - CA_HEADER_LENGTH);
635             newSender->recvDataLen += bleData->dataLen - CA_HEADER_LENGTH;
636             u_arraylist_add(g_senderInfo,(void *)newSender);
637
638             //Getting newSender index position in g_senderInfo array list
639             if(CA_STATUS_OK !=
640                 CALEGetSenderInfo(newSender->remoteEndpoint->addr, NULL, &senderIndex))
641             {
642                 OIC_LOG(ERROR, CALEADAPTER_TAG, "Existing sender index not found!!");
643                 OICFree(senderInfo->defragData);
644                 OICFree(senderInfo);
645                 ca_mutex_unlock(g_bleReceiveDataMutex);
646                 return;
647             }
648             senderInfo = newSender;
649         }
650         else
651         {
652             if(senderInfo->recvDataLen + bleData->dataLen > senderInfo->totalDataLen)
653             {
654                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
655                             "Data Length exceeding error!! Receiving [%d] total length [%d]",
656                             senderInfo->recvDataLen + bleData->dataLen, senderInfo->totalDataLen);
657                 u_arraylist_remove(g_senderInfo, senderIndex);
658                 OICFree(senderInfo->defragData);
659                 OICFree(senderInfo);
660                 ca_mutex_unlock(g_bleReceiveDataMutex);
661                 return;
662             }
663             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Copying the data of length [%d]", bleData->dataLen);
664             memcpy(senderInfo->defragData + senderInfo->recvDataLen, bleData->data,
665                     bleData->dataLen);
666             senderInfo->recvDataLen += bleData->dataLen ;
667             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "totalDatalength  [%d] recveived Datalen [%d]",
668                                                 senderInfo->totalDataLen, senderInfo->recvDataLen);
669         }
670
671         if (senderInfo->totalDataLen == senderInfo->recvDataLen)
672         {
673             ca_mutex_lock(g_bleAdapterReqRespCbMutex);
674             if (NULL == g_networkPacketReceivedCallback)
675             {
676                 OIC_LOG(ERROR, CALEADAPTER_TAG, "gReqRespCallback is NULL!");
677
678                 u_arraylist_remove(g_senderInfo, senderIndex);
679                 OICFree(senderInfo->defragData);
680                 OICFree(senderInfo);
681                 ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
682                 ca_mutex_unlock(g_bleReceiveDataMutex);
683                 return;
684             }
685             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending data up !");
686             g_networkPacketReceivedCallback(senderInfo->remoteEndpoint,
687                                                 senderInfo->defragData, senderInfo->recvDataLen);
688             ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
689             u_arraylist_remove(g_senderInfo, senderIndex);
690             senderInfo->remoteEndpoint = NULL;
691             senderInfo->defragData = NULL;
692             OICFree(senderInfo);
693         }
694     }
695     ca_mutex_unlock(g_bleReceiveDataMutex);
696     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
697 }
698
699 void CALEServerSendDataThread(void *threadData)
700 {
701     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
702
703     CALEData_t *bleData = (CALEData_t *) threadData;
704     if (!bleData)
705     {
706         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bledata!");
707         return;
708     }
709
710     char *header = (char *) OICCalloc(CA_HEADER_LENGTH, sizeof(char));
711     VERIFY_NON_NULL_VOID(header, CALEADAPTER_TAG, "Malloc failed");
712
713     int32_t totalLength = bleData->dataLen + CA_HEADER_LENGTH;
714
715     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server total Data length with header is [%d]", totalLength);
716     char *dataSegment = (char *) OICCalloc(totalLength + 1, sizeof(char));
717     if (NULL == dataSegment)
718     {
719         OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failed");
720         OICFree(header);
721         return;
722     }
723
724     CAResult_t result = CAGenerateHeader(header, bleData->dataLen);
725     if (CA_STATUS_OK != result )
726     {
727         OIC_LOG(ERROR, CALEADAPTER_TAG, "Generate header failed");
728         OICFree(header);
729         OICFree(dataSegment);
730         return ;
731     }
732
733     memcpy(dataSegment, header, CA_HEADER_LENGTH);
734     OICFree(header);
735
736     int32_t length = 0;
737     if (CA_SUPPORTED_BLE_MTU_SIZE > totalLength)
738     {
739         length = totalLength;
740         memcpy(dataSegment + CA_HEADER_LENGTH, bleData->data, bleData->dataLen);
741     }
742     else
743     {
744         length =  CA_SUPPORTED_BLE_MTU_SIZE;
745         memcpy(dataSegment + CA_HEADER_LENGTH, bleData->data,
746                CA_SUPPORTED_BLE_MTU_SIZE - CA_HEADER_LENGTH);
747     }
748
749     int32_t iter = totalLength / CA_SUPPORTED_BLE_MTU_SIZE;
750     int32_t index = 0;
751     // Send the first segment with the header.
752      if (NULL != bleData->remoteEndpoint) //Sending Unicast Data
753     {
754         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Unicast Data");
755         result = CAUpdateCharacteristicsToGattClient(
756                     bleData->remoteEndpoint->addr, dataSegment, length);
757         if (CA_STATUS_OK != result)
758         {
759             OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]", result);
760             g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
761             OICFree(dataSegment);
762             return;
763         }
764
765         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", length);
766         for (index = 1; index < iter; index++)
767         {
768             // Send the remaining header.
769             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Sending the chunk number [%d]", index);
770             result = CAUpdateCharacteristicsToGattClient(
771                          bleData->remoteEndpoint->addr,
772                          bleData->data + ((index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH),
773                          CA_SUPPORTED_BLE_MTU_SIZE);
774             if (CA_STATUS_OK != result)
775             {
776                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
777                             "Update characteristics failed, result [%d]", result);
778                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
779                 OICFree(dataSegment);
780                 return;
781             }
782             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]",
783                                                CA_SUPPORTED_BLE_MTU_SIZE);
784         }
785
786         int32_t remainingLen = totalLength % CA_SUPPORTED_BLE_MTU_SIZE;
787         if (remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
788         {
789             // send the last segment of the data (Ex: 22 bytes of 622 bytes of data when MTU is 200)
790             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
791             result = CAUpdateCharacteristicsToGattClient(
792                          bleData->remoteEndpoint->addr,
793                          bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
794                          remainingLen);
795             if (CA_STATUS_OK != result)
796             {
797                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
798                                                    result);
799                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
800                 OICFree(dataSegment);
801                 return;
802             }
803             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", remainingLen);
804         }
805      }
806     else
807     {
808         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Server Sending Multicast data");
809         result = CAUpdateCharacteristicsToAllGattClients(dataSegment, length);
810         if (CA_STATUS_OK != result)
811         {
812             OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
813                       result);
814             CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
815             OICFree(dataSegment);
816             return;
817         }
818         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", length);
819         for (index = 1; index < iter; index++)
820         {
821             // Send the remaining header.
822             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Sending the chunk number [%d]", index);
823             result = CAUpdateCharacteristicsToAllGattClients(
824                          bleData->data + ((index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH),
825                          CA_SUPPORTED_BLE_MTU_SIZE);
826             if (CA_STATUS_OK != result)
827             {
828                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
829                           result);
830                 CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
831                 OICFree(dataSegment);
832                 return;
833             }
834             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", CA_SUPPORTED_BLE_MTU_SIZE);
835         }
836
837         int32_t remainingLen = totalLength % CA_SUPPORTED_BLE_MTU_SIZE;
838         if (remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
839         {
840             // send the last segment of the data (Ex: 22 bytes of 622 bytes of data when MTU is 200)
841             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
842             result = CAUpdateCharacteristicsToAllGattClients(
843                          bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
844                          remainingLen);
845             if (CA_STATUS_OK != result)
846             {
847                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
848                           result);
849                 CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
850                 OICFree(dataSegment);
851                 return;
852             }
853             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Server Sent data length [%d]", remainingLen);
854         }
855     }
856     OICFree(dataSegment);
857
858     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
859 }
860
861 void CALEClientSendDataThread(void *threadData)
862 {
863     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
864
865     CALEData_t *bleData = (CALEData_t *) threadData;
866     if (!bleData)
867     {
868         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bledata!");
869         return;
870     }
871
872     char *header = (char *) OICCalloc(CA_HEADER_LENGTH, sizeof(char));
873     VERIFY_NON_NULL_VOID(header, CALEADAPTER_TAG, "Malloc failed");
874
875     uint32_t totalLength = bleData->dataLen + CA_HEADER_LENGTH;
876     char *dataSegment = (char *) OICCalloc(totalLength + 1, sizeof(char));
877     if (NULL == dataSegment)
878     {
879         OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failed");
880         OICFree(header);
881         return;
882     }
883
884     CAResult_t result = CAGenerateHeader(header, bleData->dataLen);
885     if (CA_STATUS_OK != result )
886     {
887         OIC_LOG(ERROR, CALEADAPTER_TAG, "Generate header failed");
888         OICFree(header);
889         OICFree(dataSegment);
890         return ;
891     }
892     memcpy(dataSegment, header, CA_HEADER_LENGTH);
893     OICFree(header);
894
895     uint32_t length = 0;
896     if (CA_SUPPORTED_BLE_MTU_SIZE > totalLength)
897     {
898         length = totalLength;
899         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "length [%d]", length);
900         memcpy(dataSegment + CA_HEADER_LENGTH, bleData->data, bleData->dataLen);
901     }
902     else
903     {
904         length = CA_SUPPORTED_BLE_MTU_SIZE;
905         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "length  [%d]", length);
906         memcpy(dataSegment + CA_HEADER_LENGTH, bleData->data,
907                CA_SUPPORTED_BLE_MTU_SIZE - CA_HEADER_LENGTH);
908     }
909
910     uint32_t iter = totalLength / CA_SUPPORTED_BLE_MTU_SIZE;
911     uint32_t index = 0;
912     if (NULL != bleData->remoteEndpoint) //Sending Unicast Data
913     {
914         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending Unicast Data");
915         // Send the first segment with the header.
916         result = CAUpdateCharacteristicsToGattServer(bleData->remoteEndpoint->addr,
917                  dataSegment,
918                  length,
919                  LE_UNICAST, 0);
920
921         if (CA_STATUS_OK != result)
922         {
923             OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]", result);
924             g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
925             OICFree(dataSegment);
926             return ;
927         }
928
929         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]", length);
930         for (index = 1; index < iter; index++)
931         {
932             // Send the remaining header.
933             result = CAUpdateCharacteristicsToGattServer(
934                      bleData->remoteEndpoint->addr,
935                      bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
936                      CA_SUPPORTED_BLE_MTU_SIZE,
937                      LE_UNICAST, 0);
938             if (CA_STATUS_OK != result)
939             {
940                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
941                                                    result);
942                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
943                 OICFree(dataSegment);
944                 return;
945             }
946             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]",
947                                                CA_SUPPORTED_BLE_MTU_SIZE);
948         }
949
950         uint32_t remainingLen = totalLength % CA_SUPPORTED_BLE_MTU_SIZE;
951         if (remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
952         {
953             // send the last segment of the data (Ex: 22 bytes of 622 bytes of data when MTU is 200)
954             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
955             result = CAUpdateCharacteristicsToGattServer(
956                      bleData->remoteEndpoint->addr,
957                      bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
958                      remainingLen,
959                      LE_UNICAST, 0);
960
961             if (CA_STATUS_OK != result)
962             {
963                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics failed, result [%d]",
964                                                    result);
965                 g_errorHandler(bleData->remoteEndpoint, bleData->data, bleData->dataLen, result);
966                 OICFree(dataSegment);
967                 return;
968             }
969             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]", remainingLen);
970         }
971     }
972     else
973     {
974         //Sending Mulitcast Data
975         // Send the first segment with the header.
976         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending Multicast Data");
977         result = CAUpdateCharacteristicsToAllGattServers(dataSegment, length);
978         if (CA_STATUS_OK != result)
979         {
980             OIC_LOG_V(ERROR, CALEADAPTER_TAG,
981                       "Update characteristics (all) failed, result [%d]", result);
982             CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
983             OICFree(dataSegment);
984             return ;
985         }
986         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]", length);
987         // Send the remaining header.
988         for (index = 1; index < iter; index++)
989         {
990             result = CAUpdateCharacteristicsToAllGattServers(
991                          bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
992                          CA_SUPPORTED_BLE_MTU_SIZE);
993             if (CA_STATUS_OK != result)
994             {
995                 OIC_LOG_V(ERROR, CALEADAPTER_TAG, "Update characteristics (all) failed, result [%d]",
996                           result);
997                 CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
998                 OICFree(dataSegment);
999                 return;
1000             }
1001             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]",
1002                       CA_SUPPORTED_BLE_MTU_SIZE);
1003         }
1004
1005         uint32_t remainingLen = totalLength % CA_SUPPORTED_BLE_MTU_SIZE;
1006         if ( remainingLen && (totalLength > CA_SUPPORTED_BLE_MTU_SIZE))
1007         {
1008             // send the last segment of the data (Ex: 22 bytes of 622 bytes of data when MTU is 200)
1009             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
1010             result = CAUpdateCharacteristicsToAllGattServers(
1011                          bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
1012                           remainingLen);
1013             if (CA_STATUS_OK != result)
1014             {
1015                 OIC_LOG_V(ERROR, CALEADAPTER_TAG,
1016                           "Update characteristics (all) failed, result [%d]", result);
1017                 CALEErrorHandler(NULL, bleData->data, bleData->dataLen, result);
1018                 OICFree(dataSegment);
1019                 return;
1020             }
1021             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Client Sent Data length  is [%d]", remainingLen);
1022         }
1023
1024     }
1025
1026     OICFree(dataSegment);
1027
1028     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT - CABLEClientSendDataThread");
1029 }
1030
1031 CALEData_t *CACreateLEData(const CAEndpoint_t *remoteEndpoint, const void *data,
1032                            uint32_t dataLength)
1033 {
1034     CALEData_t *bleData = (CALEData_t *) OICMalloc(sizeof(CALEData_t));
1035     if (!bleData)
1036     {
1037         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
1038         return NULL;
1039     }
1040
1041     bleData->remoteEndpoint = CACloneEndpoint(remoteEndpoint);
1042     bleData->data = (void *)OICCalloc(dataLength + 1, 1);
1043     if (NULL == bleData->data)
1044     {
1045         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
1046         CAFreeLEData(bleData);
1047         return NULL;
1048     }
1049     memcpy(bleData->data, data, dataLength);
1050     bleData->dataLen = dataLength;
1051
1052     return bleData;
1053 }
1054
1055 void CAFreeLEData(CALEData_t *bleData)
1056 {
1057     VERIFY_NON_NULL_VOID(bleData, CALEADAPTER_TAG, "Param bleData is NULL");
1058
1059     CAFreeEndpoint(bleData->remoteEndpoint);
1060     OICFree(bleData->data);
1061     OICFree(bleData);
1062 }
1063
1064 void CALEDataDestroyer(void *data, uint32_t size)
1065 {
1066     CALEData_t *ledata = (CALEData_t *) data;
1067
1068     CAFreeLEData(ledata);
1069 }
1070 #endif
1071
1072 CAResult_t CAInitLEAdapterMutex()
1073 {
1074     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1075
1076     if (NULL == g_bleIsServerMutex)
1077     {
1078         g_bleIsServerMutex = ca_mutex_new();
1079         if (NULL == g_bleIsServerMutex)
1080         {
1081             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1082             return CA_STATUS_FAILED;
1083         }
1084     }
1085
1086     if (NULL == g_bleNetworkCbMutex)
1087     {
1088         g_bleNetworkCbMutex = ca_mutex_new();
1089         if (NULL == g_bleNetworkCbMutex)
1090         {
1091             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1092             CATerminateLEAdapterMutex();
1093             return CA_STATUS_FAILED;
1094         }
1095     }
1096
1097     if (NULL == g_bleLocalAddressMutex)
1098     {
1099         g_bleLocalAddressMutex = ca_mutex_new();
1100         if (NULL == g_bleLocalAddressMutex)
1101         {
1102             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1103             CATerminateLEAdapterMutex();
1104             return CA_STATUS_FAILED;
1105         }
1106     }
1107
1108     if (NULL == g_bleAdapterThreadPoolMutex)
1109     {
1110         g_bleAdapterThreadPoolMutex = ca_mutex_new();
1111         if (NULL == g_bleAdapterThreadPoolMutex)
1112         {
1113             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1114             CATerminateLEAdapterMutex();
1115             return CA_STATUS_FAILED;
1116         }
1117     }
1118
1119     if (NULL == g_bleClientSendDataMutex)
1120     {
1121         g_bleClientSendDataMutex = ca_mutex_new();
1122         if (NULL == g_bleClientSendDataMutex)
1123         {
1124             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1125             CATerminateLEAdapterMutex();
1126             return CA_STATUS_FAILED;
1127         }
1128     }
1129
1130     if (NULL == g_bleClientReceiveDataMutex)
1131     {
1132         g_bleClientReceiveDataMutex = ca_mutex_new();
1133         if (NULL == g_bleClientReceiveDataMutex)
1134         {
1135             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1136             CATerminateLEAdapterMutex();
1137             return CA_STATUS_FAILED;
1138         }
1139     }
1140
1141     if (NULL == g_bleServerSendDataMutex)
1142     {
1143         g_bleServerSendDataMutex = ca_mutex_new();
1144         if (NULL == g_bleServerSendDataMutex)
1145         {
1146             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1147             CATerminateLEAdapterMutex();
1148             return CA_STATUS_FAILED;
1149         }
1150     }
1151
1152     if (NULL == g_bleServerReceiveDataMutex)
1153     {
1154         g_bleServerReceiveDataMutex = ca_mutex_new();
1155         if (NULL == g_bleServerReceiveDataMutex)
1156         {
1157             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1158             CATerminateLEAdapterMutex();
1159             return CA_STATUS_FAILED;
1160         }
1161     }
1162
1163     if (NULL == g_bleAdapterReqRespCbMutex)
1164     {
1165         g_bleAdapterReqRespCbMutex = ca_mutex_new();
1166         if (NULL == g_bleAdapterReqRespCbMutex)
1167         {
1168             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1169             CATerminateLEAdapterMutex();
1170             return CA_STATUS_FAILED;
1171         }
1172     }
1173
1174     if (NULL == g_bleReceiveDataMutex)
1175     {
1176         g_bleReceiveDataMutex = ca_mutex_new();
1177         if (NULL == g_bleReceiveDataMutex)
1178         {
1179             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1180             return CA_STATUS_FAILED;
1181         }
1182     }
1183
1184     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1185     return CA_STATUS_OK;
1186 }
1187
1188 void CATerminateLEAdapterMutex()
1189 {
1190     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1191
1192     ca_mutex_free(g_bleIsServerMutex);
1193     g_bleIsServerMutex = NULL;
1194
1195     ca_mutex_free(g_bleNetworkCbMutex);
1196     g_bleNetworkCbMutex = NULL;
1197
1198     ca_mutex_free(g_bleLocalAddressMutex);
1199     g_bleLocalAddressMutex = NULL;
1200
1201     ca_mutex_free(g_bleAdapterThreadPoolMutex);
1202     g_bleAdapterThreadPoolMutex = NULL;
1203
1204     ca_mutex_free(g_bleClientSendDataMutex);
1205     g_bleClientSendDataMutex = NULL;
1206
1207     ca_mutex_free(g_bleClientReceiveDataMutex);
1208     g_bleClientReceiveDataMutex = NULL;
1209
1210     ca_mutex_free(g_bleServerSendDataMutex);
1211     g_bleServerSendDataMutex = NULL;
1212
1213     ca_mutex_free(g_bleServerReceiveDataMutex);
1214     g_bleServerReceiveDataMutex = NULL;
1215
1216     ca_mutex_free(g_bleAdapterReqRespCbMutex);
1217     g_bleAdapterReqRespCbMutex = NULL;
1218
1219     ca_mutex_free(g_bleReceiveDataMutex);
1220     g_bleReceiveDataMutex = NULL;
1221
1222     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1223 }
1224
1225 CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
1226                           CANetworkPacketReceivedCallback reqRespCallback,
1227                           CANetworkChangeCallback netCallback,
1228                           CAErrorHandleCallback errorCallback, ca_thread_pool_t handle)
1229 {
1230     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1231
1232     //Input validation
1233     VERIFY_NON_NULL(registerCallback, CALEADAPTER_TAG, "RegisterConnectivity callback is null");
1234     VERIFY_NON_NULL(reqRespCallback, CALEADAPTER_TAG, "PacketReceived Callback is null");
1235     VERIFY_NON_NULL(netCallback, CALEADAPTER_TAG, "NetworkChange Callback is null");
1236
1237     CAResult_t result = CA_STATUS_OK;
1238     result = CAInitLEAdapterMutex();
1239     if (CA_STATUS_OK != result)
1240     {
1241         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleAdapterMutex failed!");
1242         return CA_STATUS_FAILED;
1243     }
1244     result = CAInitializeLENetworkMonitor();
1245     if (CA_STATUS_OK != result)
1246     {
1247         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLENetworkMonitor() failed");
1248         return CA_STATUS_FAILED;
1249     }
1250
1251     CAInitializeLEAdapter();
1252
1253     CASetLEClientThreadPoolHandle(handle);
1254     CASetLEReqRespClientCallback(CALEAdapterClientReceivedData);
1255     CASetLEServerThreadPoolHandle(handle);
1256     CASetLEAdapterThreadPoolHandle(handle);
1257     CASetLEReqRespServerCallback(CALEAdapterServerReceivedData);
1258     CASetLEReqRespAdapterCallback(reqRespCallback);
1259
1260     CASetBLEClientErrorHandleCallback(CALEErrorHandler);
1261     CASetBLEServerErrorHandleCallback(CALEErrorHandler);
1262     CALERegisterNetworkNotifications(netCallback);
1263
1264     g_errorHandler = errorCallback;
1265
1266     CAConnectivityHandler_t connHandler;
1267     connHandler.startAdapter = CAStartLE;
1268     connHandler.stopAdapter = CAStopLE;
1269     connHandler.startListenServer = CAStartLEListeningServer;
1270     connHandler.startDiscoveryServer = CAStartLEDiscoveryServer;
1271     connHandler.sendData = CASendLEUnicastData;
1272     connHandler.sendDataToAll = CASendLEMulticastData;
1273     connHandler.GetnetInfo = CAGetLEInterfaceInformation;
1274     connHandler.readData = CAReadLEData;
1275     connHandler.terminate = CATerminateLE;
1276     registerCallback(connHandler, CA_ADAPTER_GATT_BTLE);
1277
1278     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1279
1280     return CA_STATUS_OK;
1281 }
1282
1283 CAResult_t CAStartLE()
1284 {
1285     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1286     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CAStartLE, not implemented");
1287     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1288     return CA_STATUS_OK;
1289 }
1290
1291 CAResult_t CAStopLE()
1292 {
1293     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1294 #ifndef SINGLE_THREAD
1295     CAStopLEQueues();
1296 #endif
1297
1298     ca_mutex_lock(g_bleIsServerMutex);
1299     if (true == g_isServer)
1300     {
1301         CAStopLEGattServer();
1302     }
1303     else
1304     {
1305         CAStopLEGattClient();
1306     }
1307     ca_mutex_unlock(g_bleIsServerMutex);
1308
1309     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1310
1311     return CA_STATUS_OK;
1312 }
1313
1314 void CATerminateLE()
1315 {
1316     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1317
1318     CASetLEReqRespServerCallback(NULL);
1319     CASetLEReqRespClientCallback(NULL);
1320     CALERegisterNetworkNotifications(NULL);
1321     CASetLEReqRespAdapterCallback(NULL);
1322     CATerminateLENetworkMonitor();
1323
1324     ca_mutex_lock(g_bleIsServerMutex);
1325     if (true == g_isServer)
1326     {
1327         CATerminateLEGattServer();
1328     }
1329     else
1330     {
1331         CATerminateLEGattClient();
1332     }
1333     ca_mutex_unlock(g_bleIsServerMutex);
1334
1335 #ifndef SINGLE_THREAD
1336     CATerminateLEQueues();
1337 #endif
1338     CATerminateLEAdapterMutex();
1339
1340     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1341 }
1342
1343 CAResult_t CAStartLEListeningServer()
1344 {
1345     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1346     CAResult_t result = CA_STATUS_OK;
1347 #ifndef SINGLE_THREAD
1348     result = CAInitLEServerQueues();
1349     if (CA_STATUS_OK != result)
1350     {
1351         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEServerQueues failed");
1352         return CA_STATUS_FAILED;
1353     }
1354 #endif
1355
1356     result = CAGetLEAdapterState();
1357     if (CA_ADAPTER_NOT_ENABLED == result)
1358     {
1359         gLeServerStatus = CA_LISTENING_SERVER;
1360         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Listen Server will be started once BT Adapter is enabled");
1361         return CA_STATUS_OK;
1362     }
1363
1364     if (CA_STATUS_FAILED == result)
1365     {
1366         OIC_LOG(ERROR, CALEADAPTER_TAG, "Bluetooth get state failed!");
1367         return CA_STATUS_FAILED;
1368     }
1369
1370     CAStartLEGattServer();
1371
1372     ca_mutex_lock(g_bleIsServerMutex);
1373     g_isServer = true;
1374     ca_mutex_unlock(g_bleIsServerMutex);
1375
1376     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1377     return CA_STATUS_OK;
1378 }
1379
1380 CAResult_t CAStartLEDiscoveryServer()
1381 {
1382     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1383     CAResult_t result = CA_STATUS_OK;
1384 #ifndef SINGLE_THREAD
1385     result = CAInitLEClientQueues();
1386     if (CA_STATUS_OK != result)
1387     {
1388         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEClientQueues failed");
1389         return CA_STATUS_FAILED;
1390     }
1391 #endif
1392     result = CAGetLEAdapterState();
1393     if (CA_ADAPTER_NOT_ENABLED == result)
1394     {
1395         gLeServerStatus = CA_DISCOVERY_SERVER;
1396         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Listen Server will be started once BT Adapter is enabled");
1397         return CA_STATUS_OK;
1398     }
1399
1400     if (CA_STATUS_FAILED == result)
1401     {
1402         OIC_LOG(ERROR, CALEADAPTER_TAG, "Bluetooth get state failed!");
1403         return CA_STATUS_FAILED;
1404     }
1405
1406     CAStartLEGattClient();
1407
1408     ca_mutex_lock(g_bleIsServerMutex);
1409     g_isServer = false;
1410     ca_mutex_unlock(g_bleIsServerMutex);
1411
1412     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1413     return CA_STATUS_OK;
1414 }
1415
1416 CAResult_t CAStartLENotifyServer()
1417 {
1418     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1419
1420     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1421     return CA_STATUS_OK;
1422 }
1423
1424 uint32_t CASendLENotification(const CAEndpoint_t *endpoint, const void *data,
1425                               uint32_t dataLen)
1426 {
1427     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1428
1429     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1430     return 0;
1431 }
1432
1433 CAResult_t CAReadLEData()
1434 {
1435     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1436 #ifdef SINGLE_THREAD
1437     CACheckLEData();
1438 #endif
1439     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1440     return CA_STATUS_OK;
1441 }
1442
1443 int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint, const void *data, uint32_t dataLen)
1444 {
1445     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1446
1447     //Input validation
1448     VERIFY_NON_NULL_RET(endpoint, CALEADAPTER_TAG, "Remote endpoint is null", -1);
1449     VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
1450
1451     CAResult_t result = CA_STATUS_FAILED;
1452
1453     ca_mutex_lock(g_bleIsServerMutex);
1454     if (true  == g_isServer)
1455     {
1456         result = CALEAdapterServerSendData(endpoint, data, dataLen);
1457         if (CA_STATUS_OK != result)
1458         {
1459             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data failed\n");
1460             if (g_errorHandler)
1461             {
1462                 g_errorHandler((void *) endpoint, (void *) data, dataLen, result);
1463             }
1464             ca_mutex_unlock(g_bleIsServerMutex);
1465             return -1;
1466         }
1467     }
1468     else
1469     {
1470         result = CALEAdapterClientSendData(endpoint, data, dataLen);
1471         if (CA_STATUS_OK != result)
1472         {
1473             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data failed \n");
1474             if (g_errorHandler)
1475             {
1476                 g_errorHandler(endpoint, data, dataLen, result);
1477             }
1478             ca_mutex_unlock(g_bleIsServerMutex);
1479             return -1;
1480         }
1481     }
1482     ca_mutex_unlock(g_bleIsServerMutex);
1483
1484     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1485     return dataLen;
1486 }
1487
1488 int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint, const void *data, uint32_t dataLen)
1489 {
1490     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1491
1492     //Input validation
1493     VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
1494
1495     if (0 >= dataLen)
1496     {
1497         OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid Parameter");
1498         return -1;
1499     }
1500
1501     CAResult_t result = CA_STATUS_FAILED;
1502
1503     ca_mutex_lock(g_bleIsServerMutex);
1504     if (true  == g_isServer)
1505     {
1506         result = CALEAdapterServerSendData(NULL, data, dataLen);
1507         if (CA_STATUS_OK != result)
1508         {
1509             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send multicast data failed" );
1510
1511             ca_mutex_unlock(g_bleIsServerMutex);
1512             if (g_errorHandler)
1513             {
1514                 g_errorHandler(endpoint, data, dataLen, result);
1515             }
1516             return -1;
1517         }
1518     }
1519     else
1520     {
1521         result = CALEAdapterClientSendData(NULL, data, dataLen);
1522         if (CA_STATUS_OK != result)
1523         {
1524             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send Multicast data failed" );
1525             if (g_errorHandler)
1526             {
1527                 g_errorHandler(endpoint, data, dataLen, result);
1528             }
1529             ca_mutex_unlock(g_bleIsServerMutex);
1530             return -1;
1531         }
1532     }
1533     ca_mutex_unlock(g_bleIsServerMutex);
1534
1535     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1536     return dataLen;
1537 }
1538
1539 CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1540 {
1541     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1542
1543     VERIFY_NON_NULL(info, CALEADAPTER_TAG, "CALocalConnectivity info is null");
1544
1545     char *local_address = NULL;
1546
1547     CAResult_t res = CAGetLEAddress(&local_address);
1548     if (CA_STATUS_OK != res)
1549     {
1550         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAGetLEAddress has failed");
1551         return res;
1552     }
1553
1554     if (NULL == local_address)
1555     {
1556         OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is NULL");
1557         return CA_STATUS_FAILED;
1558     }
1559
1560     *size = 0;
1561     (*info) = (CAEndpoint_t *) OICCalloc(1, sizeof(CAEndpoint_t));
1562     if (NULL == (*info))
1563     {
1564         OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failure!");
1565         OICFree(local_address);
1566         return CA_STATUS_FAILED;
1567     }
1568
1569     size_t local_address_len = strlen(local_address);
1570
1571     if(local_address_len >= sizeof(g_localBLEAddress) ||
1572             local_address_len >= MAX_ADDR_STR_SIZE_CA - 1)
1573     {
1574         OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is too long");
1575         OICFree(*info);
1576         OICFree(local_address);
1577         return CA_STATUS_FAILED;
1578     }
1579
1580     OICStrcpy((*info)->addr, sizeof((*info)->addr), local_address);
1581     ca_mutex_lock(g_bleLocalAddressMutex);
1582     OICStrcpy(g_localBLEAddress, sizeof(g_localBLEAddress), local_address);
1583     ca_mutex_unlock(g_bleLocalAddressMutex);
1584
1585     (*info)->adapter = CA_ADAPTER_GATT_BTLE;
1586     *size = 1;
1587     OICFree(local_address);
1588
1589     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1590     return CA_STATUS_OK;
1591 }
1592
1593 CAResult_t CALERegisterNetworkNotifications(CANetworkChangeCallback netCallback)
1594 {
1595     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1596
1597     ca_mutex_lock(g_bleNetworkCbMutex);
1598     g_networkCallback = netCallback;
1599     ca_mutex_unlock(g_bleNetworkCbMutex);
1600     CAResult_t res = CA_STATUS_OK;
1601     if (netCallback)
1602     {
1603         res = CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCb);
1604         if (CA_STATUS_OK != res)
1605         {
1606             OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
1607         }
1608     }
1609     else
1610     {
1611         res = CAUnSetLEAdapterStateChangedCb();
1612         if (CA_STATUS_OK != res)
1613         {
1614             OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
1615         }
1616     }
1617
1618     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1619     return res;
1620 }
1621
1622 void CALEDeviceStateChangedCb( CAAdapterState_t adapter_state)
1623 {
1624     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1625
1626     VERIFY_NON_NULL_VOID(g_localBLEAddress, CALEADAPTER_TAG, "g_localBLEAddress is null");
1627     CAEndpoint_t localEndpoint = {};
1628
1629     ca_mutex_lock(g_bleLocalAddressMutex);
1630     OICStrcpy(localEndpoint.addr, sizeof(localEndpoint.addr), g_localBLEAddress);
1631     ca_mutex_unlock(g_bleLocalAddressMutex);
1632
1633     g_bleAdapterState = adapter_state;
1634     // Start a GattServer/Client if gLeServerStatus is SET
1635     if (CA_LISTENING_SERVER == gLeServerStatus)
1636     {
1637         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Before CAStartLEGattServer");
1638         CAStartLEGattServer();
1639     }
1640     else if (CA_DISCOVERY_SERVER == gLeServerStatus)
1641     {
1642         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Before CAStartBleGattClient");
1643         CAStartLEGattClient();
1644     }
1645     gLeServerStatus = CA_SERVER_NOTSTARTED;
1646
1647     ca_mutex_lock(g_bleNetworkCbMutex);
1648     if (NULL != g_networkCallback)
1649     {
1650         g_networkCallback(&localEndpoint, adapter_state);
1651     }
1652     else
1653     {
1654         OIC_LOG(ERROR, CALEADAPTER_TAG, "g_networkCallback is NULL");
1655     }
1656     ca_mutex_unlock(g_bleNetworkCbMutex);
1657
1658     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1659 }
1660
1661 CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
1662                                      const void *data,
1663                                      uint32_t dataLen)
1664 {
1665     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1666
1667     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
1668 #ifndef SINGLE_THREAD
1669     VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG,
1670                         "g_bleClientSendQueueHandle is  NULL",
1671                         CA_STATUS_FAILED);
1672     VERIFY_NON_NULL_RET(g_bleClientSendDataMutex, CALEADAPTER_TAG,
1673                         "g_bleClientSendDataMutex is NULL",
1674                         CA_STATUS_FAILED);
1675
1676     VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG, "g_bleClientSendQueueHandle",
1677                         CA_STATUS_FAILED);
1678
1679     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%d]", dataLen);
1680
1681     CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLen);
1682     if (!bleData)
1683     {
1684         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
1685         return CA_MEMORY_ALLOC_FAILED;
1686     }
1687     // Add message to send queue
1688     ca_mutex_lock(g_bleClientSendDataMutex);
1689     CAQueueingThreadAddData(g_bleClientSendQueueHandle, bleData, sizeof(CALEData_t));
1690     ca_mutex_unlock(g_bleClientSendDataMutex);
1691 #endif
1692     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1693     return CA_STATUS_OK;
1694 }
1695
1696
1697 CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
1698                                      const void *data,
1699                                      uint32_t dataLen)
1700 {
1701     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1702
1703     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
1704
1705 #ifdef SINGLE_THREAD
1706     char header[CA_HEADER_LENGTH] = {0};
1707
1708     CAResult_t result = CAGenerateHeader(header, dataLen);
1709
1710     if (CA_STATUS_OK != result)
1711     {
1712         OIC_LOG(ERROR, CALEADAPTER_TAG, "Generate header failed");
1713         return -1;
1714     }
1715
1716     if (!CAIsLEConnected())
1717     {
1718         OIC_LOG(ERROR, CALEADAPTER_TAG, "le not conn");
1719         return -1;
1720     }
1721
1722     result = CAUpdateCharacteristicsToAllGattClients(header, CA_HEADER_LENGTH);
1723     if (CA_STATUS_OK != result)
1724     {
1725         OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
1726         return -1;
1727     }
1728
1729     int32_t dataLimit = dataLen / CA_SUPPORTED_BLE_MTU_SIZE;
1730     for (int32_t iter = 0; iter < dataLimit; iter++)
1731     {
1732         result = CAUpdateCharacteristicsToAllGattClients((data +
1733                                                          (iter * CA_SUPPORTED_BLE_MTU_SIZE)),
1734                                                          CA_SUPPORTED_BLE_MTU_SIZE);
1735         if (CA_STATUS_OK != result)
1736         {
1737             OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
1738             return -1;
1739         }
1740         CALEDoEvents();
1741     }
1742
1743     uint8_t remainingLen = dataLen % CA_SUPPORTED_BLE_MTU_SIZE;
1744     if(remainingLen)
1745     {
1746         result = CAUpdateCharacteristicsToAllGattClients((data +
1747                                                          (dataLimit * CA_SUPPORTED_BLE_MTU_SIZE)),
1748                                                          remainingLen);
1749         if (CA_STATUS_OK != result)
1750         {
1751             OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
1752             return -1;
1753         }
1754         CALEDoEvents();
1755     }
1756 #else
1757     VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG,
1758                         "BleClientReceiverQueue is NULL",
1759                         CA_STATUS_FAILED);
1760     VERIFY_NON_NULL_RET(g_bleServerSendDataMutex, CALEADAPTER_TAG,
1761                         "BleClientSendDataMutex is NULL",
1762                         CA_STATUS_FAILED);
1763
1764     VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG, "sendQueueHandle",
1765                         CA_STATUS_FAILED);
1766
1767     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%d]", dataLen);
1768
1769     CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLen);
1770     if (!bleData)
1771     {
1772         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
1773         return CA_MEMORY_ALLOC_FAILED;
1774     }
1775     // Add message to send queue
1776     ca_mutex_lock(g_bleServerSendDataMutex);
1777     CAQueueingThreadAddData(g_bleServerSendQueueHandle, bleData, sizeof(CALEData_t));
1778     ca_mutex_unlock(g_bleServerSendDataMutex);
1779 #endif
1780     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1781     return CA_STATUS_OK;
1782 }
1783
1784 CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress, const char *serviceUUID,
1785                                          const void *data, uint32_t dataLength,
1786                                          uint32_t *sentLength)
1787 {
1788     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1789
1790     //Input validation
1791     VERIFY_NON_NULL(serviceUUID, CALEADAPTER_TAG, "service UUID is null");
1792     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
1793     VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
1794
1795 #ifdef SINGLE_THREAD
1796     if(g_networkPacketReceivedCallback)
1797     {
1798         CAEndpoint_t endPoint = { 0 };   // will be filled by upper layer
1799         endPoint.adapter = CA_ADAPTER_GATT_BTLE;
1800         g_networkPacketReceivedCallback(&endPoint, data, dataLength);
1801     }
1802 #else
1803     VERIFY_NON_NULL_RET(g_bleReceiverQueue, CALEADAPTER_TAG, "g_bleReceiverQueue",
1804                         CA_STATUS_FAILED);
1805
1806     //Add message to data queue
1807     CAEndpoint_t *remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
1808                                                           CA_ADAPTER_GATT_BTLE,
1809                                                           remoteAddress, 0);
1810     if (NULL == remoteEndpoint)
1811     {
1812         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
1813         return CA_STATUS_FAILED;
1814     }
1815
1816     // Create bleData to add to queue
1817     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data received from LE layer [%d]", dataLength);
1818
1819     CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLength);
1820     if (!bleData)
1821     {
1822         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
1823         CAFreeEndpoint(remoteEndpoint);
1824         return CA_MEMORY_ALLOC_FAILED;
1825     }
1826
1827     CAFreeEndpoint(remoteEndpoint);
1828     // Add message to send queue
1829     CAQueueingThreadAddData(g_bleReceiverQueue, bleData, sizeof(CALEData_t));
1830
1831     *sentLength = dataLength;
1832 #endif
1833     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1834     return CA_STATUS_OK;
1835 }
1836
1837 CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress, const char *serviceUUID,
1838                                          const void *data, uint32_t dataLength,
1839                                          uint32_t *sentLength)
1840 {
1841     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1842
1843     //Input validation
1844     VERIFY_NON_NULL(serviceUUID, CALEADAPTER_TAG, "service UUID is null");
1845     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
1846     VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
1847 #ifndef SINGLE_THREAD
1848     VERIFY_NON_NULL_RET(g_bleReceiverQueue, CALEADAPTER_TAG, "g_bleReceiverQueue",
1849                         CA_STATUS_FAILED);
1850
1851     //Add message to data queue
1852     CAEndpoint_t *remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
1853                                                           CA_ADAPTER_GATT_BTLE,
1854                                                           remoteAddress, 0);
1855     if (NULL == remoteEndpoint)
1856     {
1857         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
1858         return CA_STATUS_FAILED;
1859     }
1860
1861     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data received from LE layer [%d]", dataLength);
1862
1863     // Create bleData to add to queue
1864     CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLength);
1865     if (!bleData)
1866     {
1867         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
1868         CAFreeEndpoint(remoteEndpoint);
1869         return CA_MEMORY_ALLOC_FAILED;
1870     }
1871
1872     CAFreeEndpoint(remoteEndpoint);
1873     // Add message to send queue
1874     CAQueueingThreadAddData(g_bleReceiverQueue, bleData, sizeof(CALEData_t));
1875
1876     *sentLength = dataLength;
1877 #endif
1878     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1879     return CA_STATUS_OK;
1880 }
1881
1882 void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle)
1883 {
1884     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1885
1886     ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
1887     g_bleAdapterThreadPool = handle;
1888     ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
1889
1890     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1891 }
1892
1893 void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback)
1894 {
1895     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1896
1897     ca_mutex_lock(g_bleAdapterReqRespCbMutex);
1898
1899     g_networkPacketReceivedCallback = callback;
1900
1901     ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
1902
1903     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1904 }
1905
1906 void CALEErrorHandler(const char *remoteAddress, const void *data, uint32_t dataLen,
1907                       CAResult_t result)
1908 {
1909     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEErrorHandler IN");
1910
1911     VERIFY_NON_NULL_VOID(data, CALEADAPTER_TAG, "Data is null");
1912     CAEndpoint_t *rep = CACreateEndpointObject(CA_DEFAULT_FLAGS, CA_ADAPTER_GATT_BTLE,
1913                                                remoteAddress, 0);
1914     //if required, will be used to build remote end point
1915     g_errorHandler(rep, data, dataLen, result);
1916
1917     CAFreeEndpoint(rep);
1918     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEErrorHandler OUT");
1919 }