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