Fix -Wreturn-type build warning
[platform/upstream/iotivity.git] / resource / csdk / connectivity / src / bt_le_adapter / tizen / caleclient.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
21 #include "caleclient.h"
22
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <arpa/inet.h>
27 #include <sys/types.h>
28 #include <sys/socket.h>
29 #include <netinet/in.h>
30 #include <pthread.h>
31 #include <gio/gio.h>
32
33 #include "octhread.h"
34 #include "uarraylist.h"
35 #include "caqueueingthread.h"
36 #include "caadapterutils.h"
37 #include "cagattservice.h"
38 #include "oic_string.h"
39 #include "oic_malloc.h"
40
41 /**
42  * Logging tag for module name.
43  */
44 #define TAG "OIC_CA_LE_CLIENT"
45
46 #define RETRY_COUNT 1
47 #define MICROSECS_PER_SEC 1000000
48 #define WAIT_TIME_WRITE_CHARACTERISTIC 10 * MICROSECS_PER_SEC
49
50 //For custom uuid ble server
51 #define CA_GATT_CUSTOM_UUID "4209"
52 #define CA_GATT_CUSTOM_UUID2 "4204"
53 #define CUSTOM_UUID_LEN 4
54 #define MICROSECS_PER_SEC 1000000
55
56 static const int samsung_code = 117;
57 static int g_retrycount = 0;
58 static int retry_flag = 0;
59 uint64_t const TIMEOUT = 30 * MICROSECS_PER_SEC;
60
61 /**
62  * Mutex to call connect only after disconnect during retry
63  */
64 static oc_mutex g_isDisconnectedMutex = NULL;
65
66 /**
67  * Condition for calling connect during connection retry
68  */
69 static oc_cond g_LEDisconnectedCond = NULL;
70
71 /**
72  * Flag to check if scanning is in progress
73  */
74 static bool g_isScanningInProgress = false;
75
76 /**
77  * Mutex to synchronize access to g_isScanningInProgress
78  */
79 static oc_mutex g_isScanningInProgressMutex = NULL;
80
81 /**
82  * Flag to check if connection is in progress
83  */
84 static bool g_isConnectionInProgress = false;
85
86 /**
87  * Mutex to synchronize access to g_isConnectionInProgress
88  */
89 static oc_mutex g_isConnectionInProgressMutex = NULL;
90
91 /**
92  * Flag to check if multicast is already in progress.
93  */
94 static bool g_isMulticastInProgress = false;
95
96 /**
97  * Flag to check if unicast scan is in progress
98  */
99 static bool g_isUnicastScanInProgress = false;
100
101 /**
102  * Mutex to synchronize access to g_isMulticastInProgress
103  * and g_isUnicastScanInProgress
104  */
105 static oc_mutex g_scanMutex = NULL;
106
107 /**
108  * Pending multicast data list to be sent.
109  */
110 static u_arraylist_t *g_multicastDataList = NULL;
111
112 /**
113  * Mutex to synchronize the access to Pending multicast data list.
114  */
115 static oc_mutex g_multicastDataListMutex = NULL;
116
117 /**
118  * Condition to start the timer for scanning.
119  */
120 static oc_cond g_startTimerCond = NULL;
121
122 /**
123  * Condition for scanning Time interval.
124  */
125 static oc_cond g_scanningTimeCond = NULL;
126
127 /**
128  * This contains the list of OIC services a client connect tot.
129  */
130 static LEServerInfoList *g_LEServerList = NULL;
131
132 /**
133  * Mutex to synchronize access to BleServiceList.
134  */
135 static oc_mutex g_LEServerListMutex = NULL;
136
137 /**
138  * Boolean variable to keep the state of the GATT Client.
139  */
140 static bool g_isLEGattClientStarted = false;
141
142 /**
143  * Mutex to synchronize access to the requestResponse callback to be called
144  * when the data needs to be sent from GATTClient.
145  */
146 static oc_mutex g_LEReqRespClientCbMutex = NULL;
147
148 /**
149  * Mutex to synchronize access to the requestResponse callback to be called
150  * when the data needs to be sent from GATTClient.
151  */
152 static oc_mutex g_LEClientConnectMutex = NULL;
153
154 /**
155  * Mutex to synchronize the calls to be done to the platform from GATTClient
156  * interfaces from different threads.
157  */
158 static oc_mutex g_LEClientStateMutex = NULL;
159
160 /**
161  * Mutex to synchronize the task to be pushed to thread pool.
162  */
163 static oc_mutex g_LEClientThreadPoolMutex = NULL;
164
165 /**
166  * Mutex to synchronize the task to write characteristic one packet after another.
167  */
168 static oc_mutex g_threadWriteCharacteristicMutex = NULL;
169
170 /**
171  * Condition for Writing characteristic.
172  */
173 static oc_cond g_threadWriteCharacteristicCond = NULL;
174
175 /**
176  * Mutex to synchronize the task for MTU Changed.
177  */
178 static oc_mutex g_threadMTUChangedMutex = NULL;
179
180 /**
181  * Condition for MTU Changed.
182  */
183 static oc_cond g_threadMTUChangedCond = NULL;
184
185 /**
186  * Flag to check status of write characteristic.
187  */
188 static bool g_isSignalSetFlag = false;
189
190 /**
191  * Maintains the callback to be notified on receival of network packets from other
192  *           BLE devices
193  */
194 static CABLEDataReceivedCallback g_LEClientDataReceivedCallback = NULL;
195
196 /**
197  * callback to update the error to le adapter
198  */
199 static CABLEErrorHandleCallback g_clientErrorCallback;
200
201 /**
202  * gmainLoop to manage the threads to receive the callback from the platfrom.
203  */
204 static GMainLoop *g_eventLoop = NULL;
205
206 /**
207  * Reference to threadpool
208  */
209 static ca_thread_pool_t g_LEClientThreadPool = NULL;
210
211 void CALEGattCharacteristicChangedCb(bt_gatt_h characteristic,
212                                      char *value,
213                                      int valueLen, void *userData)
214 {
215     (void)characteristic;
216
217     OIC_LOG(DEBUG, TAG, "IN");
218     OIC_LOG_V(DEBUG, TAG, "Changed characteristic value length [%d]", valueLen);
219
220     oc_mutex_lock(g_LEReqRespClientCbMutex);
221     if (NULL == g_LEClientDataReceivedCallback)
222     {
223         OIC_LOG(ERROR, TAG, "Request response callback is not set");
224         oc_mutex_unlock(g_LEReqRespClientCbMutex);
225         return;
226     }
227
228     uint32_t sentLength = 0;
229     g_LEClientDataReceivedCallback(userData, (uint8_t *)value, valueLen, &sentLength);
230
231     OIC_LOG_V(DEBUG, TAG, "Recv data Length is %d", sentLength);
232
233     oc_mutex_unlock(g_LEReqRespClientCbMutex);
234
235     OIC_LOG(DEBUG, TAG, "OUT");
236 }
237
238 void CALEGattClientMTUChangedCb(bt_gatt_client_h client_handle, const bt_gatt_client_att_mtu_info_s *mtu_info, void *user_data)
239 {
240     OIC_LOG(DEBUG, TAG, "IN");
241     oc_mutex_lock(g_threadMTUChangedMutex);
242     OIC_LOG(DEBUG, TAG, "MTU changed signal");
243     oc_cond_signal(g_threadMTUChangedCond);
244     oc_mutex_unlock(g_threadMTUChangedMutex);
245     OIC_LOG(DEBUG, TAG, "OUT");
246 }
247
248
249 void CALEGattCharacteristicWriteCb(int result, bt_gatt_h reqHandle, void *userData)
250 {
251     (void)reqHandle;
252     (void)userData;
253
254     OIC_LOG(DEBUG, TAG, "IN ");
255
256     if (BT_ERROR_NONE != result)
257     {
258         CALogSendStateInfo(CA_ADAPTER_GATT_BTLE, "", 0, -1,
259                            false, "writeChar failure");
260
261         OIC_LOG(ERROR, TAG, "Write failed Need Retry ");
262         //Need to Implement retry mechanism
263     }
264     else
265     {
266         oc_mutex_lock(g_threadWriteCharacteristicMutex);
267         OIC_LOG(DEBUG, TAG, "g_isSignalSetFlag is set true and signal");
268         g_isSignalSetFlag = true;
269         oc_cond_signal(g_threadWriteCharacteristicCond);
270         oc_mutex_unlock(g_threadWriteCharacteristicMutex);
271
272         CALogSendStateInfo(CA_ADAPTER_GATT_BTLE, "", 0, -1,
273                            true, "writeChar success");
274     }
275
276     OIC_LOG(DEBUG, TAG, "OUT ");
277 }
278
279 CAResult_t CALEGattInitiateConnection(const char *remoteAddress)
280 {
281     OIC_LOG(DEBUG, TAG, "IN");
282
283     oc_mutex_lock(g_isConnectionInProgressMutex);
284     if (g_isConnectionInProgress)
285     {
286         oc_mutex_unlock(g_isConnectionInProgressMutex);
287         OIC_LOG(DEBUG, TAG, "Connection already in progress, cannot initiate new connection");
288         return CA_STATUS_FAILED;
289     }
290     g_isConnectionInProgress = true;
291     // Set gatt connect retry count
292     g_retrycount = RETRY_COUNT;
293     oc_mutex_unlock(g_isConnectionInProgressMutex);
294
295     // Pause the scanning
296     CALEGattStopDeviceScanning();
297
298     OIC_LOG_V(DEBUG, TAG,
299               "Trying to do Gatt connection to [%s]", remoteAddress);
300
301     oc_mutex_lock(g_LEClientThreadPoolMutex);
302     if (NULL == g_LEClientThreadPool)
303     {
304         oc_mutex_unlock(g_LEClientThreadPoolMutex);
305         OIC_LOG(ERROR, TAG, "g_LEClientThreadPool is NULL");
306         return CA_STATUS_FAILED;
307     }
308
309     char *addr = OICStrdup(remoteAddress);
310     if (NULL == addr)
311     {
312         oc_mutex_unlock(g_LEClientThreadPoolMutex);
313         OIC_LOG(ERROR, TAG, "OICStrdup failed");
314         return CA_STATUS_FAILED;
315     }
316
317     CAResult_t res = ca_thread_pool_add_task(g_LEClientThreadPool, CAGattConnectThread, addr, NULL);
318     oc_mutex_unlock(g_LEClientThreadPoolMutex);
319     if (CA_STATUS_OK != res)
320     {
321         OIC_LOG_V(ERROR, TAG,
322                   "ca_thread_pool_add_task failed with ret [%d]", res);
323         OICFree(addr);
324         return CA_STATUS_FAILED;
325     }
326     OIC_LOG(DEBUG, TAG, "OUT");
327     return CA_STATUS_OK;
328 }
329
330 void CALEGattConnectionStateChanged(bool connected, const char *remoteAddress)
331 {
332     OIC_LOG(DEBUG, TAG, "IN ");
333
334     VERIFY_NON_NULL_VOID(remoteAddress, TAG, "remote address is NULL");
335
336     if (!connected)
337     {
338         OIC_LOG_V(DEBUG, TAG, "DisConnected from [%s] ", remoteAddress);
339         if(!retry_flag)
340         {
341             oc_mutex_lock(g_LEServerListMutex);
342             CARemoveLEServerInfoFromList(&g_LEServerList, remoteAddress);
343             oc_mutex_unlock(g_LEServerListMutex);
344         }
345         else
346         {
347             oc_mutex_lock(g_isDisconnectedMutex);
348             oc_cond_signal(g_LEDisconnectedCond);
349             oc_mutex_unlock(g_isDisconnectedMutex);
350         }
351         retry_flag = 0;
352     }
353     else
354     {
355         OIC_LOG_V(DEBUG, TAG, "Connected to [%s] ", remoteAddress);
356
357         oc_mutex_lock(g_isConnectionInProgressMutex);
358         g_isConnectionInProgress = false;
359         oc_mutex_unlock(g_isConnectionInProgressMutex);
360
361         LEServerInfo *serverInfo = NULL;
362         oc_mutex_lock(g_LEServerListMutex);
363         if (CA_STATUS_OK != CAGetLEServerInfo(g_LEServerList, remoteAddress, &serverInfo))
364         {
365             oc_mutex_unlock(g_LEServerListMutex);
366             OIC_LOG_V(ERROR, TAG, "Could not get server info for [%s]", remoteAddress);
367             return;
368         }
369
370         serverInfo->status = LE_STATUS_CONNECTED;
371         oc_mutex_unlock(g_LEServerListMutex);
372         oc_mutex_lock(g_LEClientThreadPoolMutex);
373         if (NULL == g_LEClientThreadPool)
374         {
375             oc_mutex_unlock(g_LEClientThreadPoolMutex);
376             OIC_LOG(ERROR, TAG, "g_LEClientThreadPool is NULL");
377             return;
378         }
379
380         char *addr = OICStrdup(remoteAddress);
381         if (NULL == addr)
382         {
383             oc_mutex_unlock(g_LEClientThreadPoolMutex);
384             OIC_LOG(ERROR, TAG, "addr is NULL");
385             return;
386         }
387
388         CAResult_t ret = ca_thread_pool_add_task(g_LEClientThreadPool, CADiscoverLEServicesThread,
389                                                  addr, NULL);
390         oc_mutex_unlock(g_LEClientThreadPoolMutex);
391         if (CA_STATUS_OK != ret)
392         {
393             OIC_LOG_V(ERROR, TAG, "ca_thread_pool_add_task failed with ret [%d]", ret);
394             OICFree(addr);
395         }
396     }
397     OIC_LOG(DEBUG, TAG, "OUT");
398 }
399
400 static bool CALEIsHaveServiceImpl(bt_adapter_le_device_scan_result_info_s *scanInfo,
401                                   const char *service_uuid,
402                                   bt_adapter_le_packet_type_e pkt_type)
403 {
404     bool ret = false;
405     char **uuids = NULL;
406     int count = 0;
407     int result = 0;
408
409     result = bt_adapter_le_get_scan_result_service_uuids(scanInfo,
410              pkt_type, &uuids, &count);
411     if (result == BT_ERROR_NONE && NULL != uuids)
412     {
413         for (int i = 0; i < count; i++)
414         {
415             if (0 == strcasecmp(uuids[i], service_uuid))
416             {
417                 OIC_LOG_V(DEBUG, TAG, "Service[%s] Found in %s",
418                           uuids[i], scanInfo->remote_address);
419                 ret = true;
420             }
421             OICFree(uuids[i]);
422         }
423         OICFree(uuids);
424     }
425
426     if(ret == false){
427         char *man_data = NULL;
428         int man_data_len;
429         int man_id;
430         result = bt_adapter_le_get_scan_result_manufacturer_data(scanInfo,
431                               pkt_type, &man_id, &man_data, &man_data_len);
432
433         if (result == BT_ERROR_NONE && NULL != man_data)
434         {
435             int pos =0;
436             char *compare_man_data = OICCalloc(1, (man_data_len*2)+1);
437             if (!compare_man_data)
438             {
439                 OIC_LOG(ERROR, TAG, "Memory allocation failed for compare_man_data");
440                 OICFree(man_data);
441                 return false;
442             }
443
444             for(int i=0;i<man_data_len;i++){
445                 pos += snprintf(compare_man_data+pos, 2, "%.2x", man_data[i]);
446             }
447
448             if (man_id == samsung_code && 0 == strncasecmp(compare_man_data, service_uuid, CUSTOM_UUID_LEN))
449             {
450                 OIC_LOG_V(DEBUG, TAG, "Manufacture Data[%s] Found in %s",
451                                        compare_man_data, scanInfo->remote_address);
452                 ret = true;
453             }
454             OICFree(compare_man_data);
455             OICFree(man_data);
456         }
457     }
458     return ret;
459 }
460
461 static bool CALEIsHaveService(bt_adapter_le_device_scan_result_info_s *scanInfo,
462                               const char *service_uuid)
463 {
464     return
465         // For arduino servers, scan response will give the UUIDs advertised.
466         CALEIsHaveServiceImpl(scanInfo, service_uuid,
467                               BT_ADAPTER_LE_PACKET_SCAN_RESPONSE) ||
468         // For android/tizen servers, advertising packet will give the UUIDs.
469         CALEIsHaveServiceImpl(scanInfo, service_uuid,
470                               BT_ADAPTER_LE_PACKET_ADVERTISING);
471 }
472
473 void CALEAdapterScanResultCb(int result, bt_adapter_le_device_scan_result_info_s *scanInfo,
474                              void *userData)
475 {
476     (void)userData;
477     OIC_LOG(DEBUG, TAG, "IN");
478
479     VERIFY_NON_NULL_VOID(scanInfo, TAG, "scanInfo");
480     VERIFY_NON_NULL_VOID(scanInfo->remote_address, TAG, "scanInfo->remote_address");
481
482     OIC_LOG_V(DEBUG, TAG, "Remote Address [%s]", scanInfo->remote_address);
483     OIC_LOG_V(DEBUG, TAG, "Scan Result [%d]", result);
484     OIC_LOG_V(DEBUG, TAG,
485               " Adv data len [%d] Scan data len[%d]RSSI [%d] Addr_type [%d] ",
486               scanInfo->adv_data_len, scanInfo->scan_data_len, scanInfo->rssi,
487               scanInfo->address_type);
488
489     // Check if scanning was stopped (since this callback is
490     // being triggered even after stopping the scan)
491     oc_mutex_lock(g_isScanningInProgressMutex);
492     if (!g_isScanningInProgress)
493     {
494         oc_mutex_unlock(g_isScanningInProgressMutex);
495         OIC_LOG(DEBUG, TAG, "Scanning not in progress, so ignoring callback");
496         return;
497     }
498     oc_mutex_unlock(g_isScanningInProgressMutex);
499
500     if (CALEIsHaveService(scanInfo, CA_GATT_SERVICE_UUID) ||
501         CALEIsHaveService(scanInfo, CA_GATT_CUSTOM_UUID)||
502         CALEIsHaveService(scanInfo, CA_GATT_CUSTOM_UUID2))
503     {
504         OIC_LOG_V(DEBUG, TAG, "Device [%s] supports OIC or custom service", scanInfo->remote_address);
505
506         LEServerInfo *serverInfo = NULL;
507         oc_mutex_lock(g_LEServerListMutex);
508         CAResult_t ret = CAGetLEServerInfo(g_LEServerList, scanInfo->remote_address, &serverInfo);
509         if (CA_STATUS_OK != ret)
510         {
511             OIC_LOG_V(DEBUG, TAG,
512                       "Newly discovered device with address [%s] ", scanInfo->remote_address);
513
514             char *addr = OICStrdup(scanInfo->remote_address);
515             if (NULL == addr)
516             {
517                 oc_mutex_unlock(g_LEServerListMutex);
518                 OIC_LOG(ERROR, TAG, "Device address is NULL");
519                 return;
520             }
521             serverInfo = (LEServerInfo *)OICCalloc(1, sizeof(LEServerInfo));
522             if (NULL == serverInfo)
523             {
524                 oc_mutex_unlock(g_LEServerListMutex);
525                 OIC_LOG(ERROR, TAG, "Calloc failed");
526                 OICFree(addr);
527                 return;
528             }
529             serverInfo->remoteAddress = addr;
530             serverInfo->status = LE_STATUS_DISCOVERED;
531
532             if (CA_STATUS_OK != CAAddLEServerInfoToList(&g_LEServerList, serverInfo))
533             {
534                 oc_mutex_unlock(g_LEServerListMutex);
535                 OIC_LOG_V(ERROR, TAG, "Could not add [%s] to server list", scanInfo->remote_address);
536                 CAFreeLEServerInfo(serverInfo);
537                 return;
538             }
539         }else {
540             OIC_LOG_V(DEBUG, TAG,
541                       "Device Present with address [%s] ", scanInfo->remote_address);
542
543             if(serverInfo->status == LE_STATUS_UNICAST_PENDING){
544                 bt_gatt_client_h clientHandle = NULL;
545                 int32_t ret = bt_gatt_client_create(serverInfo->remoteAddress, &clientHandle);
546                 if (BT_ERROR_NONE != ret || NULL == clientHandle)
547                 {
548                     OIC_LOG_V(ERROR, TAG,
549                               "bt_gatt_client_create Failed with ret value [%s] ", CALEGetErrorMsg(ret));
550                     CALEGattDisConnect(serverInfo->remoteAddress);
551                     oc_mutex_unlock(g_LEServerListMutex);
552                     return ;
553                 }
554                 serverInfo->clientHandle = clientHandle;
555
556                 serverInfo->status = LE_STATUS_CONNECTION_INITIATED;
557                 if (CA_STATUS_OK != CALEGattInitiateConnection(serverInfo->remoteAddress))
558                 {
559                     OIC_LOG_V(ERROR, TAG, "Could not initiate connection to [%s]", serverInfo->remoteAddress);
560                     serverInfo->status = LE_STATUS_DISCOVERED;
561                     CADestroyLEDataList(&serverInfo->pendingDataList);
562                     oc_mutex_unlock(g_LEServerListMutex);
563                     return ;
564                 }
565             }
566         }
567         oc_mutex_unlock(g_LEServerListMutex);
568     }
569
570     OIC_LOG(DEBUG, TAG, "OUT");
571 }
572
573 void CASetLEClientThreadPoolHandle(ca_thread_pool_t handle)
574 {
575     OIC_LOG(DEBUG, TAG, "IN");
576
577     oc_mutex_lock(g_LEClientThreadPoolMutex);
578     g_LEClientThreadPool = handle;
579     oc_mutex_unlock(g_LEClientThreadPoolMutex);
580
581     OIC_LOG(DEBUG, TAG, "OUT");
582 }
583
584 void CASetLEReqRespClientCallback(CABLEDataReceivedCallback callback)
585 {
586     OIC_LOG(DEBUG, TAG, "IN");
587
588     oc_mutex_lock(g_LEReqRespClientCbMutex);
589
590     g_LEClientDataReceivedCallback = callback;
591
592     oc_mutex_unlock(g_LEReqRespClientCbMutex);
593
594     OIC_LOG(DEBUG, TAG, "OUT");
595 }
596
597 void CASetBLEClientErrorHandleCallback(CABLEErrorHandleCallback callback)
598 {
599     g_clientErrorCallback = callback;
600 }
601
602 CAResult_t CAStartLEGattClient()
603 {
604     OIC_LOG(DEBUG, TAG, "IN");
605
606     oc_mutex_lock(g_LEClientStateMutex);
607     if (true  == g_isLEGattClientStarted)
608     {
609         OIC_LOG(ERROR, TAG, "Gatt Client is already running!!");
610         oc_mutex_unlock(g_LEClientStateMutex);
611         return CA_STATUS_FAILED;
612     }
613
614     CAResult_t  result = CALEGattSetCallbacks();
615     if (CA_STATUS_OK != result)
616     {
617         OIC_LOG(ERROR, TAG, "CABleGattSetCallbacks Failed");
618         oc_mutex_unlock(g_LEClientStateMutex);
619         CATerminateLEGattClient();
620         return CA_STATUS_FAILED;
621     }
622
623     g_isLEGattClientStarted = true;
624     oc_mutex_unlock(g_LEClientStateMutex);
625
626     oc_mutex_lock(g_LEClientThreadPoolMutex);
627     if (NULL == g_LEClientThreadPool)
628     {
629         OIC_LOG(ERROR, TAG, "gBleServerThreadPool is NULL");
630         CATerminateGattClientMutexVariables();
631         oc_mutex_unlock(g_LEClientThreadPoolMutex);
632         return CA_STATUS_FAILED;
633     }
634
635     result = ca_thread_pool_add_task(g_LEClientThreadPool, CAStartTimerThread,
636                                      NULL, NULL);
637     if (CA_STATUS_OK != result)
638     {
639         OIC_LOG(ERROR, TAG, "ca_thread_pool_add_task failed");
640         CATerminateGattClientMutexVariables();
641         oc_mutex_unlock(g_LEClientThreadPoolMutex);
642         return CA_STATUS_FAILED;
643     }
644
645 #ifdef TIZEN_VD
646     result= ca_thread_pool_add_task(g_LEClientThreadPool, CALEClientScanThread,
647                                     NULL, NULL);
648     if (CA_STATUS_OK != result)
649     {
650         OIC_LOG(ERROR, TAG, "ca_thread_pool_add_task failed");
651         CATerminateGattClientMutexVariables();
652         oc_mutex_unlock(g_LEClientThreadPoolMutex);
653         return CA_STATUS_FAILED;
654     }
655 #endif
656     oc_mutex_unlock(g_LEClientThreadPoolMutex);
657
658     OIC_LOG(DEBUG, TAG, "OUT");
659     return CA_STATUS_OK;
660 }
661
662 #ifdef TIZEN_VD
663 void CALEClientScanThread()
664 {
665     oc_mutex_lock(g_scanMutex);
666     if (!g_isMulticastInProgress && !g_isUnicastScanInProgress)
667     {
668         CAResult_t result = CALEGattStartDeviceScanning();
669         if (CA_STATUS_OK != result)
670         {
671             oc_mutex_unlock(g_scanMutex);
672             OIC_LOG(ERROR, TAG, "CALEGattStartDeviceScanning failed");
673             return ;
674         }
675         g_isUnicastScanInProgress = true;
676         // Start Timer
677         oc_cond_signal(g_startTimerCond);
678     }
679     else
680     {
681         g_isUnicastScanInProgress = true;
682         // Reset Timer
683         oc_cond_signal(g_scanningTimeCond);
684     }
685     oc_mutex_unlock(g_scanMutex);
686
687     OIC_LOG(DEBUG, TAG, "OUT");
688     return ;
689 }
690 #endif
691
692 void CAStartTimerThread(void *data)
693 {
694     (void)data;
695
696     OIC_LOG(DEBUG, TAG, "IN");
697     while (g_isLEGattClientStarted)
698     {
699         oc_mutex_lock(g_scanMutex);
700         if (!g_isMulticastInProgress && !g_isUnicastScanInProgress)
701         {
702             OIC_LOG(DEBUG, TAG, "waiting....");
703             oc_cond_wait(g_startTimerCond, g_scanMutex);
704             OIC_LOG(DEBUG, TAG, "Wake up");
705         }
706
707         // Timed conditional wait for stopping the scan.
708         OCWaitResult_t ret = oc_cond_wait_for(g_scanningTimeCond, g_scanMutex,
709                                               TIMEOUT);
710         if (OC_WAIT_TIMEDOUT == ret)
711         {
712             OIC_LOG(DEBUG, TAG, "Scan is timed Out");
713             // Call stop scan.
714             CALEGattStopDeviceScanning();
715
716             if (g_isMulticastInProgress)
717             {
718                 oc_mutex_lock(g_multicastDataListMutex);
719                 // Clear the data list and device list.
720                 u_arraylist_destroy(g_multicastDataList);
721                 g_multicastDataList = NULL;
722                 oc_mutex_unlock(g_multicastDataListMutex);
723                 g_isMulticastInProgress = false;
724             }
725             g_isUnicastScanInProgress = false;
726         }
727         oc_mutex_unlock(g_scanMutex);
728     }
729
730     OIC_LOG(DEBUG, TAG, "OUT");
731 }
732
733 void CAStopLEGattClient()
734 {
735     OIC_LOG(DEBUG,  TAG, "IN");
736
737     oc_mutex_lock(g_LEClientStateMutex);
738
739     if (false == g_isLEGattClientStarted)
740     {
741         OIC_LOG(ERROR, TAG, "Gatt Client is not running to stop");
742         oc_mutex_unlock(g_LEClientStateMutex);
743         return;
744     }
745
746     CALEGattUnSetCallbacks();
747
748     CALEGattStopDeviceScanning();
749
750     g_isLEGattClientStarted = false;
751
752     // Signal the conditions waiting in Start timer.
753     oc_cond_signal(g_startTimerCond);
754     oc_cond_signal(g_scanningTimeCond);
755
756     // Destroy the multicast data list and device list if not empty.
757     if (NULL != g_multicastDataList)
758     {
759         oc_mutex_lock(g_multicastDataListMutex);
760         u_arraylist_destroy(g_multicastDataList);
761         g_multicastDataList = NULL;
762         oc_mutex_unlock(g_multicastDataListMutex);
763     }
764
765     oc_mutex_lock(g_LEServerListMutex);
766     CAFreeLEServerList(g_LEServerList);
767     g_LEServerList = NULL;
768     oc_mutex_unlock(g_LEServerListMutex);
769
770     oc_mutex_lock(g_threadWriteCharacteristicMutex);
771     oc_cond_signal(g_threadWriteCharacteristicCond);
772     oc_mutex_unlock(g_threadWriteCharacteristicMutex);
773
774     GMainContext  *context_event_loop = NULL;
775     // Required for waking up the thread which is running in gmain loop
776     if (NULL != g_eventLoop)
777     {
778         context_event_loop = g_main_loop_get_context(g_eventLoop);
779     }
780     if (context_event_loop)
781     {
782         OIC_LOG_V(DEBUG,  TAG, "g_eventLoop context %p", (void *)context_event_loop);
783         g_main_context_wakeup(context_event_loop);
784
785         // Kill g main loops and kill threads.
786         g_main_loop_quit(g_eventLoop);
787     }
788     else
789     {
790         OIC_LOG(ERROR, TAG, "g_eventLoop context is NULL");
791     }
792
793     oc_mutex_unlock(g_LEClientStateMutex);
794
795     OIC_LOG(DEBUG,  TAG, "OUT");
796 }
797
798 CAResult_t CAInitializeLEGattClient()
799 {
800     OIC_LOG(DEBUG, TAG, "Initialize GATT Client");
801     CAResult_t res = CAInitGattClientMutexVariables();
802     if (CA_STATUS_OK != res)
803     {
804         OIC_LOG(ERROR, TAG, "CAInitGattClientMutexVariables failed!");
805         CATerminateGattClientMutexVariables();
806         return CA_STATUS_FAILED;
807     }
808     return res;
809 }
810
811 void CATerminateLEGattClient()
812 {
813     OIC_LOG(DEBUG,  TAG, "IN");
814
815     CATerminateGattClientMutexVariables();
816
817     OIC_LOG(DEBUG,  TAG, "OUT");
818 }
819
820 CAResult_t CAInitGattClientMutexVariables()
821 {
822     OIC_LOG(DEBUG,  TAG, "IN");
823     if (NULL == g_LEClientStateMutex)
824     {
825         g_LEClientStateMutex = oc_mutex_new();
826         if (NULL == g_LEClientStateMutex)
827         {
828             OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
829             return CA_STATUS_FAILED;
830         }
831     }
832
833     if (NULL == g_LEServerListMutex)
834     {
835         g_LEServerListMutex = oc_mutex_new();
836         if (NULL == g_LEServerListMutex)
837         {
838             OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
839             return CA_STATUS_FAILED;
840         }
841     }
842
843     if (NULL == g_LEReqRespClientCbMutex)
844     {
845         g_LEReqRespClientCbMutex = oc_mutex_new();
846         if (NULL == g_LEReqRespClientCbMutex)
847         {
848             OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
849             return CA_STATUS_FAILED;
850         }
851     }
852
853     if (NULL == g_LEClientThreadPoolMutex)
854     {
855         g_LEClientThreadPoolMutex = oc_mutex_new();
856         if (NULL == g_LEClientThreadPoolMutex)
857         {
858             OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
859             return CA_STATUS_FAILED;
860         }
861     }
862
863     if (NULL == g_LEClientConnectMutex)
864     {
865         g_LEClientConnectMutex = oc_mutex_new();
866         if (NULL == g_LEClientConnectMutex)
867         {
868             OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
869             return CA_STATUS_FAILED;
870         }
871     }
872
873     if (NULL == g_isScanningInProgressMutex)
874     {
875         g_isScanningInProgressMutex = oc_mutex_new();
876         if (NULL == g_isScanningInProgressMutex)
877         {
878             OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
879             return CA_STATUS_FAILED;
880         }
881     }
882
883     if (NULL == g_isConnectionInProgressMutex)
884     {
885         g_isConnectionInProgressMutex = oc_mutex_new();
886         if (NULL == g_isConnectionInProgressMutex)
887         {
888             OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
889             return CA_STATUS_FAILED;
890         }
891     }
892
893     if (NULL == g_multicastDataListMutex)
894     {
895         g_multicastDataListMutex = oc_mutex_new();
896         if (NULL == g_multicastDataListMutex)
897         {
898             OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
899             return CA_STATUS_FAILED;
900         }
901     }
902
903     if (NULL == g_scanMutex)
904     {
905         g_scanMutex = oc_mutex_new();
906         if (NULL == g_scanMutex)
907         {
908             OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
909             return CA_STATUS_FAILED;
910         }
911     }
912
913     if (NULL == g_threadWriteCharacteristicMutex)
914     {
915         g_threadWriteCharacteristicMutex = oc_mutex_new();
916         if (NULL == g_threadWriteCharacteristicMutex)
917         {
918             OIC_LOG(ERROR, TAG, "oc_mutex_new has failed");
919             return CA_STATUS_FAILED;
920         }
921     }
922
923     if (NULL == g_threadMTUChangedMutex)
924     {
925         g_threadMTUChangedMutex = oc_mutex_new();
926         if (NULL == g_threadMTUChangedMutex)
927         {
928             OIC_LOG(ERROR, TAG, "oc_mutex_new has failed");
929             return CA_STATUS_FAILED;
930         }
931     }
932
933     if (NULL == g_isDisconnectedMutex)
934     {
935         g_isDisconnectedMutex = oc_mutex_new();
936         if (NULL == g_isDisconnectedMutex)
937         {
938             OIC_LOG(ERROR, TAG, "oc_mutex_new has failed");
939             return CA_STATUS_FAILED;
940         }
941     }
942
943     if (NULL == g_LEDisconnectedCond)
944     {
945         g_LEDisconnectedCond = oc_cond_new();
946         if (NULL == g_LEDisconnectedCond)
947         {
948             OIC_LOG(ERROR, TAG, "oc_cond_new failed");
949             return CA_STATUS_FAILED;
950         }
951     }
952
953     if (NULL == g_startTimerCond)
954     {
955         g_startTimerCond = oc_cond_new();
956         if (NULL == g_startTimerCond)
957         {
958             OIC_LOG(ERROR, TAG, "oc_cond_new failed");
959             return CA_STATUS_FAILED;
960         }
961     }
962
963     if (NULL == g_scanningTimeCond)
964     {
965         g_scanningTimeCond = oc_cond_new();
966         if (NULL == g_scanningTimeCond)
967         {
968             OIC_LOG(ERROR, TAG, "oc_cond_new failed");
969             return CA_STATUS_FAILED;
970         }
971     }
972
973     if (NULL == g_threadWriteCharacteristicCond)
974     {
975         g_threadWriteCharacteristicCond = oc_cond_new();
976         if (NULL == g_threadWriteCharacteristicCond)
977         {
978             OIC_LOG(ERROR, TAG, "oc_cond_new failed");
979             return CA_STATUS_FAILED;
980         }
981     }
982
983     if (NULL == g_threadMTUChangedCond)
984     {
985         g_threadMTUChangedCond = oc_cond_new();
986         if (NULL == g_threadMTUChangedCond)
987         {
988             OIC_LOG(ERROR, TAG, "oc_cond_new failed");
989             return CA_STATUS_FAILED;
990         }
991     }
992
993
994     OIC_LOG(DEBUG,  TAG, "OUT");
995     return CA_STATUS_OK;
996 }
997
998 void CATerminateGattClientMutexVariables()
999 {
1000     OIC_LOG(DEBUG,  TAG, "IN");
1001
1002     oc_mutex_free(g_LEClientStateMutex);
1003     g_LEClientStateMutex = NULL;
1004
1005     oc_mutex_free(g_LEServerListMutex);
1006     g_LEServerListMutex = NULL;
1007
1008     oc_mutex_free(g_LEReqRespClientCbMutex);
1009     g_LEReqRespClientCbMutex = NULL;
1010
1011     oc_mutex_free(g_LEClientConnectMutex);
1012     g_LEClientConnectMutex = NULL;
1013
1014     oc_mutex_free(g_LEClientThreadPoolMutex);
1015     g_LEClientThreadPoolMutex = NULL;
1016
1017     oc_mutex_free(g_isScanningInProgressMutex);
1018     g_isScanningInProgressMutex = NULL;
1019
1020     oc_mutex_free(g_isConnectionInProgressMutex);
1021     g_isConnectionInProgressMutex = NULL;
1022
1023     oc_mutex_free(g_multicastDataListMutex);
1024     g_multicastDataListMutex = NULL;
1025
1026     oc_mutex_free(g_scanMutex);
1027     g_scanMutex = NULL;
1028
1029     oc_mutex_free(g_threadWriteCharacteristicMutex);
1030     g_threadWriteCharacteristicMutex = NULL;
1031
1032     oc_mutex_free(g_threadMTUChangedMutex);
1033     g_threadMTUChangedMutex = NULL;
1034
1035     oc_mutex_free(g_isDisconnectedMutex);
1036     g_isDisconnectedMutex = NULL;
1037
1038     oc_cond_free(g_LEDisconnectedCond);
1039     g_LEDisconnectedCond = NULL;
1040
1041     oc_cond_free(g_startTimerCond);
1042     g_startTimerCond = NULL;
1043
1044     oc_cond_free(g_scanningTimeCond);
1045     g_scanningTimeCond = NULL;
1046
1047     oc_cond_free(g_threadWriteCharacteristicCond);
1048     g_threadWriteCharacteristicCond = NULL;
1049     g_isSignalSetFlag = false;
1050
1051     oc_cond_free(g_threadMTUChangedCond);
1052     g_threadMTUChangedCond = NULL;
1053
1054     OIC_LOG(DEBUG,  TAG, "OUT");
1055 }
1056
1057 CAResult_t CALEGattSetCallbacks()
1058 {
1059     OIC_LOG(DEBUG, TAG, "IN");
1060
1061     OIC_LOG(DEBUG, TAG, "OUT");
1062     return CA_STATUS_OK;
1063 }
1064
1065 void CALEGattUnSetCallbacks()
1066 {
1067     OIC_LOG(DEBUG, TAG, "IN");
1068
1069     bt_gatt_unset_connection_state_changed_cb();
1070
1071     oc_mutex_lock(g_LEServerListMutex);
1072     LEServerInfoList *curNode = g_LEServerList;
1073     while (curNode)
1074     {
1075         LEServerInfo *serverInfo = curNode->serverInfo;
1076         if (serverInfo->status >= LE_STATUS_SERVICES_DISCOVERED)
1077         {
1078             bt_gatt_client_unset_characteristic_value_changed_cb(serverInfo->readChar);
1079         }
1080         curNode = curNode->next;
1081     }
1082     oc_mutex_unlock(g_LEServerListMutex);
1083
1084     OIC_LOG(DEBUG, TAG, "OUT");
1085 }
1086
1087 CAResult_t CALEGattStartDeviceScanning()
1088 {
1089     OIC_LOG(DEBUG, TAG, "IN");
1090
1091     oc_mutex_lock(g_isScanningInProgressMutex);
1092     if (!g_isScanningInProgress)
1093     {
1094         int ret = bt_adapter_le_start_scan(CALEAdapterScanResultCb, NULL);
1095         if (BT_ERROR_NONE != ret)
1096         {
1097             oc_mutex_unlock(g_isScanningInProgressMutex);
1098             OIC_LOG_V(ERROR, TAG, "bt_adapter_le_start_scan failed[%s]",
1099                       CALEGetErrorMsg(ret));
1100             return CA_STATUS_FAILED;
1101         }
1102         g_isScanningInProgress = true;
1103     }
1104     else
1105     {
1106         OIC_LOG(DEBUG, TAG, "Ignore, scanning already in progress");
1107     }
1108     oc_mutex_unlock(g_isScanningInProgressMutex);
1109
1110     OIC_LOG(DEBUG, TAG, "OUT");
1111     return CA_STATUS_OK;
1112 }
1113
1114 void CALEGattStopDeviceScanning()
1115 {
1116     OIC_LOG(DEBUG, TAG, "IN");
1117
1118     oc_mutex_lock(g_isScanningInProgressMutex);
1119     if (g_isScanningInProgress)
1120     {
1121         int ret = bt_adapter_le_stop_scan();
1122         if (BT_ERROR_NONE != ret)
1123         {
1124             oc_mutex_unlock(g_isScanningInProgressMutex);
1125             OIC_LOG_V(ERROR, TAG, "bt_adapter_le_stop_scan failed[%s]",
1126                       CALEGetErrorMsg(ret));
1127             return;
1128         }
1129         g_isScanningInProgress = false;
1130         g_isUnicastScanInProgress= false;
1131     }
1132     else
1133     {
1134         OIC_LOG(DEBUG, TAG, "Ignore, scanning not in progress");
1135     }
1136     oc_mutex_unlock(g_isScanningInProgressMutex);
1137
1138     OIC_LOG(DEBUG, TAG, "OUT");
1139 }
1140
1141 void CAGattConnectThread (void *remoteAddress)
1142 {
1143     OIC_LOG(DEBUG, TAG, "IN ");
1144
1145     VERIFY_NON_NULL_VOID(remoteAddress, TAG, "remote address is NULL");
1146
1147     char *address  = (char *)remoteAddress;
1148
1149     OIC_LOG_V(DEBUG, TAG, "remote address is [%s]", address);
1150
1151     CAResult_t result = CALEGattConnect(address);
1152
1153     if (CA_STATUS_OK != result)
1154     {
1155         OIC_LOG_V(ERROR, TAG, "bt_gatt_connect failed for [%s]", address);
1156     }
1157
1158     OICFree(address);
1159
1160     OIC_LOG(DEBUG, TAG, "OUT");
1161 }
1162
1163 CAResult_t CALEGattConnect(const char *remoteAddress)
1164 {
1165     OIC_LOG(DEBUG, TAG, "IN");
1166
1167     VERIFY_NON_NULL_RET(remoteAddress, TAG,
1168                         "remote address is NULL", CA_STATUS_FAILED);
1169
1170     oc_mutex_lock(g_LEClientConnectMutex);
1171     CAResult_t result = CA_STATUS_OK;
1172
1173 #ifdef TIZEN_VD
1174     int ret = bt_gatt_connect(remoteAddress, true);
1175 #else
1176     int ret = bt_gatt_connect(remoteAddress, false);
1177 #endif
1178     if (BT_ERROR_NONE != ret)
1179     {
1180         OIC_LOG_V(ERROR, TAG, "bt_gatt_connect Failed with ret value [%s] ",
1181                   CALEGetErrorMsg(ret));
1182         oc_mutex_unlock(g_LEClientConnectMutex);
1183         return CA_STATUS_FAILED;
1184     }
1185
1186     oc_mutex_unlock(g_LEClientConnectMutex);
1187
1188     OIC_LOG(DEBUG, TAG, "OUT");
1189     return result;
1190 }
1191
1192 CAResult_t CALEGattDisConnect(const char *remoteAddress)
1193 {
1194     OIC_LOG(DEBUG, TAG, "IN");
1195
1196     VERIFY_NON_NULL_RET(remoteAddress, TAG,
1197                         "remote address is NULL", CA_STATUS_FAILED);
1198
1199     int ret = bt_gatt_disconnect(remoteAddress);
1200
1201     if (BT_ERROR_NONE != ret)
1202     {
1203         OIC_LOG_V(ERROR, TAG, "bt_gatt_disconnect Failed with ret value [%s] ",
1204                   CALEGetErrorMsg(ret));
1205         return CA_STATUS_FAILED;
1206     }
1207
1208     OIC_LOG(DEBUG, TAG, "OUT");
1209     return CA_STATUS_OK;
1210 }
1211
1212 CAResult_t CAUpdateCharacteristicsToGattServerImpl(LEServerInfo *serverInfo,
1213         const uint8_t *data, const uint32_t dataLen)
1214 {
1215     OIC_LOG(DEBUG, TAG, "IN");
1216
1217     VERIFY_NON_NULL(serverInfo, TAG, "Server Info is NULL");
1218
1219     CALEGattStopDeviceScanning();
1220
1221     OIC_LOG_V(DEBUG, TAG, "Updating the data of length [%d] to [%s] ", dataLen,
1222               serverInfo->remoteAddress);
1223
1224     int result = bt_gatt_set_value(serverInfo->writeChar, (char *)data, dataLen);
1225
1226     if (BT_ERROR_NONE != result)
1227     {
1228         OIC_LOG_V(ERROR, TAG,
1229                   "bt_gatt_set_value Failed with return val [%s]",
1230                   CALEGetErrorMsg(result));
1231         goto exit;
1232     }
1233
1234     result = bt_gatt_client_write_value(serverInfo->writeChar, CALEGattCharacteristicWriteCb,
1235                                         NULL);
1236     if (BT_ERROR_NONE != result)
1237     {
1238         OIC_LOG_V(ERROR, TAG,
1239                   "bt_gatt_client_write_value Failed with return val [%s]",
1240                   CALEGetErrorMsg(result));
1241         goto exit;
1242     }
1243
1244     // wait for callback for write Characteristic with success to sent data
1245     OIC_LOG_V(DEBUG, TAG, "callback flag is %d", g_isSignalSetFlag);
1246     oc_mutex_lock(g_threadWriteCharacteristicMutex);
1247     if (!g_isSignalSetFlag)
1248     {
1249         OIC_LOG(DEBUG, TAG, "wait for callback to notify writeCharacteristic is success");
1250         if (OC_WAIT_SUCCESS != oc_cond_wait_for(g_threadWriteCharacteristicCond,
1251                                                 g_threadWriteCharacteristicMutex,
1252                                                 WAIT_TIME_WRITE_CHARACTERISTIC))
1253         {
1254             g_isSignalSetFlag = false;
1255             oc_mutex_unlock(g_threadWriteCharacteristicMutex);
1256             OIC_LOG(ERROR, TAG, "there is no response. write has failed");
1257             goto exit;
1258         }
1259     }
1260     // reset flag set by writeCharacteristic Callback
1261     g_isSignalSetFlag = false;
1262     oc_mutex_unlock(g_threadWriteCharacteristicMutex);
1263
1264     oc_mutex_lock(g_scanMutex);
1265     if (g_isMulticastInProgress || g_isUnicastScanInProgress)
1266     {
1267         if (CA_STATUS_OK != CALEGattStartDeviceScanning())
1268         {
1269             OIC_LOG(ERROR, TAG, "Could not start device scanning");
1270         }
1271     }
1272     oc_mutex_unlock(g_scanMutex);
1273     OIC_LOG(DEBUG, TAG, "OUT");
1274     return CA_STATUS_OK;
1275
1276 exit:
1277     oc_mutex_lock(g_scanMutex);
1278     if (g_isMulticastInProgress || g_isUnicastScanInProgress)
1279     {
1280         if (CA_STATUS_OK != CALEGattStartDeviceScanning())
1281         {
1282             OIC_LOG(ERROR, TAG, "Could not start device scanning");
1283         }
1284     }
1285     oc_mutex_unlock(g_scanMutex);
1286
1287     OIC_LOG(DEBUG, TAG, "OUT");
1288     return CA_STATUS_FAILED;
1289 }
1290
1291 void CADiscoverLEServicesThread(void *remoteAddress)
1292 {
1293     OIC_LOG(DEBUG, TAG, "IN");
1294
1295     VERIFY_NON_NULL_VOID(remoteAddress, TAG, "remote address is NULL");
1296
1297     char *address  = (char *)remoteAddress;
1298
1299     CAResult_t result = CALEGattDiscoverServices(address);
1300     if (CA_STATUS_OK != result)
1301     {
1302         OIC_LOG(ERROR, TAG, "CALEGattDiscoverServices failed");
1303     }
1304
1305     OICFree(address);
1306     OIC_LOG(DEBUG, TAG, "OUT");
1307 }
1308
1309 static int CALEWaittillDisconnect(oc_mutex mutex, oc_cond cv, int wait_seconds)
1310 {
1311     OIC_LOG(DEBUG, TAG, "Waiting for server to be disconnected...");
1312     oc_mutex_lock(mutex);
1313     uint64_t wait_time = wait_seconds * MICROSECS_PER_SEC;
1314     int ret = oc_cond_wait_for(cv, mutex, wait_time);
1315     oc_mutex_unlock(mutex);
1316     return ret;
1317 }
1318
1319 static CAResult_t CALEGattConnectionRetry(const char *remoteAddress)
1320 {
1321     OIC_LOG(DEBUG, TAG, "IN");
1322
1323     VERIFY_NON_NULL_RET(remoteAddress, TAG,
1324                         "remote address is NULL", CA_STATUS_FAILED);
1325
1326     CALEGattDisConnect(remoteAddress);
1327     CALEWaittillDisconnect(g_isDisconnectedMutex, g_LEDisconnectedCond, 10);
1328     CAResult_t result = CALEGattConnect(remoteAddress);
1329     OIC_LOG(DEBUG, TAG, "OUT");
1330     return result;
1331 }
1332
1333 CAResult_t CALEGattDiscoverServices(const char *remoteAddress)
1334 {
1335     OIC_LOG(DEBUG, TAG, "IN");
1336
1337     VERIFY_NON_NULL_RET(remoteAddress, TAG,
1338                         "remote address is NULL", CA_STATUS_FAILED);
1339
1340     LEServerInfo *serverInfo = NULL;
1341     unsigned int mtu_size;
1342     oc_mutex_lock(g_LEServerListMutex);
1343     if (CA_STATUS_OK != CAGetLEServerInfo(g_LEServerList, remoteAddress, &serverInfo))
1344     {
1345         oc_mutex_unlock(g_LEServerListMutex);
1346         OIC_LOG_V(ERROR, TAG, "Could not get server info for [%s]", remoteAddress);
1347         CALEGattDisConnect(remoteAddress);
1348         return CA_STATUS_FAILED;
1349     }
1350
1351     bt_gatt_h serviceHandle = NULL;
1352     int32_t ret = bt_gatt_client_get_service(serverInfo->clientHandle, CA_GATT_SERVICE_UUID, &serviceHandle);
1353     if (BT_ERROR_NONE != ret || NULL == serviceHandle)
1354     {
1355         OIC_LOG_V(ERROR, TAG,
1356                   "bt_gatt_client_get_service Failed with ret value [%s] ", CALEGetErrorMsg(ret));
1357
1358         if(g_retrycount)
1359         {
1360             OIC_LOG(DEBUG, TAG, "Retry will be attempted to connect Gatt Server");
1361             g_retrycount--;
1362             retry_flag = 1;
1363             OIC_LOG_V(DEBUG, TAG, "Retry count left %d time(s)", g_retrycount);
1364             CAResult_t result = CALEGattConnectionRetry(remoteAddress);
1365             if(result == CA_STATUS_FAILED)
1366             {
1367                 goto error_exit;
1368             }
1369             else
1370             {
1371                 oc_mutex_unlock(g_LEServerListMutex);
1372                 OIC_LOG(ERROR, TAG, "Previous connection attempt failed, attempting to retry again");
1373                 OIC_LOG_V(DEBUG, TAG, "Retry count left %d time(s)", g_retrycount);
1374                 return CA_STATUS_FAILED;
1375             }
1376         }
1377     }
1378
1379     retry_flag = 0;
1380     // Server will read data on this characteristic.
1381     bt_gatt_h writeChrHandle = NULL;
1382     ret = bt_gatt_service_get_characteristic(serviceHandle, CA_GATT_REQUEST_CHRC_UUID,
1383             &writeChrHandle);
1384     if (BT_ERROR_NONE != ret || NULL == writeChrHandle)
1385     {
1386         OIC_LOG_V(ERROR, TAG,
1387                   "bt_gatt_service_get_characteristic Failed with ret value [%s] ",
1388                   CALEGetErrorMsg(ret));
1389         goto error_exit;
1390     }
1391
1392     // Server will notify data on this characteristic.
1393     bt_gatt_h readChrHandle = NULL;
1394     ret = bt_gatt_service_get_characteristic(serviceHandle, CA_GATT_RESPONSE_CHRC_UUID,
1395             &readChrHandle);
1396     if (BT_ERROR_NONE != ret || NULL == readChrHandle)
1397     {
1398         OIC_LOG_V(ERROR, TAG,
1399                   "bt_gatt_service_get_characteristic Failed with ret value [%s] ",
1400                   CALEGetErrorMsg(ret));
1401         goto error_exit;
1402     }
1403
1404
1405     //TODO: This data has to be freed while unsetting the callback.
1406     char *addr = OICStrdup(remoteAddress);
1407     if (NULL == addr)
1408     {
1409         OIC_LOG(ERROR, TAG, "addr is NULL");
1410         goto error_exit;
1411     }
1412
1413     ret = bt_gatt_client_set_characteristic_value_changed_cb(readChrHandle,
1414             CALEGattCharacteristicChangedCb,
1415             (void *)addr);
1416     if (BT_ERROR_NONE != ret)
1417     {
1418         OIC_LOG_V(ERROR, TAG,
1419                   "bt_gatt_client_set_characteristic_value_changed_cb Failed with ret value [%s]",
1420                   CALEGetErrorMsg(ret));
1421         goto error_exit;
1422     }
1423
1424     ret = bt_gatt_client_set_att_mtu_changed_cb(serverInfo->clientHandle,
1425             CALEGattClientMTUChangedCb,
1426             (void *)serverInfo->remoteAddress);
1427     if (BT_ERROR_NONE != ret)
1428     {
1429         OIC_LOG_V(ERROR, TAG,
1430                   "bt_gatt_client_set_att_mtu_changed_cb Failed with ret value [%s]",
1431                   CALEGetErrorMsg(ret));
1432         goto error_exit;
1433     }
1434
1435     oc_mutex_lock(g_threadMTUChangedMutex);
1436     ret = bt_gatt_client_request_att_mtu_change(serverInfo->clientHandle, CA_SUPPORTED_BLE_MTU_SIZE - CA_BLE_MTU_HEADER_SIZE);
1437     if (BT_ERROR_NONE != ret)
1438     {
1439         OIC_LOG_V(ERROR, TAG,
1440                   "bt_gatt_client_request_att_mtu_change Failed with ret value [%s]",
1441                   CALEGetErrorMsg(ret));
1442         oc_mutex_unlock(g_threadMTUChangedMutex);
1443         goto error_exit;
1444     }
1445
1446     OIC_LOG(DEBUG, TAG, "wait for callback to notify MTU Changed Callback");
1447     oc_cond_wait(g_threadMTUChangedCond, g_threadMTUChangedMutex);
1448     oc_mutex_unlock(g_threadMTUChangedMutex);
1449
1450     OIC_LOG(DEBUG, TAG, "Done MTU");
1451     ret = bt_gatt_client_get_att_mtu(serverInfo->clientHandle, &mtu_size);
1452     if (BT_ERROR_NONE != ret)
1453     {
1454         OIC_LOG_V(ERROR, TAG,
1455                   "bt_gatt_client_get_att_mtu Failed with ret value [%s]",
1456                   CALEGetErrorMsg(ret));
1457         goto error_exit;
1458     }
1459     OIC_LOG_V(DEBUG, TAG,"Negotiated MTU Size %d",mtu_size);
1460
1461     serverInfo->serviceHandle = serviceHandle;
1462     serverInfo->readChar = readChrHandle;
1463     serverInfo->writeChar = writeChrHandle;
1464     serverInfo->status = LE_STATUS_SERVICES_DISCOVERED;
1465     serverInfo->mtu_size = mtu_size;
1466
1467     while (serverInfo->pendingDataList)
1468     {
1469         LEData *leData = serverInfo->pendingDataList->data;
1470         if (CA_STATUS_OK != CAUpdateCharacteristicsToGattServerImpl(
1471                 serverInfo, leData->data, leData->dataLength))
1472         {
1473             OIC_LOG_V(ERROR, TAG, "Failed to send pending data to [%s]",
1474                       serverInfo->remoteAddress);
1475
1476             CADestroyLEDataList(&serverInfo->pendingDataList);
1477             break;
1478         }
1479         CARemoveLEDataFromList(&serverInfo->pendingDataList);
1480     }
1481     oc_mutex_unlock(g_LEServerListMutex);
1482
1483     OIC_LOG(DEBUG, TAG, "OUT");
1484     return CA_STATUS_OK;
1485
1486 error_exit:
1487     bt_gatt_client_destroy(serverInfo->clientHandle);
1488     serverInfo->clientHandle = NULL;
1489     oc_mutex_unlock(g_LEServerListMutex);
1490     CALEGattDisConnect(remoteAddress);
1491     return CA_STATUS_FAILED;
1492 }
1493
1494 CAResult_t CAUpdateCharacteristicsToGattServer(const char *remoteAddress,
1495         const uint8_t *data, const uint32_t dataLen,
1496         CALETransferType_t type, const int32_t position)
1497 {
1498     OIC_LOG(DEBUG, TAG, "IN");
1499
1500     VERIFY_NON_NULL(data, TAG, "data is NULL");
1501
1502     if (0 == dataLen)
1503     {
1504         OIC_LOG(ERROR, TAG, "dataLen is less than or equal zero. Invalid input!");
1505         return CA_STATUS_INVALID_PARAM;
1506     }
1507
1508     LEServerInfo *serverInfo = NULL;
1509     bool isConnected = false;
1510     oc_mutex_lock(g_LEServerListMutex);
1511     if (LE_UNICAST == type)
1512     {
1513         if (CA_STATUS_OK != CAGetLEServerInfo(g_LEServerList, remoteAddress, &serverInfo))
1514         {
1515             OIC_LOG_V(DEBUG, TAG,
1516                       "Device with address [%s] not yet found, initiating scan",
1517                       remoteAddress);
1518
1519             char *addr = OICStrdup(remoteAddress);
1520             if (NULL == addr)
1521             {
1522                 oc_mutex_unlock(g_LEServerListMutex);
1523                 OIC_LOG(ERROR, TAG, "Device address is NULL");
1524                 return CA_STATUS_FAILED;
1525             }
1526             serverInfo = (LEServerInfo *)OICCalloc(1, sizeof(LEServerInfo));
1527             if (NULL == serverInfo)
1528             {
1529                 oc_mutex_unlock(g_LEServerListMutex);
1530                 OIC_LOG(ERROR, TAG, "Calloc failed");
1531                 OICFree(addr);
1532                 return CA_STATUS_FAILED;
1533             }
1534             serverInfo->remoteAddress = addr;
1535             serverInfo->status = LE_STATUS_UNICAST_PENDING;
1536
1537             if (CA_STATUS_OK != CAAddLEServerInfoToList(&g_LEServerList, serverInfo))
1538             {
1539                 oc_mutex_unlock(g_LEServerListMutex);
1540                 OIC_LOG_V(ERROR, TAG, "Could not add [%s] to server list", remoteAddress);
1541                 CAFreeLEServerInfo(serverInfo);
1542                 return CA_STATUS_FAILED;
1543             }
1544
1545             if (CA_STATUS_OK != CAAddLEDataToList(&serverInfo->pendingDataList, data, dataLen))
1546             {
1547                 oc_mutex_unlock(g_LEServerListMutex);
1548                 OIC_LOG(ERROR, TAG, "Could not add data to pending list");
1549                 return CA_STATUS_FAILED;
1550             }
1551         }
1552
1553         if(serverInfo->status == LE_STATUS_UNICAST_PENDING)
1554         {
1555
1556             int ret = bt_device_is_profile_connected(remoteAddress, BT_PROFILE_GATT, &isConnected);
1557             if (BT_ERROR_NONE != ret)
1558             {
1559                 OIC_LOG_V(ERROR, TAG, "bt_device_is_profile_connected Failed with ret value [%s] ",
1560                           CALEGetErrorMsg(ret));
1561                 oc_mutex_unlock(g_LEServerListMutex);
1562                 return CA_STATUS_FAILED;
1563             }
1564
1565             if (isConnected){
1566                 OIC_LOG_V(DEBUG, TAG, "Already connected to address [%s]", remoteAddress);
1567                 serverInfo->status = LE_STATUS_CONNECTED;
1568             } else {
1569                 oc_mutex_lock(g_scanMutex);
1570                 if (!g_isMulticastInProgress && !g_isUnicastScanInProgress)
1571                 {
1572                     CAResult_t result = CALEGattStartDeviceScanning();
1573                     if (CA_STATUS_OK != result)
1574                     {
1575                         oc_mutex_unlock(g_scanMutex);
1576                         OIC_LOG(ERROR, TAG, "CALEGattStartDeviceScanning failed");
1577                         oc_mutex_unlock(g_LEServerListMutex);
1578                         return CA_STATUS_FAILED;
1579                     }
1580                     g_isUnicastScanInProgress = true;
1581                     // Start Timer
1582                     oc_cond_signal(g_startTimerCond);
1583                 }
1584                 else
1585                 {
1586                     g_isUnicastScanInProgress = true;
1587                     // Reset Timer
1588                     oc_cond_signal(g_scanningTimeCond);
1589                 }
1590                 oc_mutex_unlock(g_scanMutex);
1591               }
1592
1593         }
1594
1595         if (serverInfo->status == LE_STATUS_CONNECTED)
1596         {
1597             oc_mutex_lock(g_LEClientThreadPoolMutex);
1598             if (NULL == g_LEClientThreadPool)
1599             {
1600                 oc_mutex_unlock(g_LEClientThreadPoolMutex);
1601                 OIC_LOG(ERROR, TAG, "g_LEClientThreadPool is NULL");
1602                 oc_mutex_unlock(g_LEServerListMutex);
1603                 return CA_STATUS_FAILED;
1604             }
1605             char *addr = OICStrdup(remoteAddress);
1606             if (NULL == addr)
1607             {
1608                 oc_mutex_unlock(g_LEClientThreadPoolMutex);
1609                 OIC_LOG(ERROR, TAG, "addr is NULL");
1610                 oc_mutex_unlock(g_LEServerListMutex);
1611                 return CA_STATUS_FAILED;
1612             }
1613             CAResult_t ret = ca_thread_pool_add_task(g_LEClientThreadPool, CADiscoverLEServicesThread,
1614                                                      addr, NULL);
1615             oc_mutex_unlock(g_LEClientThreadPoolMutex);
1616             if (CA_STATUS_OK != ret)
1617             {
1618                 OIC_LOG_V(ERROR, TAG, "ca_thread_pool_add_task failed with ret [%d]", ret);
1619                 OICFree(addr);
1620             }
1621         }
1622
1623         if (serverInfo->status == LE_STATUS_DISCOVERED)
1624         {
1625             if (CA_STATUS_OK != CAAddLEDataToList(&serverInfo->pendingDataList, data, dataLen))
1626             {
1627                 oc_mutex_unlock(g_LEServerListMutex);
1628                 OIC_LOG(ERROR, TAG, "Could not add data to pending list");
1629                 return CA_STATUS_FAILED;
1630             }
1631
1632             bt_gatt_client_h clientHandle = NULL;
1633             int32_t ret = bt_gatt_client_create(serverInfo->remoteAddress, &clientHandle);
1634             if (BT_ERROR_NONE != ret || NULL == clientHandle)
1635             {
1636                 OIC_LOG_V(ERROR, TAG,
1637                           "bt_gatt_client_create Failed with ret value [%s] ", CALEGetErrorMsg(ret));
1638                 CALEGattDisConnect(serverInfo->remoteAddress);
1639                 oc_mutex_unlock(g_LEServerListMutex);
1640                 return CA_STATUS_FAILED;
1641             }
1642             serverInfo->clientHandle = clientHandle;
1643
1644             serverInfo->status = LE_STATUS_CONNECTION_INITIATED;
1645             if (CA_STATUS_OK != CALEGattInitiateConnection(serverInfo->remoteAddress))
1646             {
1647                 OIC_LOG_V(ERROR, TAG, "Could not initiate connection to [%s]", serverInfo->remoteAddress);
1648                 serverInfo->status = LE_STATUS_DISCOVERED;
1649                 CADestroyLEDataList(&serverInfo->pendingDataList);
1650                 oc_mutex_unlock(g_LEServerListMutex);
1651                 return CA_STATUS_FAILED;
1652             }
1653         }
1654         else if (serverInfo->status < LE_STATUS_SERVICES_DISCOVERED)
1655         {
1656             if (CA_STATUS_OK != CAAddLEDataToList(&serverInfo->pendingDataList, data, dataLen))
1657             {
1658                 oc_mutex_unlock(g_LEServerListMutex);
1659                 OIC_LOG(ERROR, TAG, "Could not add data to pending list");
1660                 return CA_STATUS_FAILED;
1661             }
1662         }
1663         else
1664         {
1665             if (CA_STATUS_OK != CAUpdateCharacteristicsToGattServerImpl(serverInfo, data, dataLen))
1666             {
1667                 OIC_LOG_V(ERROR, TAG, "Could not update characteristic to gatt server [%s]",
1668                           serverInfo->remoteAddress);
1669                 oc_mutex_unlock(g_LEServerListMutex);
1670                 return CA_STATUS_FAILED;
1671             }
1672         }
1673     }
1674     else if (LE_MULTICAST == type)
1675     {
1676         OIC_LOG(ERROR, TAG, "LE_MULTICAST type Not used");
1677     }
1678     oc_mutex_unlock(g_LEServerListMutex);
1679     OIC_LOG(DEBUG, TAG, "OUT");
1680     return CA_STATUS_OK;
1681 }
1682
1683 CAResult_t CAUpdateCharacteristicsToAllGattServers(const uint8_t *data, uint32_t dataLen)
1684 {
1685     OIC_LOG(DEBUG,  TAG, "IN");
1686
1687     VERIFY_NON_NULL(data, TAG, "data is NULL");
1688
1689     if (0 == dataLen)
1690     {
1691         OIC_LOG(ERROR, TAG, "dataLen is less than or equal zero. Invalid input !");
1692         return CA_STATUS_INVALID_PARAM;
1693     }
1694
1695     oc_mutex_lock(g_LEServerListMutex);
1696     LEServerInfoList *curNode = g_LEServerList;
1697     while (curNode)
1698     {
1699         LEServerInfo *serverInfo = curNode->serverInfo;
1700         if (serverInfo->status == LE_STATUS_SERVICES_DISCOVERED)
1701         {
1702             if (CA_STATUS_OK != CAUpdateCharacteristicsToGattServerImpl(serverInfo, data, dataLen))
1703             {
1704                 OIC_LOG_V(ERROR, TAG, "Failed to update characteristics to gatt server [%s]",
1705                           serverInfo->remoteAddress);
1706             }
1707         }
1708         else if (serverInfo->status != LE_STATUS_INVALID)
1709         {
1710             if (CA_STATUS_OK != CAAddLEDataToList(&serverInfo->pendingDataList, data, dataLen))
1711             {
1712                 OIC_LOG(ERROR, TAG, "Failed to add to pending list");
1713             }
1714         }
1715         curNode = curNode->next;
1716     }
1717     oc_mutex_unlock(g_LEServerListMutex);
1718
1719     // Add the data to pending list.
1720     LEData *multicastData = (LEData *)OICCalloc(1, sizeof(LEData));
1721     if (NULL == multicastData)
1722     {
1723         OIC_LOG(ERROR, TAG, "Calloc failed");
1724         goto exit;
1725     }
1726     multicastData->data = OICCalloc(1, dataLen);
1727     if (NULL == multicastData->data)
1728     {
1729         OIC_LOG(ERROR, TAG, "Calloc failed");
1730         goto exit;
1731     }
1732     memcpy(multicastData->data, data, dataLen);
1733     multicastData->dataLength = dataLen;
1734
1735     oc_mutex_lock(g_multicastDataListMutex);
1736     if (NULL == g_multicastDataList)
1737     {
1738         g_multicastDataList = u_arraylist_create();
1739     }
1740     u_arraylist_add(g_multicastDataList, (void *)multicastData);
1741     oc_mutex_unlock(g_multicastDataListMutex);
1742
1743     // Start the scanning, if not started, else reset timer
1744     oc_mutex_lock(g_scanMutex);
1745     if (!g_isMulticastInProgress && !g_isUnicastScanInProgress)
1746     {
1747         CAResult_t result = CALEGattStartDeviceScanning();
1748         if (CA_STATUS_OK != result)
1749         {
1750             oc_mutex_unlock(g_scanMutex);
1751             OIC_LOG(ERROR, TAG, "CALEGattStartDeviceScanning Failed");
1752             goto exit;
1753         }
1754         g_isMulticastInProgress = true;
1755         // Start the timer by signalling it
1756         oc_cond_signal(g_startTimerCond);
1757     }
1758     else
1759     {
1760         g_isMulticastInProgress = true;
1761         // Reset timer
1762         oc_cond_signal(g_scanningTimeCond);
1763     }
1764     oc_mutex_unlock(g_scanMutex);
1765
1766 exit:
1767     OIC_LOG(DEBUG, TAG, "OUT ");
1768     return CA_STATUS_OK;
1769 }
1770
1771 uint16_t CALEClientGetMtuSize(const char* remote_address)
1772 {
1773     LEServerInfo *serverInfo = NULL;
1774     oc_mutex_lock(g_LEServerListMutex);
1775     if (CA_STATUS_OK == CAGetLEServerInfo(g_LEServerList, remote_address, &serverInfo))
1776     {
1777         if (serverInfo->status == LE_STATUS_SERVICES_DISCOVERED){
1778             OIC_LOG_V(DEBUG, TAG, "Mtu Size [%d]", serverInfo->mtu_size);
1779             oc_mutex_unlock(g_LEServerListMutex);
1780             OIC_LOG_V(INFO, TAG, "Returning Mtu Size [%d]", serverInfo->mtu_size - CA_BLE_MTU_HEADER_SIZE);
1781             return serverInfo->mtu_size - CA_BLE_MTU_HEADER_SIZE;
1782         }
1783     }
1784     oc_mutex_unlock(g_LEServerListMutex);
1785     return CA_DEFAULT_BLE_MTU_SIZE;
1786
1787 }
1788
1789 bool CALEClientIsConnected(const char* address)
1790 {
1791     (void)address;
1792     //@Todo
1793     return true;
1794 }
1795
1796 CAResult_t CALEClientSetMtuSize(const char* address, uint16_t mtuSize)
1797 {
1798     (void)mtuSize;
1799
1800     VERIFY_NON_NULL(address, TAG, "address is null");
1801     //@Todo
1802     //it should be implemented after update Tizen 3.0
1803     return CA_NOT_SUPPORTED;
1804 }
1805
1806 CAResult_t CALEClientSendNegotiationMessage(const char* address)
1807 {
1808     OIC_LOG_V(DEBUG, TAG, "CALEClientSendNegotiationMessage(%s)", address);
1809     //@Todo
1810     //it will be implemented when tizen public 3.0 is released.
1811     return CA_NOT_SUPPORTED;
1812 }