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