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