Disable auto connect while calling bt_gatt_connect
[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     int ret = bt_gatt_connect(remoteAddress, false);
1174
1175     if (BT_ERROR_NONE != ret)
1176     {
1177         OIC_LOG_V(ERROR, TAG, "bt_gatt_connect Failed with ret value [%s] ",
1178                   CALEGetErrorMsg(ret));
1179         oc_mutex_unlock(g_LEClientConnectMutex);
1180         return CA_STATUS_FAILED;
1181     }
1182
1183     oc_mutex_unlock(g_LEClientConnectMutex);
1184
1185     OIC_LOG(DEBUG, TAG, "OUT");
1186     return result;
1187 }
1188
1189 CAResult_t CALEGattDisConnect(const char *remoteAddress)
1190 {
1191     OIC_LOG(DEBUG, TAG, "IN");
1192
1193     VERIFY_NON_NULL_RET(remoteAddress, TAG,
1194                         "remote address is NULL", CA_STATUS_FAILED);
1195
1196     int ret = bt_gatt_disconnect(remoteAddress);
1197
1198     if (BT_ERROR_NONE != ret)
1199     {
1200         OIC_LOG_V(ERROR, TAG, "bt_gatt_disconnect Failed with ret value [%s] ",
1201                   CALEGetErrorMsg(ret));
1202         return CA_STATUS_FAILED;
1203     }
1204
1205     OIC_LOG(DEBUG, TAG, "OUT");
1206     return CA_STATUS_OK;
1207 }
1208
1209 CAResult_t CAUpdateCharacteristicsToGattServerImpl(LEServerInfo *serverInfo,
1210         const uint8_t *data, const uint32_t dataLen)
1211 {
1212     OIC_LOG(DEBUG, TAG, "IN");
1213
1214     VERIFY_NON_NULL(serverInfo, TAG, "Server Info is NULL");
1215
1216     CALEGattStopDeviceScanning();
1217
1218     OIC_LOG_V(DEBUG, TAG, "Updating the data of length [%d] to [%s] ", dataLen,
1219               serverInfo->remoteAddress);
1220
1221     int result = bt_gatt_set_value(serverInfo->writeChar, (char *)data, dataLen);
1222
1223     if (BT_ERROR_NONE != result)
1224     {
1225         OIC_LOG_V(ERROR, TAG,
1226                   "bt_gatt_set_value Failed with return val [%s]",
1227                   CALEGetErrorMsg(result));
1228         goto exit;
1229     }
1230
1231     result = bt_gatt_client_write_value(serverInfo->writeChar, CALEGattCharacteristicWriteCb,
1232                                         NULL);
1233     if (BT_ERROR_NONE != result)
1234     {
1235         OIC_LOG_V(ERROR, TAG,
1236                   "bt_gatt_client_write_value Failed with return val [%s]",
1237                   CALEGetErrorMsg(result));
1238         goto exit;
1239     }
1240
1241     // wait for callback for write Characteristic with success to sent data
1242     OIC_LOG_V(DEBUG, TAG, "callback flag is %d", g_isSignalSetFlag);
1243     oc_mutex_lock(g_threadWriteCharacteristicMutex);
1244     if (!g_isSignalSetFlag)
1245     {
1246         OIC_LOG(DEBUG, TAG, "wait for callback to notify writeCharacteristic is success");
1247         if (OC_WAIT_SUCCESS != oc_cond_wait_for(g_threadWriteCharacteristicCond,
1248                                                 g_threadWriteCharacteristicMutex,
1249                                                 WAIT_TIME_WRITE_CHARACTERISTIC))
1250         {
1251             g_isSignalSetFlag = false;
1252             oc_mutex_unlock(g_threadWriteCharacteristicMutex);
1253             OIC_LOG(ERROR, TAG, "there is no response. write has failed");
1254             goto exit;
1255         }
1256     }
1257     // reset flag set by writeCharacteristic Callback
1258     g_isSignalSetFlag = false;
1259     oc_mutex_unlock(g_threadWriteCharacteristicMutex);
1260
1261     oc_mutex_lock(g_scanMutex);
1262     if (g_isMulticastInProgress || g_isUnicastScanInProgress)
1263     {
1264         if (CA_STATUS_OK != CALEGattStartDeviceScanning())
1265         {
1266             OIC_LOG(ERROR, TAG, "Could not start device scanning");
1267         }
1268     }
1269     oc_mutex_unlock(g_scanMutex);
1270     OIC_LOG(DEBUG, TAG, "OUT");
1271     return CA_STATUS_OK;
1272
1273 exit:
1274     oc_mutex_lock(g_scanMutex);
1275     if (g_isMulticastInProgress || g_isUnicastScanInProgress)
1276     {
1277         if (CA_STATUS_OK != CALEGattStartDeviceScanning())
1278         {
1279             OIC_LOG(ERROR, TAG, "Could not start device scanning");
1280         }
1281     }
1282     oc_mutex_unlock(g_scanMutex);
1283
1284     OIC_LOG(DEBUG, TAG, "OUT");
1285     return CA_STATUS_FAILED;
1286 }
1287
1288 void CADiscoverLEServicesThread(void *remoteAddress)
1289 {
1290     OIC_LOG(DEBUG, TAG, "IN");
1291
1292     VERIFY_NON_NULL_VOID(remoteAddress, TAG, "remote address is NULL");
1293
1294     char *address  = (char *)remoteAddress;
1295
1296     CAResult_t result = CALEGattDiscoverServices(address);
1297     if (CA_STATUS_OK != result)
1298     {
1299         OIC_LOG(ERROR, TAG, "CALEGattDiscoverServices failed");
1300     }
1301
1302     OICFree(address);
1303     OIC_LOG(DEBUG, TAG, "OUT");
1304 }
1305
1306 static int CALEWaittillDisconnect(oc_mutex mutex, oc_cond cv, int wait_seconds)
1307 {
1308     OIC_LOG(DEBUG, TAG, "Waiting for server to be disconnected...");
1309     oc_mutex_lock(mutex);
1310     uint64_t wait_time = wait_seconds * MICROSECS_PER_SEC;
1311     int ret = oc_cond_wait_for(cv, mutex, wait_time);
1312     oc_mutex_unlock(mutex);
1313     return ret;
1314 }
1315
1316 static CAResult_t CALEGattConnectionRetry(const char *remoteAddress)
1317 {
1318     OIC_LOG(DEBUG, TAG, "IN");
1319
1320     VERIFY_NON_NULL_RET(remoteAddress, TAG,
1321                         "remote address is NULL", CA_STATUS_FAILED);
1322
1323     CALEGattDisConnect(remoteAddress);
1324     CALEWaittillDisconnect(g_isDisconnectedMutex, g_LEDisconnectedCond, 10);
1325     CAResult_t result = CALEGattConnect(remoteAddress);
1326     OIC_LOG(DEBUG, TAG, "OUT");
1327     return result;
1328 }
1329
1330 CAResult_t CALEGattDiscoverServices(const char *remoteAddress)
1331 {
1332     OIC_LOG(DEBUG, TAG, "IN");
1333
1334     VERIFY_NON_NULL_RET(remoteAddress, TAG,
1335                         "remote address is NULL", CA_STATUS_FAILED);
1336
1337     LEServerInfo *serverInfo = NULL;
1338     unsigned int mtu_size;
1339     oc_mutex_lock(g_LEServerListMutex);
1340     if (CA_STATUS_OK != CAGetLEServerInfo(g_LEServerList, remoteAddress, &serverInfo))
1341     {
1342         oc_mutex_unlock(g_LEServerListMutex);
1343         OIC_LOG_V(ERROR, TAG, "Could not get server info for [%s]", remoteAddress);
1344         CALEGattDisConnect(remoteAddress);
1345         return CA_STATUS_FAILED;
1346     }
1347
1348     bt_gatt_h serviceHandle = NULL;
1349     int32_t ret = bt_gatt_client_get_service(serverInfo->clientHandle, CA_GATT_SERVICE_UUID, &serviceHandle);
1350     if (BT_ERROR_NONE != ret || NULL == serviceHandle)
1351     {
1352         OIC_LOG_V(ERROR, TAG,
1353                   "bt_gatt_client_get_service Failed with ret value [%s] ", CALEGetErrorMsg(ret));
1354
1355         if(g_retrycount)
1356         {
1357             OIC_LOG(DEBUG, TAG, "Retry will be attempted to connect Gatt Server");
1358             g_retrycount--;
1359             retry_flag = 1;
1360             OIC_LOG_V(DEBUG, TAG, "Retry count left %d time(s)", g_retrycount);
1361             CAResult_t result = CALEGattConnectionRetry(remoteAddress);
1362             if(result == CA_STATUS_FAILED)
1363             {
1364                 goto error_exit;
1365             }
1366             else
1367             {
1368                 oc_mutex_unlock(g_LEServerListMutex);
1369                 OIC_LOG(ERROR, TAG, "Previous connection attempt failed, attempting to retry again");
1370                 OIC_LOG_V(DEBUG, TAG, "Retry count left %d time(s)", g_retrycount);
1371                 return CA_STATUS_FAILED;
1372             }
1373         }
1374     }
1375
1376     retry_flag = 0;
1377     // Server will read data on this characteristic.
1378     bt_gatt_h writeChrHandle = NULL;
1379     ret = bt_gatt_service_get_characteristic(serviceHandle, CA_GATT_REQUEST_CHRC_UUID,
1380             &writeChrHandle);
1381     if (BT_ERROR_NONE != ret || NULL == writeChrHandle)
1382     {
1383         OIC_LOG_V(ERROR, TAG,
1384                   "bt_gatt_service_get_characteristic Failed with ret value [%s] ",
1385                   CALEGetErrorMsg(ret));
1386         goto error_exit;
1387     }
1388
1389     // Server will notify data on this characteristic.
1390     bt_gatt_h readChrHandle = NULL;
1391     ret = bt_gatt_service_get_characteristic(serviceHandle, CA_GATT_RESPONSE_CHRC_UUID,
1392             &readChrHandle);
1393     if (BT_ERROR_NONE != ret || NULL == readChrHandle)
1394     {
1395         OIC_LOG_V(ERROR, TAG,
1396                   "bt_gatt_service_get_characteristic Failed with ret value [%s] ",
1397                   CALEGetErrorMsg(ret));
1398         goto error_exit;
1399     }
1400
1401
1402     //TODO: This data has to be freed while unsetting the callback.
1403     char *addr = OICStrdup(remoteAddress);
1404     if (NULL == addr)
1405     {
1406         OIC_LOG(ERROR, TAG, "addr is NULL");
1407         goto error_exit;
1408     }
1409
1410     ret = bt_gatt_client_set_characteristic_value_changed_cb(readChrHandle,
1411             CALEGattCharacteristicChangedCb,
1412             (void *)addr);
1413     if (BT_ERROR_NONE != ret)
1414     {
1415         OIC_LOG_V(ERROR, TAG,
1416                   "bt_gatt_client_set_characteristic_value_changed_cb Failed with ret value [%s]",
1417                   CALEGetErrorMsg(ret));
1418         goto error_exit;
1419     }
1420
1421     ret = bt_gatt_client_set_att_mtu_changed_cb(serverInfo->clientHandle,
1422             CALEGattClientMTUChangedCb,
1423             (void *)serverInfo->remoteAddress);
1424     if (BT_ERROR_NONE != ret)
1425     {
1426         OIC_LOG_V(ERROR, TAG,
1427                   "bt_gatt_client_set_att_mtu_changed_cb Failed with ret value [%s]",
1428                   CALEGetErrorMsg(ret));
1429         goto error_exit;
1430     }
1431
1432     oc_mutex_lock(g_threadMTUChangedMutex);
1433     ret = bt_gatt_client_request_att_mtu_change(serverInfo->clientHandle, CA_SUPPORTED_BLE_MTU_SIZE - CA_BLE_MTU_HEADER_SIZE);
1434     if (BT_ERROR_NONE != ret)
1435     {
1436         OIC_LOG_V(ERROR, TAG,
1437                   "bt_gatt_client_request_att_mtu_change Failed with ret value [%s]",
1438                   CALEGetErrorMsg(ret));
1439         oc_mutex_unlock(g_threadMTUChangedMutex);
1440         goto error_exit;
1441     }
1442
1443     OIC_LOG(DEBUG, TAG, "wait for callback to notify MTU Changed Callback");
1444     oc_cond_wait(g_threadMTUChangedCond, g_threadMTUChangedMutex);
1445     oc_mutex_unlock(g_threadMTUChangedMutex);
1446
1447     OIC_LOG(DEBUG, TAG, "Done MTU");
1448     ret = bt_gatt_client_get_att_mtu(serverInfo->clientHandle, &mtu_size);
1449     if (BT_ERROR_NONE != ret)
1450     {
1451         OIC_LOG_V(ERROR, TAG,
1452                   "bt_gatt_client_get_att_mtu Failed with ret value [%s]",
1453                   CALEGetErrorMsg(ret));
1454         goto error_exit;
1455     }
1456     OIC_LOG_V(DEBUG, TAG,"Negotiated MTU Size %d",mtu_size);
1457
1458     serverInfo->serviceHandle = serviceHandle;
1459     serverInfo->readChar = readChrHandle;
1460     serverInfo->writeChar = writeChrHandle;
1461     serverInfo->status = LE_STATUS_SERVICES_DISCOVERED;
1462     serverInfo->mtu_size = mtu_size;
1463
1464     while (serverInfo->pendingDataList)
1465     {
1466         LEData *leData = serverInfo->pendingDataList->data;
1467         if (CA_STATUS_OK != CAUpdateCharacteristicsToGattServerImpl(
1468                 serverInfo, leData->data, leData->dataLength))
1469         {
1470             OIC_LOG_V(ERROR, TAG, "Failed to send pending data to [%s]",
1471                       serverInfo->remoteAddress);
1472
1473             CADestroyLEDataList(&serverInfo->pendingDataList);
1474             break;
1475         }
1476         CARemoveLEDataFromList(&serverInfo->pendingDataList);
1477     }
1478     oc_mutex_unlock(g_LEServerListMutex);
1479
1480     OIC_LOG(DEBUG, TAG, "OUT");
1481     return CA_STATUS_OK;
1482
1483 error_exit:
1484     bt_gatt_client_destroy(serverInfo->clientHandle);
1485     serverInfo->clientHandle = NULL;
1486     oc_mutex_unlock(g_LEServerListMutex);
1487     CALEGattDisConnect(remoteAddress);
1488     return CA_STATUS_FAILED;
1489 }
1490
1491 CAResult_t CAUpdateCharacteristicsToGattServer(const char *remoteAddress,
1492         const uint8_t *data, const uint32_t dataLen,
1493         CALETransferType_t type, const int32_t position)
1494 {
1495     OIC_LOG(DEBUG, TAG, "IN");
1496
1497     VERIFY_NON_NULL(data, TAG, "data is NULL");
1498
1499     if (0 == dataLen)
1500     {
1501         OIC_LOG(ERROR, TAG, "dataLen is less than or equal zero. Invalid input!");
1502         return CA_STATUS_INVALID_PARAM;
1503     }
1504
1505     LEServerInfo *serverInfo = NULL;
1506     bool isConnected = false;
1507     oc_mutex_lock(g_LEServerListMutex);
1508     if (LE_UNICAST == type)
1509     {
1510         if (CA_STATUS_OK != CAGetLEServerInfo(g_LEServerList, remoteAddress, &serverInfo))
1511         {
1512             OIC_LOG_V(DEBUG, TAG,
1513                       "Device with address [%s] not yet found, initiating scan",
1514                       remoteAddress);
1515
1516             char *addr = OICStrdup(remoteAddress);
1517             if (NULL == addr)
1518             {
1519                 oc_mutex_unlock(g_LEServerListMutex);
1520                 OIC_LOG(ERROR, TAG, "Device address is NULL");
1521                 return CA_STATUS_FAILED;
1522             }
1523             serverInfo = (LEServerInfo *)OICCalloc(1, sizeof(LEServerInfo));
1524             if (NULL == serverInfo)
1525             {
1526                 oc_mutex_unlock(g_LEServerListMutex);
1527                 OIC_LOG(ERROR, TAG, "Calloc failed");
1528                 OICFree(addr);
1529                 return CA_STATUS_FAILED;
1530             }
1531             serverInfo->remoteAddress = addr;
1532             serverInfo->status = LE_STATUS_UNICAST_PENDING;
1533
1534             if (CA_STATUS_OK != CAAddLEServerInfoToList(&g_LEServerList, serverInfo))
1535             {
1536                 oc_mutex_unlock(g_LEServerListMutex);
1537                 OIC_LOG_V(ERROR, TAG, "Could not add [%s] to server list", remoteAddress);
1538                 CAFreeLEServerInfo(serverInfo);
1539                 return CA_STATUS_FAILED;
1540             }
1541
1542             if (CA_STATUS_OK != CAAddLEDataToList(&serverInfo->pendingDataList, data, dataLen))
1543             {
1544                 oc_mutex_unlock(g_LEServerListMutex);
1545                 OIC_LOG(ERROR, TAG, "Could not add data to pending list");
1546                 return CA_STATUS_FAILED;
1547             }
1548         }
1549
1550         if(serverInfo->status == LE_STATUS_UNICAST_PENDING)
1551         {
1552
1553             int ret = bt_device_is_profile_connected(remoteAddress, BT_PROFILE_GATT, &isConnected);
1554             if (BT_ERROR_NONE != ret)
1555             {
1556                 OIC_LOG_V(ERROR, TAG, "bt_device_is_profile_connected Failed with ret value [%s] ",
1557                           CALEGetErrorMsg(ret));
1558                 oc_mutex_unlock(g_LEServerListMutex);
1559                 return CA_STATUS_FAILED;
1560             }
1561
1562             if (isConnected){
1563                 OIC_LOG_V(DEBUG, TAG, "Already connected to address [%s]", remoteAddress);
1564                 serverInfo->status = LE_STATUS_CONNECTED;
1565             } else {
1566                 oc_mutex_lock(g_scanMutex);
1567                 if (!g_isMulticastInProgress && !g_isUnicastScanInProgress)
1568                 {
1569                     CAResult_t result = CALEGattStartDeviceScanning();
1570                     if (CA_STATUS_OK != result)
1571                     {
1572                         oc_mutex_unlock(g_scanMutex);
1573                         OIC_LOG(ERROR, TAG, "CALEGattStartDeviceScanning failed");
1574                         oc_mutex_unlock(g_LEServerListMutex);
1575                         return CA_STATUS_FAILED;
1576                     }
1577                     g_isUnicastScanInProgress = true;
1578                     // Start Timer
1579                     oc_cond_signal(g_startTimerCond);
1580                 }
1581                 else
1582                 {
1583                     g_isUnicastScanInProgress = true;
1584                     // Reset Timer
1585                     oc_cond_signal(g_scanningTimeCond);
1586                 }
1587                 oc_mutex_unlock(g_scanMutex);
1588               }
1589
1590         }
1591
1592         if (serverInfo->status == LE_STATUS_CONNECTED)
1593         {
1594             oc_mutex_lock(g_LEClientThreadPoolMutex);
1595             if (NULL == g_LEClientThreadPool)
1596             {
1597                 oc_mutex_unlock(g_LEClientThreadPoolMutex);
1598                 OIC_LOG(ERROR, TAG, "g_LEClientThreadPool is NULL");
1599                 oc_mutex_unlock(g_LEServerListMutex);
1600                 return CA_STATUS_FAILED;
1601             }
1602             char *addr = OICStrdup(remoteAddress);
1603             if (NULL == addr)
1604             {
1605                 oc_mutex_unlock(g_LEClientThreadPoolMutex);
1606                 OIC_LOG(ERROR, TAG, "addr is NULL");
1607                 oc_mutex_unlock(g_LEServerListMutex);
1608                 return CA_STATUS_FAILED;
1609             }
1610             CAResult_t ret = ca_thread_pool_add_task(g_LEClientThreadPool, CADiscoverLEServicesThread,
1611                                                      addr, NULL);
1612             oc_mutex_unlock(g_LEClientThreadPoolMutex);
1613             if (CA_STATUS_OK != ret)
1614             {
1615                 OIC_LOG_V(ERROR, TAG, "ca_thread_pool_add_task failed with ret [%d]", ret);
1616                 OICFree(addr);
1617             }
1618         }
1619
1620         if (serverInfo->status == LE_STATUS_DISCOVERED)
1621         {
1622             if (CA_STATUS_OK != CAAddLEDataToList(&serverInfo->pendingDataList, data, dataLen))
1623             {
1624                 oc_mutex_unlock(g_LEServerListMutex);
1625                 OIC_LOG(ERROR, TAG, "Could not add data to pending list");
1626                 return CA_STATUS_FAILED;
1627             }
1628
1629             bt_gatt_client_h clientHandle = NULL;
1630             int32_t ret = bt_gatt_client_create(serverInfo->remoteAddress, &clientHandle);
1631             if (BT_ERROR_NONE != ret || NULL == clientHandle)
1632             {
1633                 OIC_LOG_V(ERROR, TAG,
1634                           "bt_gatt_client_create Failed with ret value [%s] ", CALEGetErrorMsg(ret));
1635                 CALEGattDisConnect(serverInfo->remoteAddress);
1636                 oc_mutex_unlock(g_LEServerListMutex);
1637                 return CA_STATUS_FAILED;
1638             }
1639             serverInfo->clientHandle = clientHandle;
1640
1641             serverInfo->status = LE_STATUS_CONNECTION_INITIATED;
1642             if (CA_STATUS_OK != CALEGattInitiateConnection(serverInfo->remoteAddress))
1643             {
1644                 OIC_LOG_V(ERROR, TAG, "Could not initiate connection to [%s]", serverInfo->remoteAddress);
1645                 serverInfo->status = LE_STATUS_DISCOVERED;
1646                 CADestroyLEDataList(&serverInfo->pendingDataList);
1647                 oc_mutex_unlock(g_LEServerListMutex);
1648                 return CA_STATUS_FAILED;
1649             }
1650         }
1651         else if (serverInfo->status < LE_STATUS_SERVICES_DISCOVERED)
1652         {
1653             if (CA_STATUS_OK != CAAddLEDataToList(&serverInfo->pendingDataList, data, dataLen))
1654             {
1655                 oc_mutex_unlock(g_LEServerListMutex);
1656                 OIC_LOG(ERROR, TAG, "Could not add data to pending list");
1657                 return CA_STATUS_FAILED;
1658             }
1659         }
1660         else
1661         {
1662             if (CA_STATUS_OK != CAUpdateCharacteristicsToGattServerImpl(serverInfo, data, dataLen))
1663             {
1664                 OIC_LOG_V(ERROR, TAG, "Could not update characteristic to gatt server [%s]",
1665                           serverInfo->remoteAddress);
1666                 oc_mutex_unlock(g_LEServerListMutex);
1667                 return CA_STATUS_FAILED;
1668             }
1669         }
1670     }
1671     else if (LE_MULTICAST == type)
1672     {
1673         OIC_LOG(ERROR, TAG, "LE_MULTICAST type Not used");
1674     }
1675     oc_mutex_unlock(g_LEServerListMutex);
1676     OIC_LOG(DEBUG, TAG, "OUT");
1677     return CA_STATUS_OK;
1678 }
1679
1680 CAResult_t CAUpdateCharacteristicsToAllGattServers(const uint8_t *data, uint32_t dataLen)
1681 {
1682     OIC_LOG(DEBUG,  TAG, "IN");
1683
1684     VERIFY_NON_NULL(data, TAG, "data is NULL");
1685
1686     if (0 == dataLen)
1687     {
1688         OIC_LOG(ERROR, TAG, "dataLen is less than or equal zero. Invalid input !");
1689         return CA_STATUS_INVALID_PARAM;
1690     }
1691
1692     oc_mutex_lock(g_LEServerListMutex);
1693     LEServerInfoList *curNode = g_LEServerList;
1694     while (curNode)
1695     {
1696         LEServerInfo *serverInfo = curNode->serverInfo;
1697         if (serverInfo->status == LE_STATUS_SERVICES_DISCOVERED)
1698         {
1699             if (CA_STATUS_OK != CAUpdateCharacteristicsToGattServerImpl(serverInfo, data, dataLen))
1700             {
1701                 OIC_LOG_V(ERROR, TAG, "Failed to update characteristics to gatt server [%s]",
1702                           serverInfo->remoteAddress);
1703             }
1704         }
1705         else if (serverInfo->status != LE_STATUS_INVALID)
1706         {
1707             if (CA_STATUS_OK != CAAddLEDataToList(&serverInfo->pendingDataList, data, dataLen))
1708             {
1709                 OIC_LOG(ERROR, TAG, "Failed to add to pending list");
1710             }
1711         }
1712         curNode = curNode->next;
1713     }
1714     oc_mutex_unlock(g_LEServerListMutex);
1715
1716     // Add the data to pending list.
1717     LEData *multicastData = (LEData *)OICCalloc(1, sizeof(LEData));
1718     if (NULL == multicastData)
1719     {
1720         OIC_LOG(ERROR, TAG, "Calloc failed");
1721         goto exit;
1722     }
1723     multicastData->data = OICCalloc(1, dataLen);
1724     if (NULL == multicastData->data)
1725     {
1726         OIC_LOG(ERROR, TAG, "Calloc failed");
1727         goto exit;
1728     }
1729     memcpy(multicastData->data, data, dataLen);
1730     multicastData->dataLength = dataLen;
1731
1732     oc_mutex_lock(g_multicastDataListMutex);
1733     if (NULL == g_multicastDataList)
1734     {
1735         g_multicastDataList = u_arraylist_create();
1736     }
1737     u_arraylist_add(g_multicastDataList, (void *)multicastData);
1738     oc_mutex_unlock(g_multicastDataListMutex);
1739
1740     // Start the scanning, if not started, else reset timer
1741     oc_mutex_lock(g_scanMutex);
1742     if (!g_isMulticastInProgress && !g_isUnicastScanInProgress)
1743     {
1744         CAResult_t result = CALEGattStartDeviceScanning();
1745         if (CA_STATUS_OK != result)
1746         {
1747             oc_mutex_unlock(g_scanMutex);
1748             OIC_LOG(ERROR, TAG, "CALEGattStartDeviceScanning Failed");
1749             goto exit;
1750         }
1751         g_isMulticastInProgress = true;
1752         // Start the timer by signalling it
1753         oc_cond_signal(g_startTimerCond);
1754     }
1755     else
1756     {
1757         g_isMulticastInProgress = true;
1758         // Reset timer
1759         oc_cond_signal(g_scanningTimeCond);
1760     }
1761     oc_mutex_unlock(g_scanMutex);
1762
1763 exit:
1764     OIC_LOG(DEBUG, TAG, "OUT ");
1765     return CA_STATUS_OK;
1766 }
1767
1768 uint16_t CALEClientGetMtuSize(const char* remote_address)
1769 {
1770     LEServerInfo *serverInfo = NULL;
1771     oc_mutex_lock(g_LEServerListMutex);
1772     if (CA_STATUS_OK == CAGetLEServerInfo(g_LEServerList, remote_address, &serverInfo))
1773     {
1774         if (serverInfo->status == LE_STATUS_SERVICES_DISCOVERED){
1775             OIC_LOG_V(DEBUG, TAG, "Mtu Size [%d]", serverInfo->mtu_size);
1776             oc_mutex_unlock(g_LEServerListMutex);
1777             OIC_LOG_V(INFO, TAG, "Returning Mtu Size [%d]", serverInfo->mtu_size - CA_BLE_MTU_HEADER_SIZE);
1778             return serverInfo->mtu_size - CA_BLE_MTU_HEADER_SIZE;
1779         }
1780     }
1781     oc_mutex_unlock(g_LEServerListMutex);
1782     return CA_DEFAULT_BLE_MTU_SIZE;
1783
1784 }
1785
1786 bool CALEClientIsConnected(const char* address)
1787 {
1788     (void)address;
1789     //@Todo
1790     return true;
1791 }
1792
1793 CAResult_t CALEClientSetMtuSize(const char* address, uint16_t mtuSize)
1794 {
1795     (void)mtuSize;
1796
1797     VERIFY_NON_NULL(address, TAG, "address is null");
1798     //@Todo
1799     //it should be implemented after update Tizen 3.0
1800     return CA_NOT_SUPPORTED;
1801 }
1802
1803 CAResult_t CALEClientSendNegotiationMessage(const char* address)
1804 {
1805     OIC_LOG_V(DEBUG, TAG, "CALEClientSendNegotiationMessage(%s)", address);
1806     //@Todo
1807     //it will be implemented when tizen public 3.0 is released.
1808     return CA_NOT_SUPPORTED;
1809 }