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