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