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