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