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