Merge branch 'master' into resource-manipulation
[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             return CA_STATUS_FAILED;
1150         }
1151     }
1152
1153     if (NULL == g_bleLocalAddressMutex)
1154     {
1155         g_bleLocalAddressMutex = ca_mutex_new();
1156         if (NULL == g_bleLocalAddressMutex)
1157         {
1158             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1159             return CA_STATUS_FAILED;
1160         }
1161     }
1162
1163     if (NULL == g_bleAdapterThreadPoolMutex)
1164     {
1165         g_bleAdapterThreadPoolMutex = ca_mutex_new();
1166         if (NULL == g_bleAdapterThreadPoolMutex)
1167         {
1168             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1169             return CA_STATUS_FAILED;
1170         }
1171     }
1172
1173     if (NULL == g_bleClientSendDataMutex)
1174     {
1175         g_bleClientSendDataMutex = ca_mutex_new();
1176         if (NULL == g_bleClientSendDataMutex)
1177         {
1178             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1179             return CA_STATUS_FAILED;
1180         }
1181     }
1182
1183     if (NULL == g_bleClientReceiveDataMutex)
1184     {
1185         g_bleClientReceiveDataMutex = ca_mutex_new();
1186         if (NULL == g_bleClientReceiveDataMutex)
1187         {
1188             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1189             return CA_STATUS_FAILED;
1190         }
1191     }
1192
1193     if (NULL == g_bleServerSendDataMutex)
1194     {
1195         g_bleServerSendDataMutex = ca_mutex_new();
1196         if (NULL == g_bleServerSendDataMutex)
1197         {
1198             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1199             return CA_STATUS_FAILED;
1200         }
1201     }
1202
1203     if (NULL == g_bleServerReceiveDataMutex)
1204     {
1205         g_bleServerReceiveDataMutex = ca_mutex_new();
1206         if (NULL == g_bleServerReceiveDataMutex)
1207         {
1208             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1209             return CA_STATUS_FAILED;
1210         }
1211     }
1212
1213     if (NULL == g_bleAdapterReqRespCbMutex)
1214     {
1215         g_bleAdapterReqRespCbMutex = ca_mutex_new();
1216         if (NULL == g_bleAdapterReqRespCbMutex)
1217         {
1218             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
1219             return CA_STATUS_FAILED;
1220         }
1221     }
1222
1223     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1224     return CA_STATUS_OK;
1225 }
1226
1227 void CATerminateLEAdapterMutex()
1228 {
1229     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1230
1231     ca_mutex_free(g_bleIsServerMutex);
1232     g_bleIsServerMutex = NULL;
1233
1234     ca_mutex_free(g_bleNetworkCbMutex);
1235     g_bleNetworkCbMutex = NULL;
1236
1237     ca_mutex_free(g_bleLocalAddressMutex);
1238     g_bleLocalAddressMutex = NULL;
1239
1240     ca_mutex_free(g_bleAdapterThreadPoolMutex);
1241     g_bleAdapterThreadPoolMutex = NULL;
1242
1243     ca_mutex_free(g_bleClientSendDataMutex);
1244     g_bleClientSendDataMutex = NULL;
1245
1246     ca_mutex_free(g_bleClientReceiveDataMutex);
1247     g_bleClientReceiveDataMutex = NULL;
1248
1249     ca_mutex_free(g_bleServerSendDataMutex);
1250     g_bleServerSendDataMutex = NULL;
1251
1252     ca_mutex_free(g_bleServerReceiveDataMutex);
1253     g_bleServerReceiveDataMutex = NULL;
1254
1255     ca_mutex_free(g_bleAdapterReqRespCbMutex);
1256     g_bleAdapterReqRespCbMutex = NULL;
1257
1258     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1259 }
1260
1261 CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
1262                           CANetworkPacketReceivedCallback reqRespCallback,
1263                           CANetworkChangeCallback netCallback,
1264                           CAErrorHandleCallback errorCallback, ca_thread_pool_t handle)
1265 {
1266     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1267
1268     //Input validation
1269     VERIFY_NON_NULL(registerCallback, CALEADAPTER_TAG, "RegisterConnectivity callback is null");
1270     VERIFY_NON_NULL(reqRespCallback, CALEADAPTER_TAG, "PacketReceived Callback is null");
1271     VERIFY_NON_NULL(netCallback, CALEADAPTER_TAG, "NetworkChange Callback is null");
1272
1273     CAResult_t result = CA_STATUS_OK;
1274     result = CAInitLEAdapterMutex();
1275     if (CA_STATUS_OK != result)
1276     {
1277         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleAdapterMutex failed!");
1278         return CA_STATUS_FAILED;
1279     }
1280     result = CAInitializeLENetworkMonitor();
1281     if (CA_STATUS_OK != result)
1282     {
1283         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLENetworkMonitor() failed");
1284         return CA_STATUS_FAILED;
1285     }
1286
1287     CAInitializeLEAdapter();
1288
1289     CASetLEClientThreadPoolHandle(handle);
1290     CASetLEReqRespClientCallback(CALEAdapterClientReceivedData);
1291     CASetLEServerThreadPoolHandle(handle);
1292     CASetLEAdapterThreadPoolHandle(handle);
1293     CASetLEReqRespServerCallback(CALEAdapterServerReceivedData);
1294     CASetLEReqRespAdapterCallback(reqRespCallback);
1295
1296     CASetBLEClientErrorHandleCallback(CALEErrorHandler);
1297     CASetBLEServerErrorHandleCallback(CALEErrorHandler);
1298     CALERegisterNetworkNotifications(netCallback);
1299
1300     g_errorHandler = errorCallback;
1301
1302     CAConnectivityHandler_t connHandler;
1303     connHandler.startAdapter = CAStartLE;
1304     connHandler.stopAdapter = CAStopLE;
1305     connHandler.startListenServer = CAStartLEListeningServer;
1306     connHandler.startDiscoveryServer = CAStartLEDiscoveryServer;
1307     connHandler.sendData = CASendLEUnicastData;
1308     connHandler.sendDataToAll = CASendLEMulticastData;
1309     connHandler.GetnetInfo = CAGetLEInterfaceInformation;
1310     connHandler.readData = CAReadLEData;
1311     connHandler.terminate = CATerminateLE;
1312     registerCallback(connHandler, CA_ADAPTER_GATT_BTLE);
1313
1314     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1315
1316     return CA_STATUS_OK;
1317 }
1318
1319 CAResult_t CAStartLE()
1320 {
1321     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1322     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CAStartLE, not implemented");
1323     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1324     return CA_STATUS_OK;
1325 }
1326
1327 CAResult_t CAStopLE()
1328 {
1329     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1330 #ifndef SINGLE_THREAD
1331     CAStopLEQueues();
1332 #endif
1333
1334     ca_mutex_lock(g_bleIsServerMutex);
1335     if (true == g_isServer)
1336     {
1337         CAStopLEGattServer();
1338     }
1339     else
1340     {
1341         CAStopLEGattClient();
1342     }
1343     ca_mutex_unlock(g_bleIsServerMutex);
1344
1345     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1346
1347     return CA_STATUS_OK;
1348 }
1349
1350 void CATerminateLE()
1351 {
1352     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1353
1354     CASetLEReqRespServerCallback(NULL);
1355     CASetLEReqRespClientCallback(NULL);
1356     CALERegisterNetworkNotifications(NULL);
1357     CASetLEReqRespAdapterCallback(NULL);
1358     CATerminateLENetworkMonitor();
1359
1360     ca_mutex_lock(g_bleIsServerMutex);
1361     if (true == g_isServer)
1362     {
1363         CATerminateLEGattServer();
1364     }
1365     else
1366     {
1367         CATerminateLEGattClient();
1368     }
1369     ca_mutex_unlock(g_bleIsServerMutex);
1370
1371 #ifndef SINGLE_THREAD
1372     CATerminateLEQueues();
1373 #endif
1374     CATerminateLEAdapterMutex();
1375
1376     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1377 }
1378
1379 CAResult_t CAStartLEListeningServer()
1380 {
1381     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1382     CAResult_t result = CA_STATUS_OK;
1383 #ifndef SINGLE_THREAD
1384     result = CAInitLEServerQueues();
1385     if (CA_STATUS_OK != result)
1386     {
1387         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEServerQueues failed");
1388         return CA_STATUS_FAILED;
1389     }
1390 #endif
1391
1392     result = CAGetLEAdapterState();
1393     if (CA_ADAPTER_NOT_ENABLED == result)
1394     {
1395         gLeServerStatus = CA_LISTENING_SERVER;
1396         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Listen Server will be started once BT Adapter is enabled");
1397         return CA_STATUS_OK;
1398     }
1399
1400     if (CA_STATUS_FAILED == result)
1401     {
1402         OIC_LOG(ERROR, CALEADAPTER_TAG, "Bluetooth get state failed!");
1403         return CA_STATUS_FAILED;
1404     }
1405
1406     CAStartLEGattServer();
1407
1408     ca_mutex_lock(g_bleIsServerMutex);
1409     g_isServer = true;
1410     ca_mutex_unlock(g_bleIsServerMutex);
1411
1412     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1413     return CA_STATUS_OK;
1414 }
1415
1416 CAResult_t CAStartLEDiscoveryServer()
1417 {
1418     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1419     CAResult_t result = CA_STATUS_OK;
1420 #ifndef SINGLE_THREAD
1421     result = CAInitLEClientQueues();
1422     if (CA_STATUS_OK != result)
1423     {
1424         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitLEClientQueues failed");
1425         return CA_STATUS_FAILED;
1426     }
1427 #endif
1428     result = CAGetLEAdapterState();
1429     if (CA_ADAPTER_NOT_ENABLED == result)
1430     {
1431         gLeServerStatus = CA_DISCOVERY_SERVER;
1432         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Listen Server will be started once BT Adapter is enabled");
1433         return CA_STATUS_OK;
1434     }
1435
1436     if (CA_STATUS_FAILED == result)
1437     {
1438         OIC_LOG(ERROR, CALEADAPTER_TAG, "Bluetooth get state failed!");
1439         return CA_STATUS_FAILED;
1440     }
1441
1442     CAStartLEGattClient();
1443
1444     ca_mutex_lock(g_bleIsServerMutex);
1445     g_isServer = false;
1446     ca_mutex_unlock(g_bleIsServerMutex);
1447
1448     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1449     return CA_STATUS_OK;
1450 }
1451
1452 CAResult_t CAStartLENotifyServer()
1453 {
1454     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1455
1456     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1457     return CA_STATUS_OK;
1458 }
1459
1460 uint32_t CASendLENotification(const CAEndpoint_t *endpoint, const void *data,
1461                               uint32_t dataLen)
1462 {
1463     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1464
1465     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1466     return 0;
1467 }
1468
1469 CAResult_t CAReadLEData()
1470 {
1471     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1472 #ifdef SINGLE_THREAD
1473     CACheckLEData();
1474 #endif
1475     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1476     return CA_STATUS_OK;
1477 }
1478
1479 int32_t CASendLEUnicastData(const CAEndpoint_t *endpoint, const void *data, uint32_t dataLen)
1480 {
1481     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1482
1483     //Input validation
1484     VERIFY_NON_NULL_RET(endpoint, CALEADAPTER_TAG, "Remote endpoint is null", -1);
1485     VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
1486
1487     CAResult_t result = CA_STATUS_FAILED;
1488
1489     ca_mutex_lock(g_bleIsServerMutex);
1490     if (true  == g_isServer)
1491     {
1492         result = CALEAdapterServerSendData(endpoint, data, dataLen);
1493         if (CA_STATUS_OK != result)
1494         {
1495             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data failed\n");
1496             if (g_errorHandler)
1497             {
1498                 g_errorHandler((void *) endpoint, (void *) data, dataLen, result);
1499             }
1500             ca_mutex_unlock(g_bleIsServerMutex);
1501             return -1;
1502         }
1503     }
1504     else
1505     {
1506         result = CALEAdapterClientSendData(endpoint, data, dataLen);
1507         if (CA_STATUS_OK != result)
1508         {
1509             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send unicast data failed \n");
1510             if (g_errorHandler)
1511             {
1512                 g_errorHandler(endpoint, data, dataLen, result);
1513             }
1514             ca_mutex_unlock(g_bleIsServerMutex);
1515             return -1;
1516         }
1517     }
1518     ca_mutex_unlock(g_bleIsServerMutex);
1519
1520     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1521     return dataLen;
1522 }
1523
1524 int32_t CASendLEMulticastData(const CAEndpoint_t *endpoint, const void *data, uint32_t dataLen)
1525 {
1526     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1527
1528     //Input validation
1529     VERIFY_NON_NULL_RET(data, CALEADAPTER_TAG, "Data is null", -1);
1530
1531     if (0 >= dataLen)
1532     {
1533         OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid Parameter");
1534         return -1;
1535     }
1536
1537     CAResult_t result = CA_STATUS_FAILED;
1538
1539     ca_mutex_lock(g_bleIsServerMutex);
1540     if (true  == g_isServer)
1541     {
1542         result = CALEAdapterServerSendData(NULL, data, dataLen);
1543         if (CA_STATUS_OK != result)
1544         {
1545             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send multicast data failed" );
1546
1547             ca_mutex_unlock(g_bleIsServerMutex);
1548             if (g_errorHandler)
1549             {
1550                 g_errorHandler(endpoint, data, dataLen, result);
1551             }
1552             return -1;
1553         }
1554     }
1555     else
1556     {
1557         result = CALEAdapterClientSendData(NULL, data, dataLen);
1558         if (CA_STATUS_OK != result)
1559         {
1560             OIC_LOG(ERROR, CALEADAPTER_TAG, "Send Multicast data failed" );
1561             if (g_errorHandler)
1562             {
1563                 g_errorHandler(endpoint, data, dataLen, result);
1564             }
1565             ca_mutex_unlock(g_bleIsServerMutex);
1566             return -1;
1567         }
1568     }
1569     ca_mutex_unlock(g_bleIsServerMutex);
1570
1571     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1572     return dataLen;
1573 }
1574
1575 CAResult_t CAGetLEInterfaceInformation(CAEndpoint_t **info, uint32_t *size)
1576 {
1577     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1578
1579     VERIFY_NON_NULL(info, CALEADAPTER_TAG, "CALocalConnectivity info is null");
1580
1581     char *local_address = NULL;
1582
1583     CAResult_t res = CAGetLEAddress(&local_address);
1584     if (CA_STATUS_OK != res)
1585     {
1586         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAGetLEAddress has failed");
1587         return res;
1588     }
1589
1590     if (NULL == local_address)
1591     {
1592         OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is NULL");
1593         return CA_STATUS_FAILED;
1594     }
1595
1596     *size = 0;
1597     (*info) = (CAEndpoint_t *) OICCalloc(1, sizeof(CAEndpoint_t));
1598     if (NULL == (*info))
1599     {
1600         OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failure!");
1601         OICFree(local_address);
1602         return CA_STATUS_FAILED;
1603     }
1604
1605     size_t local_address_len = strlen(local_address);
1606
1607     if(local_address_len >= sizeof(g_localBLEAddress) ||
1608             local_address_len >= MAX_ADDR_STR_SIZE_CA - 1)
1609     {
1610         OIC_LOG(ERROR, CALEADAPTER_TAG, "local_address is too long");
1611         OICFree(*info);
1612         OICFree(local_address);
1613         return CA_STATUS_FAILED;
1614     }
1615
1616     OICStrcpy((*info)->addr, sizeof((*info)->addr), local_address);
1617     ca_mutex_lock(g_bleLocalAddressMutex);
1618     OICStrcpy(g_localBLEAddress, sizeof(g_localBLEAddress), local_address);
1619     ca_mutex_unlock(g_bleLocalAddressMutex);
1620
1621     (*info)->adapter = CA_ADAPTER_GATT_BTLE;
1622     *size = 1;
1623     OICFree(local_address);
1624
1625     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1626     return CA_STATUS_OK;
1627 }
1628
1629 CAResult_t CALERegisterNetworkNotifications(CANetworkChangeCallback netCallback)
1630 {
1631     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1632
1633     ca_mutex_lock(g_bleNetworkCbMutex);
1634     g_networkCallback = netCallback;
1635     ca_mutex_unlock(g_bleNetworkCbMutex);
1636     CAResult_t res = CA_STATUS_OK;
1637     if (netCallback)
1638     {
1639         res = CASetLEAdapterStateChangedCb(CALEDeviceStateChangedCb);
1640         if (CA_STATUS_OK != res)
1641         {
1642             OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
1643         }
1644     }
1645     else
1646     {
1647         res = CAUnSetLEAdapterStateChangedCb();
1648         if (CA_STATUS_OK != res)
1649         {
1650             OIC_LOG(ERROR, CALEADAPTER_TAG, "CASetLEAdapterStateChangedCb failed!");
1651         }
1652     }
1653
1654     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1655     return res;
1656 }
1657
1658 void CALEDeviceStateChangedCb( CAAdapterState_t adapter_state)
1659 {
1660     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1661
1662     VERIFY_NON_NULL_VOID(g_localBLEAddress, CALEADAPTER_TAG, "g_localBLEAddress is null");
1663     CAEndpoint_t localEndpoint = {};
1664
1665     ca_mutex_lock(g_bleLocalAddressMutex);
1666     OICStrcpy(localEndpoint.addr, sizeof(localEndpoint.addr), g_localBLEAddress);
1667     ca_mutex_unlock(g_bleLocalAddressMutex);
1668
1669     g_bleAdapterState = adapter_state;
1670     // Start a GattServer/Client if gLeServerStatus is SET
1671     if (CA_LISTENING_SERVER == gLeServerStatus)
1672     {
1673         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Before CAStartLEGattServer");
1674         CAStartLEGattServer();
1675     }
1676     else if (CA_DISCOVERY_SERVER == gLeServerStatus)
1677     {
1678         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Before CAStartBleGattClient");
1679         CAStartLEGattClient();
1680     }
1681     gLeServerStatus = CA_SERVER_NOTSTARTED;
1682
1683     ca_mutex_lock(g_bleNetworkCbMutex);
1684     if (NULL != g_networkCallback)
1685     {
1686         g_networkCallback(&localEndpoint, adapter_state);
1687     }
1688     else
1689     {
1690         OIC_LOG(ERROR, CALEADAPTER_TAG, "g_networkCallback is NULL");
1691     }
1692     ca_mutex_unlock(g_bleNetworkCbMutex);
1693
1694     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1695 }
1696
1697 CAResult_t CALEAdapterClientSendData(const CAEndpoint_t *remoteEndpoint,
1698                                      const void *data,
1699                                      uint32_t dataLen)
1700 {
1701     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1702
1703     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
1704 #ifndef SINGLE_THREAD
1705     VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG,
1706                         "g_bleClientSendQueueHandle is  NULL",
1707                         CA_STATUS_FAILED);
1708     VERIFY_NON_NULL_RET(g_bleClientSendDataMutex, CALEADAPTER_TAG,
1709                         "g_bleClientSendDataMutex is NULL",
1710                         CA_STATUS_FAILED);
1711
1712     VERIFY_NON_NULL_RET(g_bleClientSendQueueHandle, CALEADAPTER_TAG, "g_bleClientSendQueueHandle",
1713                         CA_STATUS_FAILED);
1714
1715     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%d]", dataLen);
1716
1717     CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLen);
1718     if (!bleData)
1719     {
1720         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
1721         return CA_MEMORY_ALLOC_FAILED;
1722     }
1723     // Add message to send queue
1724     ca_mutex_lock(g_bleClientSendDataMutex);
1725     CAQueueingThreadAddData(g_bleClientSendQueueHandle, bleData, sizeof(CALEData_t));
1726     ca_mutex_unlock(g_bleClientSendDataMutex);
1727 #endif
1728     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1729     return CA_STATUS_OK;
1730 }
1731
1732
1733 CAResult_t CALEAdapterServerSendData(const CAEndpoint_t *remoteEndpoint,
1734                                      const void *data,
1735                                      uint32_t dataLen)
1736 {
1737     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1738
1739     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Param data is NULL");
1740
1741 #ifdef SINGLE_THREAD
1742     char header[CA_HEADER_LENGTH] = {0};
1743
1744     CAResult_t result = CAGenerateHeader(header, dataLen);
1745
1746     if (CA_STATUS_OK != result)
1747     {
1748         OIC_LOG(ERROR, CALEADAPTER_TAG, "Generate header failed");
1749         return -1;
1750     }
1751
1752     if (!CAIsLEConnected())
1753     {
1754         OIC_LOG(ERROR, CALEADAPTER_TAG, "le not conn");
1755         return -1;
1756     }
1757
1758     result = CAUpdateCharacteristicsToAllGattClients(header, CA_HEADER_LENGTH);
1759     if (CA_STATUS_OK != result)
1760     {
1761         OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
1762         return -1;
1763     }
1764
1765     int32_t dataLimit = dataLen / CA_SUPPORTED_BLE_MTU_SIZE;
1766     for (int32_t iter = 0; iter < dataLimit; iter++)
1767     {
1768         result = CAUpdateCharacteristicsToAllGattClients((data +
1769                                                          (iter * CA_SUPPORTED_BLE_MTU_SIZE)),
1770                                                          CA_SUPPORTED_BLE_MTU_SIZE);
1771         if (CA_STATUS_OK != result)
1772         {
1773             OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
1774             return -1;
1775         }
1776         CALEDoEvents();
1777     }
1778
1779     uint8_t remainingLen = dataLen % CA_SUPPORTED_BLE_MTU_SIZE;
1780     if(remainingLen)
1781     {
1782         result = CAUpdateCharacteristicsToAllGattClients((data +
1783                                                          (dataLimit * CA_SUPPORTED_BLE_MTU_SIZE)),
1784                                                          remainingLen);
1785         if (CA_STATUS_OK != result)
1786         {
1787             OIC_LOG(ERROR, CALEADAPTER_TAG, "Update characteristics failed");
1788             return -1;
1789         }
1790         CALEDoEvents();
1791     }
1792 #else
1793     VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG,
1794                         "BleClientReceiverQueue is NULL",
1795                         CA_STATUS_FAILED);
1796     VERIFY_NON_NULL_RET(g_bleServerSendDataMutex, CALEADAPTER_TAG,
1797                         "BleClientSendDataMutex is NULL",
1798                         CA_STATUS_FAILED);
1799
1800     VERIFY_NON_NULL_RET(g_bleServerSendQueueHandle, CALEADAPTER_TAG, "sendQueueHandle",
1801                         CA_STATUS_FAILED);
1802
1803     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%d]", dataLen);
1804
1805     CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLen);
1806     if (!bleData)
1807     {
1808         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
1809         return CA_MEMORY_ALLOC_FAILED;
1810     }
1811     // Add message to send queue
1812     ca_mutex_lock(g_bleServerSendDataMutex);
1813     CAQueueingThreadAddData(g_bleServerSendQueueHandle, bleData, sizeof(CALEData_t));
1814     ca_mutex_unlock(g_bleServerSendDataMutex);
1815 #endif
1816     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1817     return CA_STATUS_OK;
1818 }
1819
1820 CAResult_t CALEAdapterServerReceivedData(const char *remoteAddress, const char *serviceUUID,
1821                                          const void *data, uint32_t dataLength,
1822                                          uint32_t *sentLength)
1823 {
1824     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1825
1826     //Input validation
1827     VERIFY_NON_NULL(serviceUUID, CALEADAPTER_TAG, "service UUID is null");
1828     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
1829     VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
1830
1831 #ifdef SINGLE_THREAD
1832     if(g_networkPacketReceivedCallback)
1833     {
1834         CAEndpoint_t endPoint = { 0 };   // will be filled by upper layer
1835         endPoint.adapter = CA_ADAPTER_GATT_BTLE;
1836         g_networkPacketReceivedCallback(&endPoint, data, dataLength);
1837     }
1838 #else
1839     VERIFY_NON_NULL_RET(g_bleServerReceiverQueue, CALEADAPTER_TAG, "g_bleServerReceiverQueue",
1840                         CA_STATUS_FAILED);
1841
1842     //Add message to data queue
1843     CAEndpoint_t *remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
1844                                                           CA_ADAPTER_GATT_BTLE,
1845                                                           remoteAddress, 0);
1846     if (NULL == remoteEndpoint)
1847     {
1848         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
1849         return CA_STATUS_FAILED;
1850     }
1851
1852     // Create bleData to add to queue
1853     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data received from LE layer [%d]", dataLength);
1854
1855     CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLength);
1856     if (!bleData)
1857     {
1858         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
1859         CAFreeEndpoint(remoteEndpoint);
1860         return CA_MEMORY_ALLOC_FAILED;
1861     }
1862
1863     CAFreeEndpoint(remoteEndpoint);
1864     // Add message to send queue
1865     CAQueueingThreadAddData(g_bleServerReceiverQueue, bleData, sizeof(CALEData_t));
1866
1867     *sentLength = dataLength;
1868 #endif
1869     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1870     return CA_STATUS_OK;
1871 }
1872
1873 CAResult_t CALEAdapterClientReceivedData(const char *remoteAddress, const char *serviceUUID,
1874                                          const void *data, uint32_t dataLength,
1875                                          uint32_t *sentLength)
1876 {
1877     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1878
1879     //Input validation
1880     VERIFY_NON_NULL(serviceUUID, CALEADAPTER_TAG, "service UUID is null");
1881     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
1882     VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
1883 #ifndef SINGLE_THREAD
1884     VERIFY_NON_NULL_RET(g_bleClientReceiverQueue, CALEADAPTER_TAG, "g_bleClientReceiverQueue",
1885                         CA_STATUS_FAILED);
1886
1887     //Add message to data queue
1888     CAEndpoint_t *remoteEndpoint = CACreateEndpointObject(CA_DEFAULT_FLAGS,
1889                                                           CA_ADAPTER_GATT_BTLE,
1890                                                           remoteAddress, 0);
1891     if (NULL == remoteEndpoint)
1892     {
1893         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
1894         return CA_STATUS_FAILED;
1895     }
1896
1897     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data received from LE layer [%d]", dataLength);
1898
1899     // Create bleData to add to queue
1900     CALEData_t *bleData = CACreateLEData(remoteEndpoint, data, dataLength);
1901     if (!bleData)
1902     {
1903         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
1904         CAFreeEndpoint(remoteEndpoint);
1905         return CA_MEMORY_ALLOC_FAILED;
1906     }
1907
1908     CAFreeEndpoint(remoteEndpoint);
1909     // Add message to send queue
1910     CAQueueingThreadAddData(g_bleClientReceiverQueue, bleData, sizeof(CALEData_t));
1911
1912     *sentLength = dataLength;
1913 #endif
1914     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1915     return CA_STATUS_OK;
1916 }
1917
1918 void CASetLEAdapterThreadPoolHandle(ca_thread_pool_t handle)
1919 {
1920     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1921
1922     ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
1923     g_bleAdapterThreadPool = handle;
1924     ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
1925
1926     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1927 }
1928
1929 void CASetLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback)
1930 {
1931     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1932
1933     ca_mutex_lock(g_bleAdapterReqRespCbMutex);
1934
1935     g_networkPacketReceivedCallback = callback;
1936
1937     ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
1938
1939     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1940 }
1941
1942 void CALEErrorHandler(const char *remoteAddress, const void *data, uint32_t dataLen,
1943                       CAResult_t result)
1944 {
1945     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEErrorHandler IN");
1946
1947     VERIFY_NON_NULL_VOID(data, CALEADAPTER_TAG, "Data is null");
1948     CAEndpoint_t *rep = CACreateEndpointObject(CA_DEFAULT_FLAGS, CA_ADAPTER_GATT_BTLE,
1949                                                remoteAddress, 0);
1950     //if required, will be used to build remote end point
1951     g_errorHandler(rep, data, dataLen, result);
1952
1953     CAFreeEndpoint(rep);
1954     OIC_LOG(DEBUG, CALEADAPTER_TAG, "CALEErrorHandler OUT");
1955 }