Adding retry logic for gatt connection for VD client
[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_VOID(remoteAddress, TAG, "remote address is NULL")
1324
1325     CALEGattDisConnect(remoteAddress);
1326     CALEWaittillDisconnect(g_isDisconnectedMutex, g_LEDisconnectedCond, 10);
1327     CAResult_t result = CALEGattConnect(remoteAddress);
1328     OIC_LOG(DEBUG, TAG, "OUT");
1329     return result;
1330 }
1331
1332 CAResult_t CALEGattDiscoverServices(const char *remoteAddress)
1333 {
1334     OIC_LOG(DEBUG, TAG, "IN");
1335
1336     VERIFY_NON_NULL_RET(remoteAddress, TAG,
1337                         "remote address is NULL", CA_STATUS_FAILED);
1338
1339     LEServerInfo *serverInfo = NULL;
1340     unsigned int mtu_size;
1341     oc_mutex_lock(g_LEServerListMutex);
1342     if (CA_STATUS_OK != CAGetLEServerInfo(g_LEServerList, remoteAddress, &serverInfo))
1343     {
1344         oc_mutex_unlock(g_LEServerListMutex);
1345         OIC_LOG_V(ERROR, TAG, "Could not get server info for [%s]", remoteAddress);
1346         CALEGattDisConnect(remoteAddress);
1347         return CA_STATUS_FAILED;
1348     }
1349
1350     bt_gatt_h serviceHandle = NULL;
1351     int32_t ret = bt_gatt_client_get_service(serverInfo->clientHandle, CA_GATT_SERVICE_UUID, &serviceHandle);
1352     if (BT_ERROR_NONE != ret || NULL == serviceHandle)
1353     {
1354         OIC_LOG_V(ERROR, TAG,
1355                   "bt_gatt_client_get_service Failed with ret value [%s] ", CALEGetErrorMsg(ret));
1356
1357         if(g_retrycount)
1358         {
1359             OIC_LOG(DEBUG, TAG, "Retry will be attempted to connect Gatt Server");
1360             g_retrycount--;
1361             retry_flag = 1;
1362             OIC_LOG_V(DEBUG, TAG, "Retry count left %d time(s)", g_retrycount);
1363             CAResult_t result = CALEGattConnectionRetry(remoteAddress);
1364             if(result == CA_STATUS_FAILED)
1365             {
1366                 goto error_exit;
1367             }
1368             else
1369             {
1370                 oc_mutex_unlock(g_LEServerListMutex);
1371                 OIC_LOG(ERROR, TAG, "Previous connection attempt failed, attempting to retry again");
1372                 OIC_LOG_V(DEBUG, TAG, "Retry count left %d time(s)", g_retrycount);
1373                 return CA_STATUS_FAILED;
1374             }
1375         }
1376     }
1377
1378     retry_flag = 0;
1379     // Server will read data on this characteristic.
1380     bt_gatt_h writeChrHandle = NULL;
1381     ret = bt_gatt_service_get_characteristic(serviceHandle, CA_GATT_REQUEST_CHRC_UUID,
1382             &writeChrHandle);
1383     if (BT_ERROR_NONE != ret || NULL == writeChrHandle)
1384     {
1385         OIC_LOG_V(ERROR, TAG,
1386                   "bt_gatt_service_get_characteristic Failed with ret value [%s] ",
1387                   CALEGetErrorMsg(ret));
1388         goto error_exit;
1389     }
1390
1391     // Server will notify data on this characteristic.
1392     bt_gatt_h readChrHandle = NULL;
1393     ret = bt_gatt_service_get_characteristic(serviceHandle, CA_GATT_RESPONSE_CHRC_UUID,
1394             &readChrHandle);
1395     if (BT_ERROR_NONE != ret || NULL == readChrHandle)
1396     {
1397         OIC_LOG_V(ERROR, TAG,
1398                   "bt_gatt_service_get_characteristic Failed with ret value [%s] ",
1399                   CALEGetErrorMsg(ret));
1400         goto error_exit;
1401     }
1402
1403
1404     //TODO: This data has to be freed while unsetting the callback.
1405     char *addr = OICStrdup(remoteAddress);
1406     if (NULL == addr)
1407     {
1408         OIC_LOG(ERROR, TAG, "addr is NULL");
1409         goto error_exit;
1410     }
1411
1412     ret = bt_gatt_client_set_characteristic_value_changed_cb(readChrHandle,
1413             CALEGattCharacteristicChangedCb,
1414             (void *)addr);
1415     if (BT_ERROR_NONE != ret)
1416     {
1417         OIC_LOG_V(ERROR, TAG,
1418                   "bt_gatt_client_set_characteristic_value_changed_cb Failed with ret value [%s]",
1419                   CALEGetErrorMsg(ret));
1420         goto error_exit;
1421     }
1422
1423     ret = bt_gatt_client_set_att_mtu_changed_cb(serverInfo->clientHandle,
1424             CALEGattClientMTUChangedCb,
1425             (void *)serverInfo->remoteAddress);
1426     if (BT_ERROR_NONE != ret)
1427     {
1428         OIC_LOG_V(ERROR, TAG,
1429                   "bt_gatt_client_set_att_mtu_changed_cb Failed with ret value [%s]",
1430                   CALEGetErrorMsg(ret));
1431         goto error_exit;
1432     }
1433
1434     oc_mutex_lock(g_threadMTUChangedMutex);
1435     ret = bt_gatt_client_request_att_mtu_change(serverInfo->clientHandle, CA_SUPPORTED_BLE_MTU_SIZE - CA_BLE_MTU_HEADER_SIZE);
1436     if (BT_ERROR_NONE != ret)
1437     {
1438         OIC_LOG_V(ERROR, TAG,
1439                   "bt_gatt_client_request_att_mtu_change Failed with ret value [%s]",
1440                   CALEGetErrorMsg(ret));
1441         oc_mutex_unlock(g_threadMTUChangedMutex);
1442         goto error_exit;
1443     }
1444
1445     OIC_LOG(DEBUG, TAG, "wait for callback to notify MTU Changed Callback");
1446     oc_cond_wait(g_threadMTUChangedCond, g_threadMTUChangedMutex);
1447     oc_mutex_unlock(g_threadMTUChangedMutex);
1448
1449     OIC_LOG(DEBUG, TAG, "Done MTU");
1450     ret = bt_gatt_client_get_att_mtu(serverInfo->clientHandle, &mtu_size);
1451     if (BT_ERROR_NONE != ret)
1452     {
1453         OIC_LOG_V(ERROR, TAG,
1454                   "bt_gatt_client_get_att_mtu Failed with ret value [%s]",
1455                   CALEGetErrorMsg(ret));
1456         goto error_exit;
1457     }
1458     OIC_LOG_V(DEBUG, TAG,"Negotiated MTU Size %d",mtu_size);
1459
1460     serverInfo->serviceHandle = serviceHandle;
1461     serverInfo->readChar = readChrHandle;
1462     serverInfo->writeChar = writeChrHandle;
1463     serverInfo->status = LE_STATUS_SERVICES_DISCOVERED;
1464     serverInfo->mtu_size = mtu_size;
1465
1466     while (serverInfo->pendingDataList)
1467     {
1468         LEData *leData = serverInfo->pendingDataList->data;
1469         if (CA_STATUS_OK != CAUpdateCharacteristicsToGattServerImpl(
1470                 serverInfo, leData->data, leData->dataLength))
1471         {
1472             OIC_LOG_V(ERROR, TAG, "Failed to send pending data to [%s]",
1473                       serverInfo->remoteAddress);
1474
1475             CADestroyLEDataList(&serverInfo->pendingDataList);
1476             break;
1477         }
1478         CARemoveLEDataFromList(&serverInfo->pendingDataList);
1479     }
1480     oc_mutex_unlock(g_LEServerListMutex);
1481
1482     OIC_LOG(DEBUG, TAG, "OUT");
1483     return CA_STATUS_OK;
1484
1485 error_exit:
1486     bt_gatt_client_destroy(serverInfo->clientHandle);
1487     serverInfo->clientHandle = NULL;
1488     oc_mutex_unlock(g_LEServerListMutex);
1489     CALEGattDisConnect(remoteAddress);
1490     return CA_STATUS_FAILED;
1491 }
1492
1493 CAResult_t CAUpdateCharacteristicsToGattServer(const char *remoteAddress,
1494         const uint8_t *data, const uint32_t dataLen,
1495         CALETransferType_t type, const int32_t position)
1496 {
1497     OIC_LOG(DEBUG, TAG, "IN");
1498
1499     VERIFY_NON_NULL(data, TAG, "data is NULL");
1500
1501     if (0 == dataLen)
1502     {
1503         OIC_LOG(ERROR, TAG, "dataLen is less than or equal zero. Invalid input!");
1504         return CA_STATUS_INVALID_PARAM;
1505     }
1506
1507     LEServerInfo *serverInfo = NULL;
1508     oc_mutex_lock(g_LEServerListMutex);
1509     if (LE_UNICAST == type)
1510     {
1511         if (CA_STATUS_OK != CAGetLEServerInfo(g_LEServerList, remoteAddress, &serverInfo))
1512         {
1513             OIC_LOG_V(DEBUG, TAG,
1514                       "Device with address [%s] not yet found, initiating scan",
1515                       remoteAddress);
1516
1517             char *addr = OICStrdup(remoteAddress);
1518             if (NULL == addr)
1519             {
1520                 oc_mutex_unlock(g_LEServerListMutex);
1521                 OIC_LOG(ERROR, TAG, "Device address is NULL");
1522                 return CA_STATUS_FAILED;
1523             }
1524             serverInfo = (LEServerInfo *)OICCalloc(1, sizeof(LEServerInfo));
1525             if (NULL == serverInfo)
1526             {
1527                 oc_mutex_unlock(g_LEServerListMutex);
1528                 OIC_LOG(ERROR, TAG, "Calloc failed");
1529                 OICFree(addr);
1530                 return CA_STATUS_FAILED;
1531             }
1532             serverInfo->remoteAddress = addr;
1533             serverInfo->status = LE_STATUS_UNICAST_PENDING;
1534
1535             if (CA_STATUS_OK != CAAddLEServerInfoToList(&g_LEServerList, serverInfo))
1536             {
1537                 oc_mutex_unlock(g_LEServerListMutex);
1538                 OIC_LOG_V(ERROR, TAG, "Could not add [%s] to server list", remoteAddress);
1539                 CAFreeLEServerInfo(serverInfo);
1540                 return CA_STATUS_FAILED;
1541             }
1542
1543             if (CA_STATUS_OK != CAAddLEDataToList(&serverInfo->pendingDataList, data, dataLen))
1544             {
1545                 oc_mutex_unlock(g_LEServerListMutex);
1546                 OIC_LOG(ERROR, TAG, "Could not add data to pending list");
1547                 return CA_STATUS_FAILED;
1548             }
1549         }
1550
1551         if(serverInfo->status == LE_STATUS_UNICAST_PENDING)
1552         {
1553             oc_mutex_lock(g_scanMutex);
1554             if (!g_isMulticastInProgress && !g_isUnicastScanInProgress)
1555             {
1556                 CAResult_t result = CALEGattStartDeviceScanning();
1557                 if (CA_STATUS_OK != result)
1558                 {
1559                     oc_mutex_unlock(g_scanMutex);
1560                     OIC_LOG(ERROR, TAG, "CALEGattStartDeviceScanning failed");
1561                     return CA_STATUS_FAILED;
1562                 }
1563                 g_isUnicastScanInProgress = true;
1564                 // Start Timer
1565                 oc_cond_signal(g_startTimerCond);
1566             }
1567             else
1568             {
1569                 g_isUnicastScanInProgress = true;
1570                 // Reset Timer
1571                 oc_cond_signal(g_scanningTimeCond);
1572             }
1573             oc_mutex_unlock(g_scanMutex);
1574
1575         }
1576
1577         if (serverInfo->status == LE_STATUS_DISCOVERED)
1578         {
1579             if (CA_STATUS_OK != CAAddLEDataToList(&serverInfo->pendingDataList, data, dataLen))
1580             {
1581                 oc_mutex_unlock(g_LEServerListMutex);
1582                 OIC_LOG(ERROR, TAG, "Could not add data to pending list");
1583                 return CA_STATUS_FAILED;
1584             }
1585
1586             bt_gatt_client_h clientHandle = NULL;
1587             int32_t ret = bt_gatt_client_create(serverInfo->remoteAddress, &clientHandle);
1588             if (BT_ERROR_NONE != ret || NULL == clientHandle)
1589             {
1590                 OIC_LOG_V(ERROR, TAG,
1591                           "bt_gatt_client_create Failed with ret value [%s] ", CALEGetErrorMsg(ret));
1592                 CALEGattDisConnect(serverInfo->remoteAddress);
1593                 return CA_STATUS_FAILED;
1594             }
1595             serverInfo->clientHandle = clientHandle;
1596
1597             serverInfo->status = LE_STATUS_CONNECTION_INITIATED;
1598             if (CA_STATUS_OK != CALEGattInitiateConnection(serverInfo->remoteAddress))
1599             {
1600                 OIC_LOG_V(ERROR, TAG, "Could not initiate connection to [%s]", serverInfo->remoteAddress);
1601                 serverInfo->status = LE_STATUS_DISCOVERED;
1602                 CADestroyLEDataList(&serverInfo->pendingDataList);
1603                 oc_mutex_unlock(g_LEServerListMutex);
1604                 return CA_STATUS_FAILED;
1605             }
1606         }
1607         else if (serverInfo->status < LE_STATUS_SERVICES_DISCOVERED)
1608         {
1609             if (CA_STATUS_OK != CAAddLEDataToList(&serverInfo->pendingDataList, data, dataLen))
1610             {
1611                 oc_mutex_unlock(g_LEServerListMutex);
1612                 OIC_LOG(ERROR, TAG, "Could not add data to pending list");
1613                 return CA_STATUS_FAILED;
1614             }
1615         }
1616         else
1617         {
1618             if (CA_STATUS_OK != CAUpdateCharacteristicsToGattServerImpl(serverInfo, data, dataLen))
1619             {
1620                 OIC_LOG_V(ERROR, TAG, "Could not update characteristic to gatt server [%s]",
1621                           serverInfo->remoteAddress);
1622                 oc_mutex_unlock(g_LEServerListMutex);
1623                 return CA_STATUS_FAILED;
1624             }
1625         }
1626     }
1627     else if (LE_MULTICAST == type)
1628     {
1629         OIC_LOG(ERROR, TAG, "LE_MULTICAST type Not used");
1630     }
1631     oc_mutex_unlock(g_LEServerListMutex);
1632     OIC_LOG(DEBUG, TAG, "OUT");
1633     return CA_STATUS_OK;
1634 }
1635
1636 CAResult_t CAUpdateCharacteristicsToAllGattServers(const uint8_t *data, uint32_t dataLen)
1637 {
1638     OIC_LOG(DEBUG,  TAG, "IN");
1639
1640     VERIFY_NON_NULL(data, TAG, "data is NULL");
1641
1642     if (0 == dataLen)
1643     {
1644         OIC_LOG(ERROR, TAG, "dataLen is less than or equal zero. Invalid input !");
1645         return CA_STATUS_INVALID_PARAM;
1646     }
1647
1648     oc_mutex_lock(g_LEServerListMutex);
1649     LEServerInfoList *curNode = g_LEServerList;
1650     while (curNode)
1651     {
1652         LEServerInfo *serverInfo = curNode->serverInfo;
1653         if (serverInfo->status == LE_STATUS_SERVICES_DISCOVERED)
1654         {
1655             if (CA_STATUS_OK != CAUpdateCharacteristicsToGattServerImpl(serverInfo, data, dataLen))
1656             {
1657                 OIC_LOG_V(ERROR, TAG, "Failed to update characteristics to gatt server [%s]",
1658                           serverInfo->remoteAddress);
1659             }
1660         }
1661         else if (serverInfo->status != LE_STATUS_INVALID)
1662         {
1663             if (CA_STATUS_OK != CAAddLEDataToList(&serverInfo->pendingDataList, data, dataLen))
1664             {
1665                 OIC_LOG(ERROR, TAG, "Failed to add to pending list");
1666             }
1667         }
1668         curNode = curNode->next;
1669     }
1670     oc_mutex_unlock(g_LEServerListMutex);
1671
1672     // Add the data to pending list.
1673     LEData *multicastData = (LEData *)OICCalloc(1, sizeof(LEData));
1674     if (NULL == multicastData)
1675     {
1676         OIC_LOG(ERROR, TAG, "Calloc failed");
1677         goto exit;
1678     }
1679     multicastData->data = OICCalloc(1, dataLen);
1680     if (NULL == multicastData->data)
1681     {
1682         OIC_LOG(ERROR, TAG, "Calloc failed");
1683         goto exit;
1684     }
1685     memcpy(multicastData->data, data, dataLen);
1686     multicastData->dataLength = dataLen;
1687
1688     oc_mutex_lock(g_multicastDataListMutex);
1689     if (NULL == g_multicastDataList)
1690     {
1691         g_multicastDataList = u_arraylist_create();
1692     }
1693     u_arraylist_add(g_multicastDataList, (void *)multicastData);
1694     oc_mutex_unlock(g_multicastDataListMutex);
1695
1696     // Start the scanning, if not started, else reset timer
1697     oc_mutex_lock(g_scanMutex);
1698     if (!g_isMulticastInProgress && !g_isUnicastScanInProgress)
1699     {
1700         CAResult_t result = CALEGattStartDeviceScanning();
1701         if (CA_STATUS_OK != result)
1702         {
1703             oc_mutex_unlock(g_scanMutex);
1704             OIC_LOG(ERROR, TAG, "CALEGattStartDeviceScanning Failed");
1705             goto exit;
1706         }
1707         g_isMulticastInProgress = true;
1708         // Start the timer by signalling it
1709         oc_cond_signal(g_startTimerCond);
1710     }
1711     else
1712     {
1713         g_isMulticastInProgress = true;
1714         // Reset timer
1715         oc_cond_signal(g_scanningTimeCond);
1716     }
1717     oc_mutex_unlock(g_scanMutex);
1718
1719 exit:
1720     OIC_LOG(DEBUG, TAG, "OUT ");
1721     return CA_STATUS_OK;
1722 }
1723
1724 uint16_t CALEClientGetMtuSize(const char* remote_address)
1725 {
1726     LEServerInfo *serverInfo = NULL;
1727     oc_mutex_lock(g_LEServerListMutex);
1728     if (CA_STATUS_OK == CAGetLEServerInfo(g_LEServerList, remote_address, &serverInfo))
1729     {
1730         if (serverInfo->status == LE_STATUS_SERVICES_DISCOVERED){
1731             OIC_LOG_V(DEBUG, TAG, "Mtu Size [%d]", serverInfo->mtu_size);
1732             oc_mutex_unlock(g_LEServerListMutex);
1733             OIC_LOG_V(INFO, TAG, "Returning Mtu Size [%d]", serverInfo->mtu_size - CA_BLE_MTU_HEADER_SIZE);
1734             return serverInfo->mtu_size - CA_BLE_MTU_HEADER_SIZE;
1735         }
1736     }
1737     oc_mutex_unlock(g_LEServerListMutex);
1738     return CA_DEFAULT_BLE_MTU_SIZE;
1739
1740 }
1741
1742 bool CALEClientIsConnected(const char* address)
1743 {
1744     (void)address;
1745     //@Todo
1746     return true;
1747 }
1748
1749 CAResult_t CALEClientSetMtuSize(const char* address, uint16_t mtuSize)
1750 {
1751     (void)mtuSize;
1752
1753     VERIFY_NON_NULL(address, TAG, "address is null");
1754     //@Todo
1755     //it should be implemented after update Tizen 3.0
1756     return CA_NOT_SUPPORTED;
1757 }
1758
1759 CAResult_t CALEClientSendNegotiationMessage(const char* address)
1760 {
1761     OIC_LOG_V(DEBUG, TAG, "CALEClientSendNegotiationMessage(%s)", address);
1762     //@Todo
1763     //it will be implemented when tizen public 3.0 is released.
1764     return CA_NOT_SUPPORTED;
1765 }