Replace glib threadpool usage with a 'dumb' thread implementation.
[platform/upstream/iotivity.git] / resource / csdk / connectivity / src / bt_le_adapter / caleadapter.c
1 /******************************************************************
2  *
3  * Copyright 2014 Samsung Electronics All Rights Reserved.
4  *
5  *
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  ******************************************************************/
20 #include "caleadapter.h"
21
22 #include <stdio.h>
23 #include <stdlib.h>
24
25 #include "caleinterface.h"
26 #include "cacommon.h"
27 #include "camutex.h"
28 #include "caadapterutils.h"
29 #include "caqueueingthread.h"
30 #include "camsgparser.h"
31 #include "oic_malloc.h"
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 g_networkCallback
41  * @brief Callback to provide the status of the network change to CA layer.
42  */
43 static CANetworkChangeCallback g_networkCallback = NULL;
44
45 /**
46  * @var g_localBLEAddress
47  * @brief bleAddress of the local adapter. Value will be initialized to zero, and will be updated later.
48  */
49 static char g_localBLEAddress[16] = { 0, };
50
51 /**
52  * @var g_isServer
53  * @brief Variable to differentiate btw GattServer and GattClient.
54  */
55 static bool g_isServer = false;
56
57 /**
58  * @var g_bleIsServerMutex
59  * @brief Mutex to synchronize the task to be executed on the GattServer function calls.
60  */
61 static ca_mutex g_bleIsServerMutex = NULL;
62
63 /**
64  * @var g_bleNetworkCbMutex
65  * @brief Mutex to synchronize the callback to be called for the network changes.
66  */
67 static ca_mutex g_bleNetworkCbMutex = NULL;
68
69 /**
70  * @var g_bleLocalAddressMutex
71  * @brief Mutex to synchronize the updation of the local LE address of the adapter.
72  */
73 static ca_mutex g_bleLocalAddressMutex = NULL;
74
75 /**
76  * @var gBleClientThreadPool
77  * @brief reference to threadpool
78  */
79 static ca_thread_pool_t g_bleAdapterThreadPool = NULL;
80
81 /**
82  * @var g_bleAdapterThreadPoolMutex
83  * @brief Mutex to synchronize the task to be pushed to thread pool.
84  */
85 static ca_mutex g_bleAdapterThreadPoolMutex = NULL;
86
87 /**
88  * @var g_bLEClientSendQueueHandle
89  * @brief Queue to process the outgoing packets from GATTClient.
90  */
91 static CAQueueingThread_t *g_bLEClientSendQueueHandle = NULL;
92
93 /**
94  * @var g_bleClientReceiverQueue
95  * @brief Queue to process the incoming packets to GATT Client.
96  */
97 static CAQueueingThread_t *g_bleClientReceiverQueue = NULL;
98
99 /**
100  * @var g_bleClientSendDataMutex
101  * @brief Mutex to synchronize the queing of the data from SenderQueue.
102  */
103 static ca_mutex g_bleClientSendDataMutex = NULL;
104
105
106 /**
107  * @var g_bleClientReceiveDataMutex
108  * @brief Mutex to synchronize the queing of the data from ReceiverQueue.
109  */
110 static ca_mutex g_bleClientReceiveDataMutex = NULL;
111
112 /**
113  * @var g_dataReceiverHandlerState
114  * @brief Stop condition of redvhandler.
115  */
116 static bool g_dataReceiverHandlerState = false;
117
118 /**
119  * @var g_sendQueueHandle
120  * @brief Queue to process the outgoing packets from GATTServer.
121  */
122 static CAQueueingThread_t *g_sendQueueHandle = NULL;
123
124 /**
125  * @var g_bleServerReceiverQueue
126  * @brief Queue to process the incoming packets to GATTServer
127  */
128 static CAQueueingThread_t *g_bleServerReceiverQueue = NULL;
129
130 /**
131  * @var g_bleServerSendDataMutex
132  * @brief Mutex to synchronize the queing of the data from SenderQueue.
133  */
134 static ca_mutex g_bleServerSendDataMutex = NULL;
135
136 /**
137  * @var g_bleServerReceiveDataMutex
138  * @brief Mutex to synchronize the queing of the data from ReceiverQueue.
139  */
140 static ca_mutex g_bleServerReceiveDataMutex = NULL;
141
142 /**
143  * @var g_bleAdapterReqRespCbMutex
144  * @brief Mutex to synchronize the callback to be called for the adapterReqResponse.
145  */
146 static ca_mutex g_bleAdapterReqRespCbMutex = NULL;
147
148 /**
149  * @var g_networkPacketReceivedCallback
150  * @brief Callback to be called when the network packet recieved from either GattServer or GattClient.
151  */
152 static CANetworkPacketReceivedCallback g_networkPacketReceivedCallback = 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(ca_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  CATerminateBleAdapterMutex
220 * @brief  Used to terminate all required mutex variable for LE adapter implementation.
221 *
222 * @return  void
223 *
224 */
225 void CATerminateBleAdapterMutex();
226 static void CALEDataDestroyer(void *data, uint32_t size);
227
228 CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback,
229                           CANetworkPacketReceivedCallback reqRespCallback,
230                           CANetworkChangeCallback netCallback,
231                           ca_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 = CAInitializeLENetworkMonitor();
248     if (CA_STATUS_OK != result)
249     {
250         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitializeLENetworkMonitor() 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.startDiscoveryServer = 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     ca_mutex_lock(g_bleIsServerMutex);
289     if (true == g_isServer)
290     {
291         CAStopBleGattServer();
292     }
293     else
294     {
295         CAStopBLEGattClient();
296     }
297     ca_mutex_unlock(g_bleIsServerMutex);
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     CATerminateLENetworkMonitor();
313
314     ca_mutex_lock(g_bleIsServerMutex);
315     if (true == g_isServer)
316     {
317         CATerminateBleGattServer();
318     }
319     else
320     {
321         CATerminateBLEGattClient();
322     }
323     ca_mutex_unlock(g_bleIsServerMutex);
324
325     CATerminateBleQueues();
326
327     CATerminateBleAdapterMutex();
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     ca_mutex_lock(g_bleIsServerMutex);
362     g_isServer = true;
363     ca_mutex_unlock(g_bleIsServerMutex);
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     ca_mutex_lock(g_bleIsServerMutex);
395     g_isServer = false;
396     ca_mutex_unlock(g_bleIsServerMutex);
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, const 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 int32_t CASendLEUnicastData(const CARemoteEndpoint_t *endpoint, const void *data, uint32_t dataLen)
427 {
428     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
429
430     //Input validation
431     VERIFY_NON_NULL_RET(endpoint, NULL, "Remote endpoint is null", -1);
432     VERIFY_NON_NULL_RET(data, NULL, "Data is null", -1);
433
434     CAResult_t result = CA_STATUS_FAILED;
435
436     ca_mutex_lock(g_bleIsServerMutex);
437     if (true  == g_isServer)
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             ca_mutex_unlock(g_bleIsServerMutex);
445             return -1;
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             ca_mutex_unlock(g_bleIsServerMutex);
456             return -1;
457         }
458     }
459     ca_mutex_unlock(g_bleIsServerMutex);
460
461     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
462     return dataLen;
463 }
464
465 int32_t CASendLEMulticastData(const void *data, uint32_t dataLen)
466 {
467     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
468
469     //Input validation
470     VERIFY_NON_NULL_RET(data, NULL, "Data is null", -1);
471
472     if (0 >= dataLen)
473     {
474         OIC_LOG(ERROR, CALEADAPTER_TAG, "Invalid Parameter");
475         return -1;
476     }
477
478     CAResult_t result = CA_STATUS_FAILED;
479
480     ca_mutex_lock(g_bleIsServerMutex);
481     if (true  == g_isServer)
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             ca_mutex_unlock(g_bleIsServerMutex);
489             return -1;
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             ca_mutex_unlock(g_bleIsServerMutex);
500             return -1;
501         }
502     }
503     ca_mutex_unlock(g_bleIsServerMutex);
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 *) OICCalloc(1, sizeof(CALocalConnectivity_t));
526     if (NULL == (*info))
527     {
528         OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failure!");
529         return CA_STATUS_FAILED;
530     }
531
532     strncpy((*info)->addressInfo.BT.btMacAddress, local_address, strlen(local_address));
533     ca_mutex_lock(g_bleLocalAddressMutex);
534     strncpy(g_localBLEAddress, local_address, sizeof(g_localBLEAddress));
535     ca_mutex_unlock(g_bleLocalAddressMutex);
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     ca_mutex_lock(g_bleNetworkCbMutex);
550     g_networkCallback = netCallback;
551     ca_mutex_unlock(g_bleNetworkCbMutex);
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     ca_mutex_lock(g_bleLocalAddressMutex);
581     strncpy(localEndpoint.addressInfo.BT.btMacAddress, g_localBLEAddress, strlen(g_localBLEAddress));
582     ca_mutex_unlock(g_bleLocalAddressMutex);
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     ca_mutex_lock(g_bleNetworkCbMutex);
598     if (NULL != g_networkCallback)
599     {
600         g_networkCallback(&localEndpoint, adapter_state);
601     }
602     else
603     {
604         OIC_LOG(ERROR, CALEADAPTER_TAG, "g_networkCallback is NULL");
605     }
606     ca_mutex_unlock(g_bleNetworkCbMutex);
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     if (NULL == g_bleIsServerMutex)
617     {
618         g_bleIsServerMutex = ca_mutex_new();
619         if (NULL == g_bleIsServerMutex)
620         {
621             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
622             return CA_STATUS_FAILED;
623         }
624     }
625
626     if (NULL == g_bleNetworkCbMutex)
627     {
628         g_bleNetworkCbMutex = ca_mutex_new();
629         if (NULL == g_bleNetworkCbMutex)
630         {
631             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
632             return CA_STATUS_FAILED;
633         }
634     }
635
636     if (NULL == g_bleLocalAddressMutex)
637     {
638         g_bleLocalAddressMutex = ca_mutex_new();
639         if (NULL == g_bleLocalAddressMutex)
640         {
641             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
642             return CA_STATUS_FAILED;
643         }
644     }
645
646     if (NULL == g_bleAdapterThreadPoolMutex)
647     {
648         g_bleAdapterThreadPoolMutex = ca_mutex_new();
649         if (NULL == g_bleAdapterThreadPoolMutex)
650         {
651             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
652             return CA_STATUS_FAILED;
653         }
654     }
655
656     if (NULL == g_bleClientSendDataMutex)
657     {
658         g_bleClientSendDataMutex = ca_mutex_new();
659         if (NULL == g_bleClientSendDataMutex)
660         {
661             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
662             return CA_STATUS_FAILED;
663         }
664     }
665
666     if (NULL == g_bleClientReceiveDataMutex)
667     {
668         g_bleClientReceiveDataMutex = ca_mutex_new();
669         if (NULL == g_bleClientReceiveDataMutex)
670         {
671             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
672             return CA_STATUS_FAILED;
673         }
674     }
675
676     if (NULL == g_bleServerSendDataMutex)
677     {
678         g_bleServerSendDataMutex = ca_mutex_new();
679         if (NULL == g_bleServerSendDataMutex)
680         {
681             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
682             return CA_STATUS_FAILED;
683         }
684     }
685
686     if (NULL == g_bleServerReceiveDataMutex)
687     {
688         g_bleServerReceiveDataMutex = ca_mutex_new();
689         if (NULL == g_bleServerReceiveDataMutex)
690         {
691             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
692             return CA_STATUS_FAILED;
693         }
694     }
695
696     if (NULL == g_bleAdapterReqRespCbMutex)
697     {
698         g_bleAdapterReqRespCbMutex = ca_mutex_new();
699         if (NULL == g_bleAdapterReqRespCbMutex)
700         {
701             OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_mutex_new failed");
702             return CA_STATUS_FAILED;
703         }
704     }
705
706     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
707     return CA_STATUS_OK;
708 }
709
710 void CATerminateBleAdapterMutex()
711 {
712     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
713
714     ca_mutex_free(g_bleIsServerMutex);
715     g_bleIsServerMutex = NULL;
716
717     ca_mutex_free(g_bleNetworkCbMutex);
718     g_bleNetworkCbMutex = NULL;
719
720     ca_mutex_free(g_bleLocalAddressMutex);
721     g_bleLocalAddressMutex = NULL;
722
723     ca_mutex_free(g_bleAdapterThreadPoolMutex);
724     g_bleAdapterThreadPoolMutex = NULL;
725
726     ca_mutex_free(g_bleClientSendDataMutex);
727     g_bleClientSendDataMutex = NULL;
728
729     ca_mutex_free(g_bleClientReceiveDataMutex);
730     g_bleClientReceiveDataMutex = NULL;
731
732     ca_mutex_free(g_bleServerSendDataMutex);
733     g_bleServerSendDataMutex = NULL;
734
735     ca_mutex_free(g_bleServerReceiveDataMutex);
736     g_bleServerReceiveDataMutex = NULL;
737
738     ca_mutex_free(g_bleAdapterReqRespCbMutex);
739     g_bleAdapterReqRespCbMutex = NULL;
740
741     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
742     return;
743 }
744
745 void CAInitBleQueues()
746 {
747     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
748
749     CAResult_t result = CAInitBleServerQueues();
750     if (CA_STATUS_OK != result)
751     {
752         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleServerQueues failed");
753         return;
754     }
755
756     result = CAInitBleClientQueues();
757     if (CA_STATUS_OK != result)
758     {
759         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientQueues failed");
760         return;
761     }
762
763     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
764     return;
765 }
766
767 CAResult_t CAInitBleServerQueues()
768 {
769     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
770
771     ca_mutex_lock(g_bleAdapterThreadPoolMutex);
772
773     CAResult_t result = CAInitBleServerSenderQueue();
774     if (CA_STATUS_OK != result)
775     {
776         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleServerSenderQueue failed");
777         ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
778         return CA_STATUS_FAILED;
779     }
780
781     result = CAInitBleServerReceiverQueue();
782     if (CA_STATUS_OK != result)
783     {
784         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleServerReceiverQueue failed");
785         ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
786         return CA_STATUS_FAILED;
787     }
788
789     g_dataReceiverHandlerState = true;
790
791     ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
792
793     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
794     return CA_STATUS_OK;
795 }
796
797 CAResult_t CAInitBleClientQueues()
798 {
799     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
800
801     ca_mutex_lock(g_bleAdapterThreadPoolMutex);
802
803     CAResult_t result = CAInitBleClientSenderQueue();
804     if (CA_STATUS_OK != result)
805     {
806         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientSenderQueue failed");
807         ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
808         return CA_STATUS_FAILED;
809     }
810
811     result = CAInitBleClientReceiverQueue();
812     if (CA_STATUS_OK != result)
813     {
814         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAInitBleClientReceiverQueue failed");
815         ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
816         return CA_STATUS_FAILED;
817     }
818
819     g_dataReceiverHandlerState = true;
820
821     ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
822
823     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
824     return CA_STATUS_OK;
825 }
826
827 CAResult_t CAInitBleServerSenderQueue()
828 {
829     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
830     // Check if the message queue is already initialized
831     if (g_sendQueueHandle)
832     {
833         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Queue is already initialized!");
834         return CA_STATUS_OK;
835     }
836
837     // Create send message queue
838     g_sendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
839     if (!g_sendQueueHandle)
840     {
841         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
842         return CA_MEMORY_ALLOC_FAILED;
843     }
844
845     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_sendQueueHandle, g_bleAdapterThreadPool,
846             CABLEServerSendDataThread, CALEDataDestroyer))
847     {
848         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
849         OICFree(g_sendQueueHandle);
850         g_sendQueueHandle = NULL;
851         return CA_STATUS_FAILED;
852     }
853
854     if (CA_STATUS_OK != CAQueueingThreadStart(g_sendQueueHandle))
855     {
856         OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
857         OICFree(g_sendQueueHandle);
858         g_sendQueueHandle = NULL;
859         return CA_STATUS_FAILED;
860     }
861
862     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
863     return CA_STATUS_OK;
864 }
865
866 CAResult_t CAInitBleClientSenderQueue()
867 {
868     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
869
870     if (g_bLEClientSendQueueHandle)
871     {
872         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
873         return CA_STATUS_OK;
874     }
875
876     // Create send message queue
877     g_bLEClientSendQueueHandle = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
878     if (!g_bLEClientSendQueueHandle)
879     {
880         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
881         return CA_MEMORY_ALLOC_FAILED;
882     }
883
884     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bLEClientSendQueueHandle, g_bleAdapterThreadPool,
885             CABLEClientSendDataThread, CALEDataDestroyer))
886     {
887         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
888         OICFree(g_bLEClientSendQueueHandle);
889         g_bLEClientSendQueueHandle = NULL;
890         return CA_STATUS_FAILED;
891     }
892
893     if (CA_STATUS_OK != CAQueueingThreadStart(g_bLEClientSendQueueHandle))
894     {
895         OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
896         OICFree(g_bLEClientSendQueueHandle);
897         g_bLEClientSendQueueHandle = NULL;
898         return CA_STATUS_FAILED;
899     }
900
901     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
902     return CA_STATUS_OK;
903 }
904
905 CAResult_t CAInitBleServerReceiverQueue()
906 {
907     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
908     // Check if the message queue is already initialized
909     if (g_bleServerReceiverQueue)
910     {
911         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
912         return CA_STATUS_OK;
913     }
914
915     // Create send message queue
916     g_bleServerReceiverQueue = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
917     if (!g_bleServerReceiverQueue)
918     {
919         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
920         OICFree(g_sendQueueHandle);
921         return CA_MEMORY_ALLOC_FAILED;
922     }
923
924     if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleServerReceiverQueue, g_bleAdapterThreadPool,
925             CABLEServerDataReceiverHandler, CALEDataDestroyer))
926     {
927         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
928         OICFree(g_bleServerReceiverQueue);
929         g_bleServerReceiverQueue = NULL;
930         return CA_STATUS_FAILED;
931     }
932
933     if (CA_STATUS_OK != CAQueueingThreadStart(g_bleServerReceiverQueue))
934     {
935         OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
936         OICFree(g_bleServerReceiverQueue);
937         g_bleServerReceiverQueue = NULL;
938         return CA_STATUS_FAILED;
939     }
940
941     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
942     return CA_STATUS_OK;
943 }
944
945 CAResult_t CAInitBleClientReceiverQueue()
946 {
947     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
948
949     // Check if the message queue is already initialized
950     if (g_bleClientReceiverQueue)
951     {
952         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Already queue is initialized!");
953     }
954     else
955     {
956         // Create send message queue
957         g_bleClientReceiverQueue = (CAQueueingThread_t *) OICMalloc(sizeof(CAQueueingThread_t));
958         if (!g_bleClientReceiverQueue)
959         {
960             OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
961             OICFree(g_bLEClientSendQueueHandle);
962             return CA_MEMORY_ALLOC_FAILED;
963         }
964
965         if (CA_STATUS_OK != CAQueueingThreadInitialize(g_bleClientReceiverQueue, g_bleAdapterThreadPool,
966                 CABLEClientDataReceiverHandler, NULL))
967         {
968             OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to Initialize send queue thread");
969             OICFree(g_bLEClientSendQueueHandle);
970             OICFree(g_bleClientReceiverQueue);
971             g_bleClientReceiverQueue = NULL;
972             return CA_STATUS_FAILED;
973         }
974     }
975     if (CA_STATUS_OK != CAQueueingThreadStart(g_bleClientReceiverQueue))
976     {
977         OIC_LOG(ERROR, CALEADAPTER_TAG, "ca_thread_pool_add_task failed ");
978         OICFree(g_bleClientReceiverQueue);
979         g_bleClientReceiverQueue = NULL;
980         return CA_STATUS_FAILED;
981     }
982
983     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
984     return CA_STATUS_OK;
985 }
986
987 void CAStopBleQueues()
988 {
989     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
990
991     ca_mutex_lock(g_bleClientSendDataMutex);
992     if (NULL != g_bLEClientSendQueueHandle)
993     {
994         CAQueueingThreadStop(g_bLEClientSendQueueHandle);
995     }
996     ca_mutex_unlock(g_bleClientSendDataMutex);
997
998     ca_mutex_lock(g_bleClientReceiveDataMutex);
999     if (NULL != g_bleClientReceiverQueue)
1000     {
1001         CAQueueingThreadStop(g_bleClientReceiverQueue);
1002     }
1003     ca_mutex_unlock(g_bleClientReceiveDataMutex);
1004
1005     ca_mutex_lock(g_bleServerSendDataMutex);
1006     if (NULL != g_sendQueueHandle)
1007     {
1008         CAQueueingThreadStop(g_sendQueueHandle);
1009     }
1010     ca_mutex_unlock(g_bleServerSendDataMutex);
1011
1012     ca_mutex_lock(g_bleServerReceiveDataMutex);
1013     if (NULL != g_bleServerReceiverQueue)
1014     {
1015         CAQueueingThreadStop(g_bleServerReceiverQueue);
1016     }
1017     ca_mutex_unlock(g_bleServerReceiveDataMutex);
1018
1019     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1020 }
1021
1022 void CATerminateBleQueues()
1023 {
1024     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1025
1026     CAQueueingThreadDestroy(g_bLEClientSendQueueHandle);
1027     OICFree(g_bLEClientSendQueueHandle);
1028     g_bLEClientSendQueueHandle = NULL;
1029
1030
1031     CAQueueingThreadDestroy(g_bleClientReceiverQueue);
1032     OICFree(g_bleClientReceiverQueue);
1033     g_bleClientReceiverQueue = NULL;
1034
1035
1036     CAQueueingThreadDestroy(g_sendQueueHandle);
1037     OICFree(g_sendQueueHandle);
1038     g_sendQueueHandle = NULL;
1039
1040
1041     CAQueueingThreadDestroy(g_bleServerReceiverQueue);
1042     OICFree(g_bleServerReceiverQueue);
1043     g_bleServerReceiverQueue = NULL;
1044
1045     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1046 }
1047 void CABLEServerDataReceiverHandler(void *threadData)
1048 {
1049     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1050
1051     static uint32_t recvDataLen = 0;
1052     static uint32_t totalDataLen = 0;
1053     static char *defragData = NULL;
1054     static bool isHeaderAvailable = false;
1055     static CARemoteEndpoint_t *remoteEndpoint = NULL;
1056
1057     ca_mutex_lock(g_bleClientReceiveDataMutex);
1058
1059     if (g_dataReceiverHandlerState)
1060     {
1061         OIC_LOG(DEBUG, CALEADAPTER_TAG, "checking for DE Fragmentation");
1062
1063         CALEData_t *bleData = (CALEData_t *) threadData;
1064         if (!bleData)
1065         {
1066             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid wifidata!");
1067             return;
1068         }
1069
1070         OIC_LOG(DEBUG, CALEADAPTER_TAG, "checking for DE Fragmentation");
1071
1072         if (!isHeaderAvailable)
1073         {
1074             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Parsing the header");
1075             totalDataLen = CAParseHeader((char*)bleData->data);
1076
1077             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Total data to be accumulated [%d] bytes", totalDataLen);
1078             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "data received in the first packet [%d] bytes", bleData->dataLen);
1079
1080             defragData = (char *) OICCalloc(totalDataLen + 1, sizeof(char));
1081             if (NULL == defragData)
1082             {
1083                 OIC_LOG(ERROR, CALEADAPTER_TAG, "defragData is NULL!");
1084                 return;
1085             }
1086
1087             const char *remoteAddress = bleData->remoteEndpoint->addressInfo.LE.leMacAddress;
1088             const char *serviceUUID = bleData->remoteEndpoint->resourceUri;
1089
1090             remoteEndpoint = CAAdapterCreateRemoteEndpoint(CA_LE, remoteAddress,
1091                              serviceUUID);
1092
1093             memcpy(defragData + recvDataLen, bleData->data + CA_HEADER_LENGTH,
1094                    bleData->dataLen - CA_HEADER_LENGTH);
1095             recvDataLen += bleData->dataLen - CA_HEADER_LENGTH;
1096             isHeaderAvailable = true;
1097         }
1098         else
1099         {
1100             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Copying the data of length [%d]", bleData->dataLen);
1101             memcpy(defragData + recvDataLen, bleData->data, bleData->dataLen);
1102             recvDataLen += bleData->dataLen ;
1103             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "totalDatalength  [%d] recveived Datalen [%d]",
1104                       totalDataLen, recvDataLen);
1105         }
1106         if (totalDataLen == recvDataLen)
1107         {
1108             ca_mutex_lock(g_bleAdapterReqRespCbMutex);
1109             if (NULL == g_networkPacketReceivedCallback)
1110             {
1111                 OIC_LOG(ERROR, CALEADAPTER_TAG, "gReqRespCallback is NULL!");
1112                 ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
1113                 return;
1114             }
1115             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending data up !");
1116             g_networkPacketReceivedCallback(remoteEndpoint, defragData, recvDataLen);
1117             recvDataLen = 0;
1118             totalDataLen = 0;
1119             isHeaderAvailable = false;
1120             remoteEndpoint = NULL;
1121             defragData = NULL;
1122             ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
1123         }
1124
1125         if (false == g_dataReceiverHandlerState)
1126         {
1127             OIC_LOG(DEBUG, CALEADAPTER_TAG, "GATTClient is terminating. Cleaning up");
1128             recvDataLen = 0;
1129             totalDataLen = 0;
1130             isHeaderAvailable = false;
1131             OICFree(defragData);
1132             CAAdapterFreeRemoteEndpoint(remoteEndpoint);
1133             ca_mutex_unlock(g_bleClientReceiveDataMutex);
1134             return;
1135         }
1136     }
1137     ca_mutex_unlock(g_bleClientReceiveDataMutex);
1138     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1139 }
1140
1141 void CABLEClientDataReceiverHandler(void *threadData)
1142 {
1143     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1144
1145     static const char *remoteAddress = NULL;
1146     static const char *serviceUUID = NULL;
1147     static uint32_t recvDataLen = 0;
1148     static uint32_t totalDataLen = 0;
1149     static char *defragData = NULL;
1150     static bool isHeaderAvailable = false;
1151     static CARemoteEndpoint_t *remoteEndpoint = NULL;
1152
1153     ca_mutex_lock(g_bleClientReceiveDataMutex);
1154
1155     if (g_dataReceiverHandlerState)
1156     {
1157         OIC_LOG(DEBUG, CALEADAPTER_TAG, "checking for DE Fragmentation");
1158
1159         CALEData_t *bleData = (CALEData_t *) threadData;
1160         if (!bleData)
1161         {
1162             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid wifidata!");
1163             return;
1164         }
1165
1166         OIC_LOG(DEBUG, CALEADAPTER_TAG, "checking for DE Fragmentation");
1167
1168         if (!isHeaderAvailable)
1169         {
1170             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Parsing the header");
1171
1172             totalDataLen = CAParseHeader(bleData->data);
1173             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Total data to be accumulated [%d] bytes",
1174                       totalDataLen);
1175             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data received in the first packet [%d] bytes",
1176                       bleData->dataLen);
1177
1178             defragData = (char *) OICMalloc(sizeof(char) * totalDataLen);
1179             if (NULL == defragData)
1180             {
1181                 OIC_LOG(ERROR, CALEADAPTER_TAG, "defragData is NULL!");
1182                 return;
1183             }
1184
1185             remoteAddress = bleData->remoteEndpoint->addressInfo.LE.leMacAddress;
1186             serviceUUID = bleData->remoteEndpoint->resourceUri;
1187
1188             remoteEndpoint = CAAdapterCreateRemoteEndpoint(CA_LE, remoteAddress,
1189                                                            serviceUUID);
1190
1191             memcpy(defragData, bleData->data + CA_HEADER_LENGTH,
1192                    bleData->dataLen - CA_HEADER_LENGTH);
1193             recvDataLen += bleData->dataLen - CA_HEADER_LENGTH;
1194             isHeaderAvailable = true;
1195         }
1196         else
1197         {
1198             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Copying the data of length [%d]", bleData->dataLen);
1199             memcpy(defragData + recvDataLen, bleData->data, bleData->dataLen);
1200             recvDataLen += bleData->dataLen ;
1201             OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "totalDatalength  [%d] recveived Datalen [%d]",
1202                       totalDataLen, recvDataLen);
1203         }
1204         if (totalDataLen == recvDataLen)
1205         {
1206             ca_mutex_lock(g_bleAdapterReqRespCbMutex);
1207             if (NULL == g_networkPacketReceivedCallback)
1208             {
1209                 OIC_LOG(ERROR, CALEADAPTER_TAG, "gReqRespCallback is NULL!");
1210                 ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
1211                 return;
1212             }
1213             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending data up !");
1214             g_networkPacketReceivedCallback(remoteEndpoint, defragData, recvDataLen);
1215             recvDataLen = 0;
1216             totalDataLen = 0;
1217             isHeaderAvailable = false;
1218             remoteEndpoint = NULL;
1219             defragData = NULL;
1220             ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
1221         }
1222
1223         if (false == g_dataReceiverHandlerState)
1224         {
1225             OIC_LOG(DEBUG, CALEADAPTER_TAG, "GATTClient is terminating. Cleaning up");
1226             OICFree(defragData);
1227             CAAdapterFreeRemoteEndpoint(remoteEndpoint);
1228             ca_mutex_unlock(g_bleClientReceiveDataMutex);
1229             return;
1230         }
1231     }
1232     ca_mutex_unlock(g_bleClientReceiveDataMutex);
1233     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1234 }
1235
1236 void CABLEServerSendDataThread(void *threadData)
1237 {
1238     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1239
1240     CALEData_t *bleData = (CALEData_t *) threadData;
1241     if (!bleData)
1242     {
1243         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bledata!");
1244         return;
1245     }
1246
1247     char *header = (char *) OICCalloc(CA_HEADER_LENGTH, sizeof(char));
1248     VERIFY_NON_NULL_VOID(header, CALEADAPTER_TAG, "Malloc failed");
1249
1250     char *dataSegment = (char *) OICCalloc(bleData->dataLen + CA_HEADER_LENGTH + 1, sizeof(char));
1251     if (NULL == dataSegment)
1252     {
1253         OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failed");
1254         OICFree(header);
1255         return;
1256     }
1257
1258     CAResult_t result = CAGenerateHeader(header, bleData->dataLen);
1259     if (CA_STATUS_OK != result )
1260     {
1261         OIC_LOG(ERROR, CALEADAPTER_TAG, "Generate header failed");
1262         OICFree(header);
1263         OICFree(dataSegment);
1264         return ;
1265     }
1266
1267     memcpy(dataSegment, header, CA_HEADER_LENGTH);
1268     OICFree(header);
1269
1270     int32_t length = 0;
1271     if (CA_SUPPORTED_BLE_MTU_SIZE >= bleData->dataLen)
1272     {
1273         length = bleData->dataLen + CA_HEADER_LENGTH;
1274         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "length [%d]", length);
1275         memcpy(dataSegment + CA_HEADER_LENGTH, bleData->data, bleData->dataLen);
1276     }
1277     else
1278     {
1279         length =  CA_SUPPORTED_BLE_MTU_SIZE;
1280         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "length [%d]", length);
1281         memcpy(dataSegment + CA_HEADER_LENGTH, bleData->data,
1282                CA_SUPPORTED_BLE_MTU_SIZE - CA_HEADER_LENGTH);
1283     }
1284
1285     int32_t iter = bleData->dataLen / CA_SUPPORTED_BLE_MTU_SIZE;
1286     int32_t index = 0;
1287     ca_mutex_lock(g_bleServerSendDataMutex);
1288     // Send the first segment with the header.
1289     result = CAUpdateCharacteristicsInGattServer(dataSegment, length);
1290     if (CA_STATUS_OK != result )
1291     {
1292         OIC_LOG(ERROR, CALEADAPTER_TAG, "CAUpdateCharacteristicsInGattServer failed");
1293         OICFree(dataSegment);
1294         ca_mutex_unlock(g_bleServerSendDataMutex);
1295         return ;
1296     }
1297
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         if (CA_STATUS_OK != result )
1306         {
1307             OIC_LOG(ERROR, CALEADAPTER_TAG, "CAUpdateCharacteristicsInGattServer failed");
1308             OICFree(dataSegment);
1309             ca_mutex_unlock(g_bleServerSendDataMutex);
1310             return ;
1311         }
1312     }
1313
1314     if (bleData->dataLen / CA_SUPPORTED_BLE_MTU_SIZE)
1315     {
1316         // send the last segment of the data (Ex: 22 bytes of 622 bytes of data when MTU is 200)
1317         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
1318         result = CAUpdateCharacteristicsInGattServer(
1319                      bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
1320                      bleData->dataLen % CA_SUPPORTED_BLE_MTU_SIZE + CA_HEADER_LENGTH);
1321         if (CA_STATUS_OK != result )
1322         {
1323             OIC_LOG(ERROR, CALEADAPTER_TAG, "CAUpdateCharacteristicsInGattServer failed");
1324             OICFree(dataSegment);
1325             ca_mutex_unlock(g_bleServerSendDataMutex);
1326             return ;
1327         }
1328     }
1329
1330     OICFree(dataSegment);
1331     ca_mutex_unlock(g_bleServerSendDataMutex); // TODO: this mutex required  ?
1332
1333     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1334 }
1335
1336 void CABLEClientSendDataThread(void *threadData)
1337 {
1338     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1339
1340     CALEData_t *bleData = (CALEData_t *) threadData;
1341     if (!bleData)
1342     {
1343         OIC_LOG(DEBUG, CALEADAPTER_TAG, "Invalid bledata!");
1344         return;
1345     }
1346
1347     char *header = (char *) OICCalloc(CA_HEADER_LENGTH, sizeof(char));
1348     VERIFY_NON_NULL_VOID(header, CALEADAPTER_TAG, "Malloc failed");
1349
1350     char *dataSegment = (char *) OICCalloc(bleData->dataLen + CA_HEADER_LENGTH + 1, sizeof(char));
1351     if (NULL == dataSegment)
1352     {
1353         OIC_LOG(ERROR, CALEADAPTER_TAG, "Malloc failed");
1354         OICFree(header);
1355         return;
1356     }
1357
1358     CAResult_t result = CAGenerateHeader(header, bleData->dataLen);
1359     if (CA_STATUS_OK != result )
1360     {
1361         OIC_LOG(ERROR, CALEADAPTER_TAG, "Generate header failed");
1362         OICFree(header);
1363         OICFree(dataSegment);
1364         return ;
1365     }
1366     memcpy(dataSegment, header, CA_HEADER_LENGTH);
1367     OICFree(header);
1368
1369     int32_t length = 0;
1370     if (CA_SUPPORTED_BLE_MTU_SIZE >= bleData->dataLen)
1371     {
1372         length = bleData->dataLen + CA_HEADER_LENGTH;
1373         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "length [%d]", length);
1374         memcpy(dataSegment + CA_HEADER_LENGTH, bleData->data, bleData->dataLen);
1375     }
1376     else
1377     {
1378         length = CA_SUPPORTED_BLE_MTU_SIZE;
1379         OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "length [%d]", length);
1380         memcpy(dataSegment + CA_HEADER_LENGTH, bleData->data,
1381                CA_SUPPORTED_BLE_MTU_SIZE - CA_HEADER_LENGTH);
1382     }
1383
1384     int32_t iter = bleData->dataLen / CA_SUPPORTED_BLE_MTU_SIZE;
1385     int32_t index = 0;
1386     ca_mutex_lock(g_bleClientSendDataMutex);
1387     if (NULL != bleData->remoteEndpoint)
1388     {
1389         // Send the first segment with the header.
1390         result = CAUpdateCharacteristicsToGattServer(bleData->remoteEndpoint->addressInfo.LE.leMacAddress,
1391                  dataSegment,
1392                  length,
1393                  LE_UNICAST, 0);
1394         if (CA_STATUS_OK != result )
1395         {
1396             OIC_LOG(ERROR, CALEADAPTER_TAG, "CAUpdateCharacteristicsToGattServer failed");
1397             OICFree(dataSegment);
1398             ca_mutex_unlock(g_bleClientSendDataMutex);
1399             return ;
1400         }
1401
1402         for (index = 1; index < iter; index++)
1403         {
1404             // Send the remaining header.
1405             result = CAUpdateCharacteristicsToGattServer(bleData->remoteEndpoint->addressInfo.LE.leMacAddress,
1406                      bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
1407                      CA_SUPPORTED_BLE_MTU_SIZE,
1408                      LE_UNICAST, 0);
1409             if (CA_STATUS_OK != result )
1410             {
1411                 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAUpdateCharacteristicsToGattServer failed");
1412                 OICFree(dataSegment);
1413                 ca_mutex_unlock(g_bleClientSendDataMutex);
1414                 return ;
1415             }
1416         }
1417
1418         if (bleData->dataLen / CA_SUPPORTED_BLE_MTU_SIZE)
1419         {
1420             // send the last segment of the data (Ex: 22 bytes of 622 bytes of data when MTU is 200)
1421             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
1422             result = CAUpdateCharacteristicsToGattServer(bleData->remoteEndpoint->addressInfo.LE.leMacAddress,
1423                      bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
1424                      bleData->dataLen % CA_SUPPORTED_BLE_MTU_SIZE + CA_HEADER_LENGTH,
1425                      LE_UNICAST, 0);
1426             if (CA_STATUS_OK != result )
1427             {
1428                 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAUpdateCharacteristicsToGattServer failed");
1429                 OICFree(dataSegment);
1430                 ca_mutex_unlock(g_bleClientSendDataMutex);
1431                 return ;
1432             }
1433         }
1434     }
1435     else
1436     {
1437         // Send the first segment with the header.
1438         result = CAUpdateCharacteristicsToAllGattServers(dataSegment + (index * length),
1439                  length);
1440         if (CA_STATUS_OK != result )
1441         {
1442             OIC_LOG(ERROR, CALEADAPTER_TAG, "CAUpdateCharacteristicsToGattServer failed");
1443             OICFree(dataSegment);
1444             ca_mutex_unlock(g_bleClientSendDataMutex);
1445             return ;
1446         }
1447         // Send the remaining header.
1448         for (index = 1; index < iter; index++)
1449         {
1450             result = CAUpdateCharacteristicsToAllGattServers(
1451                          bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
1452                          CA_SUPPORTED_BLE_MTU_SIZE);
1453             if (CA_STATUS_OK != result )
1454             {
1455                 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAUpdateCharacteristicsToGattServer failed");
1456                 OICFree(dataSegment);
1457                 ca_mutex_unlock(g_bleClientSendDataMutex);
1458                 return ;
1459             }
1460         }
1461         if (bleData->dataLen / CA_SUPPORTED_BLE_MTU_SIZE)
1462         {
1463             // send the last segment of the data (Ex: 22 bytes of 622 bytes of data when MTU is 200)
1464             OIC_LOG(DEBUG, CALEADAPTER_TAG, "Sending the last chunk");
1465             result = CAUpdateCharacteristicsToAllGattServers(
1466                          bleData->data + (index * CA_SUPPORTED_BLE_MTU_SIZE) - CA_HEADER_LENGTH,
1467                          bleData->dataLen % CA_SUPPORTED_BLE_MTU_SIZE + CA_HEADER_LENGTH);
1468              if (CA_STATUS_OK != result )
1469             {
1470                 OIC_LOG(ERROR, CALEADAPTER_TAG, "CAUpdateCharacteristicsToGattServer failed");
1471                 OICFree(dataSegment);
1472                 ca_mutex_unlock(g_bleClientSendDataMutex);
1473                 return ;
1474             }
1475         }
1476     }
1477
1478     OICFree(dataSegment);
1479     ca_mutex_unlock(g_bleClientSendDataMutex);
1480
1481     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1482 }
1483
1484 CALEData_t *CACreateBLEData(const CARemoteEndpoint_t *remoteEndpoint, const void *data,
1485                            uint32_t dataLength)
1486 {
1487     CALEData_t *bleData = (CALEData_t *) OICMalloc(sizeof(CALEData_t));
1488     if (!bleData)
1489     {
1490         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
1491         return NULL;
1492     }
1493
1494     bleData->remoteEndpoint = CAAdapterCopyRemoteEndpoint(remoteEndpoint);
1495     bleData->data = (void *)OICCalloc(dataLength + 1, 1);
1496     if (NULL == bleData->data)
1497     {
1498         OIC_LOG(ERROR, CALEADAPTER_TAG, "Memory allocation failed!");
1499         CAFreeBLEData(bleData);
1500         return NULL;
1501     }
1502     memcpy(bleData->data, data, dataLength);
1503     bleData->dataLen = dataLength;
1504
1505     return bleData;
1506 }
1507
1508 void CAFreeBLEData(CALEData_t *bleData)
1509 {
1510     if (!bleData)
1511         return;
1512
1513     CAAdapterFreeRemoteEndpoint(bleData->remoteEndpoint);
1514     OICFree(bleData->data);
1515     OICFree(bleData);
1516 }
1517
1518 void CALEDataDestroyer(void *data, uint32_t size)
1519 {
1520     CALEData_t *ledata = (CALEData_t *) data;
1521
1522     CAFreeBLEData(ledata);
1523 }
1524
1525
1526 CAResult_t CABLEClientSendData(const CARemoteEndpoint_t *remoteEndpoint,
1527                                const void *data,
1528                                uint32_t dataLen)
1529 {
1530     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1531
1532     VERIFY_NON_NULL(data, NULL, "Param data is NULL");
1533
1534     VERIFY_NON_NULL_RET(g_bLEClientSendQueueHandle, CALEADAPTER_TAG,
1535                         "g_bLEClientSendQueueHandle is  NULL",
1536                         CA_STATUS_FAILED);
1537     VERIFY_NON_NULL_RET(g_bleClientSendDataMutex, CALEADAPTER_TAG,
1538                         "g_bleClientSendDataMutex is NULL",
1539                         CA_STATUS_FAILED);
1540
1541     VERIFY_NON_NULL_RET(g_bLEClientSendQueueHandle, CALEADAPTER_TAG, "g_bLEClientSendQueueHandle",
1542                         CA_STATUS_FAILED);
1543
1544     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%d]", dataLen);
1545
1546     CALEData_t *bleData = CACreateBLEData(remoteEndpoint, data, dataLen);
1547     if (!bleData)
1548     {
1549         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
1550         return CA_MEMORY_ALLOC_FAILED;
1551     }
1552     // Add message to send queue
1553     ca_mutex_lock(g_bleClientSendDataMutex);
1554     CAQueueingThreadAddData(g_bLEClientSendQueueHandle, bleData, sizeof(CALEData_t));
1555     ca_mutex_unlock(g_bleClientSendDataMutex);
1556
1557     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1558     return CA_STATUS_OK;
1559 }
1560
1561
1562 CAResult_t CABLEServerSendData(const CARemoteEndpoint_t *remoteEndpoint,
1563                                const void *data,
1564                                uint32_t dataLen)
1565 {
1566     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1567
1568     VERIFY_NON_NULL(data, NULL, "Param data is NULL");
1569
1570     VERIFY_NON_NULL_RET(g_sendQueueHandle, CALEADAPTER_TAG,
1571                         "BleClientReceiverQueue is NULL",
1572                         CA_STATUS_FAILED);
1573     VERIFY_NON_NULL_RET(g_bleClientSendDataMutex, CALEADAPTER_TAG,
1574                         "BleClientSendDataMutex is NULL",
1575                         CA_STATUS_FAILED);
1576
1577     VERIFY_NON_NULL_RET(g_sendQueueHandle, CALEADAPTER_TAG, "sendQueueHandle",
1578                         CA_STATUS_FAILED);
1579
1580     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data Sending to LE layer [%d]", dataLen);
1581
1582     CALEData_t *bleData = CACreateBLEData(remoteEndpoint, data, dataLen);
1583     if (!bleData)
1584     {
1585         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
1586         return CA_MEMORY_ALLOC_FAILED;
1587     }
1588     // Add message to send queue
1589     ca_mutex_lock(g_bleServerSendDataMutex);
1590     CAQueueingThreadAddData(g_sendQueueHandle, bleData, sizeof(CALEData_t));
1591     ca_mutex_unlock(g_bleServerSendDataMutex);
1592
1593     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1594     return CA_STATUS_OK;
1595 }
1596
1597 CAResult_t CABLEServerReceivedData(const char *remoteAddress, const char *serviceUUID,
1598                                    const void *data, uint32_t dataLength, uint32_t *sentLength)
1599 {
1600     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1601
1602     //Input validation
1603     VERIFY_NON_NULL(serviceUUID, CALEADAPTER_TAG, "service UUID is null");
1604     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
1605     VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
1606     VERIFY_NON_NULL_RET(g_bleServerReceiverQueue, CALEADAPTER_TAG, "g_bleServerReceiverQueue",
1607                         CA_STATUS_FAILED);
1608
1609     //Add message to data queue
1610     CARemoteEndpoint_t *remoteEndpoint = CAAdapterCreateRemoteEndpoint(CA_LE, remoteAddress,
1611                                          serviceUUID);
1612     if (NULL == remoteEndpoint)
1613     {
1614         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
1615         return CA_STATUS_FAILED;
1616     }
1617
1618     // Create bleData to add to queue
1619     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data received from LE layer [%d]", dataLength);
1620
1621     CALEData_t *bleData = CACreateBLEData(remoteEndpoint, data, dataLength);
1622     if (!bleData)
1623     {
1624         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
1625         CAAdapterFreeRemoteEndpoint(remoteEndpoint);
1626         return CA_MEMORY_ALLOC_FAILED;
1627     }
1628
1629     CAAdapterFreeRemoteEndpoint(remoteEndpoint);
1630     // Add message to send queue
1631     CAQueueingThreadAddData(g_bleServerReceiverQueue, bleData, sizeof(CALEData_t));
1632
1633     *sentLength = dataLength;
1634
1635     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1636     return CA_STATUS_OK;
1637 }
1638
1639 CAResult_t CABLEClientReceivedData(const char *remoteAddress, const char *serviceUUID,
1640                                    const void *data, uint32_t dataLength, uint32_t *sentLength)
1641 {
1642     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1643
1644     //Input validation
1645     VERIFY_NON_NULL(serviceUUID, CALEADAPTER_TAG, "service UUID is null");
1646     VERIFY_NON_NULL(data, CALEADAPTER_TAG, "Data is null");
1647     VERIFY_NON_NULL(sentLength, CALEADAPTER_TAG, "Sent data length holder is null");
1648     VERIFY_NON_NULL_RET(g_bleClientReceiverQueue, CALEADAPTER_TAG, "g_bleClientReceiverQueue",
1649                         CA_STATUS_FAILED);
1650
1651     //Add message to data queue
1652     CARemoteEndpoint_t *remoteEndpoint = CAAdapterCreateRemoteEndpoint(CA_LE, remoteAddress,
1653                                          serviceUUID);
1654     if (NULL == remoteEndpoint)
1655     {
1656         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create remote endpoint !");
1657         return CA_STATUS_FAILED;
1658     }
1659
1660     OIC_LOG_V(DEBUG, CALEADAPTER_TAG, "Data received from LE layer [%d]", dataLength);
1661
1662     // Create bleData to add to queue
1663     CALEData_t *bleData = CACreateBLEData(remoteEndpoint, data, dataLength);
1664     if (!bleData)
1665     {
1666         OIC_LOG(ERROR, CALEADAPTER_TAG, "Failed to create bledata!");
1667         CAAdapterFreeRemoteEndpoint(remoteEndpoint);
1668         return CA_MEMORY_ALLOC_FAILED;
1669     }
1670
1671     CAAdapterFreeRemoteEndpoint(remoteEndpoint);
1672     // Add message to send queue
1673     CAQueueingThreadAddData(g_bleClientReceiverQueue, bleData, sizeof(CALEData_t));
1674
1675     *sentLength = dataLength;
1676
1677     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1678     return CA_STATUS_OK;
1679 }
1680
1681 void CASetBleAdapterThreadPoolHandle(ca_thread_pool_t handle)
1682 {
1683     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1684
1685     ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
1686     g_bleAdapterThreadPool = handle;
1687     ca_mutex_unlock(g_bleAdapterThreadPoolMutex);
1688
1689     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1690 }
1691
1692 void CASetBLEReqRespAdapterCallback(CANetworkPacketReceivedCallback callback)
1693 {
1694     OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
1695
1696     ca_mutex_lock(g_bleAdapterReqRespCbMutex);
1697
1698     g_networkPacketReceivedCallback = callback;
1699
1700     ca_mutex_unlock(g_bleAdapterReqRespCbMutex);
1701
1702     OIC_LOG(DEBUG, CALEADAPTER_TAG, "OUT");
1703 }
1704