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