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