CONPRO-1551 Adding support for LE bi directional request.
[platform/upstream/iotivity.git] / resource / csdk / connectivity / src / bt_le_adapter / tizen / caleclient_vd.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
337         // TODO:Disabling scanning for now.Need to check.
338         /*oc_mutex_lock(g_scanMutex);
339         if (g_isMulticastInProgress || g_isUnicastScanInProgress)
340         {
341             CAResult_t ret = CALEGattStartDeviceScanning();
342             if (CA_STATUS_OK != ret)
343             {
344                 OIC_LOG(ERROR, TAG, "CALEGattStartDeviceScanning Failed");
345             }
346         }
347         oc_mutex_unlock(g_scanMutex);
348 */
349         LEServerInfo *serverInfo = NULL;
350         oc_mutex_lock(g_LEServerListMutex);
351         if (CA_STATUS_OK != CAGetLEServerInfo(g_LEServerList, remoteAddress, &serverInfo))
352         {
353             oc_mutex_unlock(g_LEServerListMutex);
354             OIC_LOG_V(ERROR, TAG, "Could not get server info for [%s]", remoteAddress);
355             return;
356         }
357
358         serverInfo->status = LE_STATUS_CONNECTED;
359         oc_mutex_unlock(g_LEServerListMutex);
360
361         oc_mutex_lock(g_LEClientThreadPoolMutex);
362         if (NULL == g_LEClientThreadPool)
363         {
364             oc_mutex_unlock(g_LEClientThreadPoolMutex);
365             OIC_LOG(ERROR, TAG, "g_LEClientThreadPool is NULL");
366             return;
367         }
368
369         char *addr = OICStrdup(remoteAddress);
370         if (NULL == addr)
371         {
372             oc_mutex_unlock(g_LEClientThreadPoolMutex);
373             OIC_LOG(ERROR, TAG, "addr is NULL");
374             return;
375         }
376
377         CAResult_t ret = ca_thread_pool_add_task(g_LEClientThreadPool, CADiscoverLEServicesThread,
378                                                  addr, NULL);
379         oc_mutex_unlock(g_LEClientThreadPoolMutex);
380         if (CA_STATUS_OK != ret)
381         {
382             OIC_LOG_V(ERROR, TAG, "ca_thread_pool_add_task failed with ret [%d]", ret);
383             OICFree(addr);
384         }
385     }
386     OIC_LOG(DEBUG, TAG, "OUT");
387 }
388
389 static bool CALEIsHaveServiceImpl(bt_adapter_le_device_scan_result_info_s *scanInfo,
390                                   const char *service_uuid,
391                                   bt_adapter_le_packet_type_e pkt_type)
392 {
393     bool ret = false;
394     char **uuids = NULL;
395     int count = 0;
396     int result = 0;
397
398     result = bt_adapter_le_get_scan_result_service_uuids(scanInfo,
399              pkt_type, &uuids, &count);
400     if (result == BT_ERROR_NONE && NULL != uuids)
401     {
402         for (int i = 0; i < count; i++)
403         {
404             if (0 == strcasecmp(uuids[i], service_uuid))
405             {
406                 OIC_LOG_V(DEBUG, TAG, "Service[%s] Found in %s",
407                           uuids[i], scanInfo->remote_address);
408                 ret = true;
409             }
410             OICFree(uuids[i]);
411         }
412         OICFree(uuids);
413     }
414
415     if(ret == false){
416         char *man_data = NULL;
417         int man_data_len;
418         int man_id;
419         result = bt_adapter_le_get_scan_result_manufacturer_data(scanInfo,
420         pkt_type, &man_id, &man_data, &man_data_len);
421
422         if (result == BT_ERROR_NONE && NULL != man_data)
423         {
424             int pos =0;
425             char *compare_man_data = OICCalloc(1, (man_data_len*2)+1);
426             if (!compare_man_data)
427             {
428                 OIC_LOG(ERROR, TAG, "Memory allocation failed for compare_man_data");
429                 OICFree(man_data);
430                 return false;
431             }
432
433             for(int i=0;i<man_data_len;i++){
434                 pos += snprintf(compare_man_data+pos, 2, "%.2x", man_data[i]);
435             }
436
437             if (man_id == samsung_code && 0 == strncasecmp(compare_man_data, service_uuid, CUSTOM_UUID_LEN))
438             {
439                 OIC_LOG_V(DEBUG, TAG, "Manufacture Data[%s] Found in %s",
440                                        compare_man_data, scanInfo->remote_address);
441                 ret = true;
442             }
443             OICFree(compare_man_data);
444             OICFree(man_data);
445         }
446     }
447     return ret;
448 }
449
450 static bool CALEIsHaveService(bt_adapter_le_device_scan_result_info_s *scanInfo,
451                               const char *service_uuid)
452 {
453     return
454         // For arduino servers, scan response will give the UUIDs advertised.
455         CALEIsHaveServiceImpl(scanInfo, service_uuid,
456                               BT_ADAPTER_LE_PACKET_SCAN_RESPONSE) ||
457         // For android/tizen servers, advertising packet will give the UUIDs.
458         CALEIsHaveServiceImpl(scanInfo, service_uuid,
459                               BT_ADAPTER_LE_PACKET_ADVERTISING);
460 }
461
462 void CALEAdapterScanResultCb(int result, bt_adapter_le_device_scan_result_info_s *scanInfo,
463                              void *userData)
464 {
465     (void)userData;
466     OIC_LOG(DEBUG, TAG, "IN");
467
468     VERIFY_NON_NULL_VOID(scanInfo, TAG, "scanInfo");
469     VERIFY_NON_NULL_VOID(scanInfo->remote_address, TAG, "scanInfo->remote_address");
470
471     OIC_LOG_V(DEBUG, TAG, "Remote Address [%s]", scanInfo->remote_address);
472     OIC_LOG_V(DEBUG, TAG, "Scan Result [%d]", result);
473     OIC_LOG_V(DEBUG, TAG,
474               " Adv data len [%d] Scan data len[%d]RSSI [%d] Addr_type [%d] ",
475               scanInfo->adv_data_len, scanInfo->scan_data_len, scanInfo->rssi,
476               scanInfo->address_type);
477
478     // Check if scanning was stopped (since this callback is
479     // being triggered even after stopping the scan)
480     oc_mutex_lock(g_isScanningInProgressMutex);
481     if (!g_isScanningInProgress)
482     {
483         oc_mutex_unlock(g_isScanningInProgressMutex);
484         OIC_LOG(DEBUG, TAG, "Scanning not in progress, so ignoring callback");
485         return;
486     }
487     oc_mutex_unlock(g_isScanningInProgressMutex);
488
489     if (CALEIsHaveService(scanInfo, CA_GATT_SERVICE_UUID) ||
490         CALEIsHaveService(scanInfo, CA_GATT_CUSTOM_UUID)||
491         CALEIsHaveService(scanInfo, CA_GATT_CUSTOM_UUID2))
492     {
493         OIC_LOG_V(DEBUG, TAG, "Device [%s] supports OIC or custom service", scanInfo->remote_address);
494
495         LEServerInfo *serverInfo = NULL;
496         oc_mutex_lock(g_LEServerListMutex);
497         CAResult_t ret = CAGetLEServerInfo(g_LEServerList, scanInfo->remote_address, &serverInfo);
498         if (CA_STATUS_OK != ret)
499         {
500             OIC_LOG_V(DEBUG, TAG,
501                       "Newly discovered device with address [%s] ", scanInfo->remote_address);
502
503             char *addr = OICStrdup(scanInfo->remote_address);
504             if (NULL == addr)
505             {
506                 oc_mutex_unlock(g_LEServerListMutex);
507                 OIC_LOG(ERROR, TAG, "Device address is NULL");
508                 return;
509             }
510             serverInfo = (LEServerInfo *)OICCalloc(1, sizeof(LEServerInfo));
511             if (NULL == serverInfo)
512             {
513                 oc_mutex_unlock(g_LEServerListMutex);
514                 OIC_LOG(ERROR, TAG, "Calloc failed");
515                 OICFree(addr);
516                 return;
517             }
518             serverInfo->remoteAddress = addr;
519             serverInfo->status = LE_STATUS_DISCOVERED;
520
521             if (CA_STATUS_OK != CAAddLEServerInfoToList(&g_LEServerList, serverInfo))
522             {
523                 oc_mutex_unlock(g_LEServerListMutex);
524                 OIC_LOG_V(ERROR, TAG, "Could not add [%s] to server list", scanInfo->remote_address);
525                 CAFreeLEServerInfo(serverInfo);
526                 return;
527             }
528         }else {
529             OIC_LOG_V(DEBUG, TAG,
530                       "Device Present with address [%s] ", scanInfo->remote_address);
531
532             if(serverInfo->status == LE_STATUS_UNICAST_PENDING){
533                 bt_gatt_client_h clientHandle = NULL;
534                 int32_t ret = bt_gatt_client_create(serverInfo->remoteAddress, &clientHandle);
535                 if (BT_ERROR_NONE != ret || NULL == clientHandle)
536                 {
537                     OIC_LOG_V(ERROR, TAG,
538                               "bt_gatt_client_create Failed with ret value [%s] ", CALEGetErrorMsg(ret));
539                     CALEGattDisConnect(serverInfo->remoteAddress);
540                     oc_mutex_unlock(g_LEServerListMutex);
541                     return ;
542                 }
543                 serverInfo->clientHandle = clientHandle;
544
545                 serverInfo->status = LE_STATUS_CONNECTION_INITIATED;
546                 if (CA_STATUS_OK != CALEGattInitiateConnection(serverInfo->remoteAddress))
547                 {
548                     OIC_LOG_V(ERROR, TAG, "Could not initiate connection to [%s]", serverInfo->remoteAddress);
549                     serverInfo->status = LE_STATUS_DISCOVERED;
550                     CADestroyLEDataList(&serverInfo->pendingDataList);
551                     oc_mutex_unlock(g_LEServerListMutex);
552                     return ;
553                  }
554              }
555          }
556     }
557     oc_mutex_unlock(g_LEServerListMutex);
558     OIC_LOG(DEBUG, TAG, "OUT");
559 }
560
561 void CASetLEClientThreadPoolHandle(ca_thread_pool_t handle)
562 {
563     OIC_LOG(DEBUG, TAG, "IN");
564
565     oc_mutex_lock(g_LEClientThreadPoolMutex);
566     g_LEClientThreadPool = handle;
567     oc_mutex_unlock(g_LEClientThreadPoolMutex);
568
569     OIC_LOG(DEBUG, TAG, "OUT");
570 }
571
572 void CASetLEReqRespClientCallback(CABLEDataReceivedCallback callback)
573 {
574     OIC_LOG(DEBUG, TAG, "IN");
575
576     oc_mutex_lock(g_LEReqRespClientCbMutex);
577
578     g_LEClientDataReceivedCallback = callback;
579
580     oc_mutex_unlock(g_LEReqRespClientCbMutex);
581
582     OIC_LOG(DEBUG, TAG, "OUT");
583 }
584
585 void CASetBLEClientErrorHandleCallback(CABLEErrorHandleCallback callback)
586 {
587     g_clientErrorCallback = callback;
588 }
589
590 CAResult_t CAStartLEGattClient()
591 {
592     OIC_LOG(DEBUG, TAG, "IN");
593
594     oc_mutex_lock(g_LEClientStateMutex);
595     if (true  == g_isLEGattClientStarted)
596     {
597         OIC_LOG(ERROR, TAG, "Gatt Client is already running!!");
598         oc_mutex_unlock(g_LEClientStateMutex);
599         return CA_STATUS_FAILED;
600     }
601
602     CAResult_t  result = CALEGattSetCallbacks();
603     if (CA_STATUS_OK != result)
604     {
605         OIC_LOG(ERROR, TAG, "CABleGattSetCallbacks Failed");
606         oc_mutex_unlock(g_LEClientStateMutex);
607         CATerminateLEGattClient();
608         return CA_STATUS_FAILED;
609     }
610
611     g_isLEGattClientStarted = true;
612     oc_mutex_unlock(g_LEClientStateMutex);
613
614     oc_mutex_lock(g_LEClientThreadPoolMutex);
615     if (NULL == g_LEClientThreadPool)
616     {
617         OIC_LOG(ERROR, TAG, "gBleServerThreadPool is NULL");
618         CATerminateGattClientMutexVariables();
619         oc_mutex_unlock(g_LEClientThreadPoolMutex);
620         return CA_STATUS_FAILED;
621     }
622
623     result = ca_thread_pool_add_task(g_LEClientThreadPool, CAStartTimerThread,
624                                      NULL, NULL);
625     if (CA_STATUS_OK != result)
626     {
627         OIC_LOG(ERROR, TAG, "ca_thread_pool_add_task failed");
628         CATerminateGattClientMutexVariables();
629         oc_mutex_unlock(g_LEClientThreadPoolMutex);
630         return CA_STATUS_FAILED;
631     }
632
633     result= ca_thread_pool_add_task(g_LEClientThreadPool, CALEClientScanThread,
634                                     NULL, NULL);
635     if (CA_STATUS_OK != result)
636     {
637         OIC_LOG(ERROR, TAG, "ca_thread_pool_add_task failed");
638         CATerminateGattClientMutexVariables();
639         oc_mutex_unlock(g_LEClientThreadPoolMutex);
640         return CA_STATUS_FAILED;
641     }
642     oc_mutex_unlock(g_LEClientThreadPoolMutex);
643
644     OIC_LOG(DEBUG, TAG, "OUT");
645     return CA_STATUS_OK;
646 }
647
648 void CALEClientScanThread()
649 {
650     oc_mutex_lock(g_scanMutex);
651     if (!g_isMulticastInProgress && !g_isUnicastScanInProgress)
652     {
653         CAResult_t result = CALEGattStartDeviceScanning();
654         if (CA_STATUS_OK != result)
655         {
656             oc_mutex_unlock(g_scanMutex);
657             OIC_LOG(ERROR, TAG, "CALEGattStartDeviceScanning failed");
658             return ;
659         }
660         g_isUnicastScanInProgress = true;
661         // Start Timer
662         oc_cond_signal(g_startTimerCond);
663     }
664     else
665     {
666         g_isUnicastScanInProgress = true;
667         // Reset Timer
668         oc_cond_signal(g_scanningTimeCond);
669     }
670     oc_mutex_unlock(g_scanMutex);
671
672     OIC_LOG(DEBUG, TAG, "OUT");
673     return ;
674 }
675
676 void CAStartTimerThread(void *data)
677 {
678     (void)data;
679
680     OIC_LOG(DEBUG, TAG, "IN");
681     while (g_isLEGattClientStarted)
682     {
683         oc_mutex_lock(g_scanMutex);
684         if (!g_isMulticastInProgress && !g_isUnicastScanInProgress)
685         {
686             OIC_LOG(DEBUG, TAG, "waiting....");
687             oc_cond_wait(g_startTimerCond, g_scanMutex);
688             OIC_LOG(DEBUG, TAG, "Wake up");
689         }
690
691         // Timed conditional wait for stopping the scan.
692         OCWaitResult_t ret = oc_cond_wait_for(g_scanningTimeCond, g_scanMutex,
693                                               TIMEOUT);
694         if (OC_WAIT_TIMEDOUT == ret)
695         {
696             OIC_LOG(DEBUG, TAG, "Scan is timed Out");
697             // Call stop scan.
698             CALEGattStopDeviceScanning();
699
700             if (g_isMulticastInProgress)
701             {
702                 oc_mutex_lock(g_multicastDataListMutex);
703                 // Clear the data list and device list.
704                 u_arraylist_destroy(g_multicastDataList);
705                 g_multicastDataList = NULL;
706                 oc_mutex_unlock(g_multicastDataListMutex);
707                 g_isMulticastInProgress = false;
708             }
709             g_isUnicastScanInProgress = false;
710         }
711         oc_mutex_unlock(g_scanMutex);
712     }
713
714     OIC_LOG(DEBUG, TAG, "OUT");
715 }
716
717 void CAStopLEGattClient()
718 {
719     OIC_LOG(DEBUG,  TAG, "IN");
720
721     oc_mutex_lock(g_LEClientStateMutex);
722
723     if (false == g_isLEGattClientStarted)
724     {
725         OIC_LOG(ERROR, TAG, "Gatt Client is not running to stop");
726         oc_mutex_unlock(g_LEClientStateMutex);
727         return;
728     }
729
730     CALEGattUnSetCallbacks();
731
732     CALEGattStopDeviceScanning();
733
734     g_isLEGattClientStarted = false;
735
736     // Signal the conditions waiting in Start timer.
737     oc_cond_signal(g_startTimerCond);
738     oc_cond_signal(g_scanningTimeCond);
739
740     // Destroy the multicast data list and device list if not empty.
741     if (NULL != g_multicastDataList)
742     {
743         oc_mutex_lock(g_multicastDataListMutex);
744         u_arraylist_destroy(g_multicastDataList);
745         g_multicastDataList = NULL;
746         oc_mutex_unlock(g_multicastDataListMutex);
747     }
748
749     oc_mutex_lock(g_LEServerListMutex);
750     CAFreeLEServerList(g_LEServerList);
751     g_LEServerList = NULL;
752     oc_mutex_unlock(g_LEServerListMutex);
753
754     oc_mutex_lock(g_threadWriteCharacteristicMutex);
755     oc_cond_signal(g_threadWriteCharacteristicCond);
756     oc_mutex_unlock(g_threadWriteCharacteristicMutex);
757
758     GMainContext  *context_event_loop = NULL;
759     // Required for waking up the thread which is running in gmain loop
760     if (NULL != g_eventLoop)
761     {
762         context_event_loop = g_main_loop_get_context(g_eventLoop);
763     }
764     if (context_event_loop)
765     {
766         OIC_LOG_V(DEBUG,  TAG, "g_eventLoop context %p", (void *)context_event_loop);
767         g_main_context_wakeup(context_event_loop);
768
769         // Kill g main loops and kill threads.
770         g_main_loop_quit(g_eventLoop);
771     }
772     else
773     {
774         OIC_LOG(ERROR, TAG, "g_eventLoop context is NULL");
775     }
776
777     oc_mutex_unlock(g_LEClientStateMutex);
778
779     OIC_LOG(DEBUG,  TAG, "OUT");
780 }
781
782 CAResult_t CAInitializeLEGattClient()
783 {
784     OIC_LOG(DEBUG, TAG, "Initialize GATT Client");
785     CAResult_t res = CAInitGattClientMutexVariables();
786     if (CA_STATUS_OK != res)
787     {
788         OIC_LOG(ERROR, TAG, "CAInitGattClientMutexVariables failed!");
789         CATerminateGattClientMutexVariables();
790         return CA_STATUS_FAILED;
791     }
792     return res;
793 }
794
795 void CATerminateLEGattClient()
796 {
797     OIC_LOG(DEBUG,  TAG, "IN");
798
799     CATerminateGattClientMutexVariables();
800
801     OIC_LOG(DEBUG,  TAG, "OUT");
802 }
803
804 CAResult_t CAInitGattClientMutexVariables()
805 {
806     OIC_LOG(DEBUG,  TAG, "IN");
807     if (NULL == g_LEClientStateMutex)
808     {
809         g_LEClientStateMutex = oc_mutex_new();
810         if (NULL == g_LEClientStateMutex)
811         {
812             OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
813             return CA_STATUS_FAILED;
814         }
815     }
816
817     if (NULL == g_LEServerListMutex)
818     {
819         g_LEServerListMutex = oc_mutex_new();
820         if (NULL == g_LEServerListMutex)
821         {
822             OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
823             return CA_STATUS_FAILED;
824         }
825     }
826
827     if (NULL == g_LEReqRespClientCbMutex)
828     {
829         g_LEReqRespClientCbMutex = oc_mutex_new();
830         if (NULL == g_LEReqRespClientCbMutex)
831         {
832             OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
833             return CA_STATUS_FAILED;
834         }
835     }
836
837     if (NULL == g_LEClientThreadPoolMutex)
838     {
839         g_LEClientThreadPoolMutex = oc_mutex_new();
840         if (NULL == g_LEClientThreadPoolMutex)
841         {
842             OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
843             return CA_STATUS_FAILED;
844         }
845     }
846
847     if (NULL == g_LEClientConnectMutex)
848     {
849         g_LEClientConnectMutex = oc_mutex_new();
850         if (NULL == g_LEClientConnectMutex)
851         {
852             OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
853             return CA_STATUS_FAILED;
854         }
855     }
856
857     if (NULL == g_isScanningInProgressMutex)
858     {
859         g_isScanningInProgressMutex = oc_mutex_new();
860         if (NULL == g_isScanningInProgressMutex)
861         {
862             OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
863             return CA_STATUS_FAILED;
864         }
865     }
866
867     if (NULL == g_isConnectionInProgressMutex)
868     {
869         g_isConnectionInProgressMutex = oc_mutex_new();
870         if (NULL == g_isConnectionInProgressMutex)
871         {
872             OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
873             return CA_STATUS_FAILED;
874         }
875     }
876
877     if (NULL == g_multicastDataListMutex)
878     {
879         g_multicastDataListMutex = oc_mutex_new();
880         if (NULL == g_multicastDataListMutex)
881         {
882             OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
883             return CA_STATUS_FAILED;
884         }
885     }
886
887     if (NULL == g_scanMutex)
888     {
889         g_scanMutex = oc_mutex_new();
890         if (NULL == g_scanMutex)
891         {
892             OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
893             return CA_STATUS_FAILED;
894         }
895     }
896
897     if (NULL == g_threadWriteCharacteristicMutex)
898     {
899         g_threadWriteCharacteristicMutex = oc_mutex_new();
900         if (NULL == g_threadWriteCharacteristicMutex)
901         {
902             OIC_LOG(ERROR, TAG, "oc_mutex_new has failed");
903             return CA_STATUS_FAILED;
904         }
905     }
906
907     if (NULL == g_threadMTUChangedMutex)
908     {
909         g_threadMTUChangedMutex = oc_mutex_new();
910         if (NULL == g_threadMTUChangedMutex)
911         {
912             OIC_LOG(ERROR, TAG, "oc_mutex_new has failed");
913             return CA_STATUS_FAILED;
914         }
915     }
916
917     if (NULL == g_startTimerCond)
918     {
919         g_startTimerCond = oc_cond_new();
920         if (NULL == g_startTimerCond)
921         {
922             OIC_LOG(ERROR, TAG, "oc_cond_new failed");
923             return CA_STATUS_FAILED;
924         }
925     }
926
927     if (NULL == g_scanningTimeCond)
928     {
929         g_scanningTimeCond = oc_cond_new();
930         if (NULL == g_scanningTimeCond)
931         {
932             OIC_LOG(ERROR, TAG, "oc_cond_new failed");
933             return CA_STATUS_FAILED;
934         }
935     }
936
937     if (NULL == g_threadWriteCharacteristicCond)
938     {
939         g_threadWriteCharacteristicCond = oc_cond_new();
940         if (NULL == g_threadWriteCharacteristicCond)
941         {
942             OIC_LOG(ERROR, TAG, "oc_cond_new failed");
943             return CA_STATUS_FAILED;
944         }
945     }
946
947     if (NULL == g_threadMTUChangedCond)
948     {
949         g_threadMTUChangedCond = oc_cond_new();
950         if (NULL == g_threadMTUChangedCond)
951         {
952             OIC_LOG(ERROR, TAG, "oc_cond_new failed");
953             return CA_STATUS_FAILED;
954         }
955     }
956
957
958     OIC_LOG(DEBUG,  TAG, "OUT");
959     return CA_STATUS_OK;
960 }
961
962 void CATerminateGattClientMutexVariables()
963 {
964     OIC_LOG(DEBUG,  TAG, "IN");
965
966     oc_mutex_free(g_LEClientStateMutex);
967     g_LEClientStateMutex = NULL;
968
969     oc_mutex_free(g_LEServerListMutex);
970     g_LEServerListMutex = NULL;
971
972     oc_mutex_free(g_LEReqRespClientCbMutex);
973     g_LEReqRespClientCbMutex = NULL;
974
975     oc_mutex_free(g_LEClientConnectMutex);
976     g_LEClientConnectMutex = NULL;
977
978     oc_mutex_free(g_LEClientThreadPoolMutex);
979     g_LEClientThreadPoolMutex = NULL;
980
981     oc_mutex_free(g_isScanningInProgressMutex);
982     g_isScanningInProgressMutex = NULL;
983
984     oc_mutex_free(g_isConnectionInProgressMutex);
985     g_isConnectionInProgressMutex = NULL;
986
987     oc_mutex_free(g_multicastDataListMutex);
988     g_multicastDataListMutex = NULL;
989
990     oc_mutex_free(g_scanMutex);
991     g_scanMutex = NULL;
992
993     oc_mutex_free(g_threadWriteCharacteristicMutex);
994     g_threadWriteCharacteristicMutex = NULL;
995
996     oc_mutex_free(g_threadMTUChangedMutex);
997     g_threadMTUChangedMutex = NULL;
998
999     oc_cond_free(g_startTimerCond);
1000     g_startTimerCond = NULL;
1001
1002     oc_cond_free(g_scanningTimeCond);
1003     g_scanningTimeCond = NULL;
1004
1005     oc_cond_free(g_threadWriteCharacteristicCond);
1006     g_threadWriteCharacteristicCond = NULL;
1007     g_isSignalSetFlag = false;
1008
1009     oc_cond_free(g_threadMTUChangedCond);
1010     g_threadMTUChangedCond = NULL;
1011
1012     OIC_LOG(DEBUG,  TAG, "OUT");
1013 }
1014
1015 CAResult_t CALEGattSetCallbacks()
1016 {
1017     OIC_LOG(DEBUG, TAG, "IN");
1018
1019     OIC_LOG(DEBUG, TAG, "OUT");
1020     return CA_STATUS_OK;
1021 }
1022
1023 void CALEGattUnSetCallbacks()
1024 {
1025     OIC_LOG(DEBUG, TAG, "IN");
1026
1027     bt_gatt_unset_connection_state_changed_cb();
1028
1029     oc_mutex_lock(g_LEServerListMutex);
1030     LEServerInfoList *curNode = g_LEServerList;
1031     while (curNode)
1032     {
1033         LEServerInfo *serverInfo = curNode->serverInfo;
1034         if (serverInfo->status >= LE_STATUS_SERVICES_DISCOVERED)
1035         {
1036             bt_gatt_client_unset_characteristic_value_changed_cb(serverInfo->readChar);
1037         }
1038         curNode = curNode->next;
1039     }
1040     oc_mutex_unlock(g_LEServerListMutex);
1041
1042     OIC_LOG(DEBUG, TAG, "OUT");
1043 }
1044
1045 CAResult_t CALEGattStartDeviceScanning()
1046 {
1047     OIC_LOG(DEBUG, TAG, "IN");
1048
1049     oc_mutex_lock(g_isScanningInProgressMutex);
1050     if (!g_isScanningInProgress)
1051     {
1052         int ret = bt_adapter_le_start_scan(CALEAdapterScanResultCb, NULL);
1053         if (BT_ERROR_NONE != ret)
1054         {
1055             oc_mutex_unlock(g_isScanningInProgressMutex);
1056             OIC_LOG_V(ERROR, TAG, "bt_adapter_le_start_scan failed[%s]",
1057                       CALEGetErrorMsg(ret));
1058             return CA_STATUS_FAILED;
1059         }
1060         g_isScanningInProgress = true;
1061     }
1062     else
1063     {
1064         OIC_LOG(DEBUG, TAG, "Ignore, scanning already in progress");
1065     }
1066     oc_mutex_unlock(g_isScanningInProgressMutex);
1067
1068     OIC_LOG(DEBUG, TAG, "OUT");
1069     return CA_STATUS_OK;
1070 }
1071
1072 void CALEGattStopDeviceScanning()
1073 {
1074     OIC_LOG(DEBUG, TAG, "IN");
1075
1076     oc_mutex_lock(g_isScanningInProgressMutex);
1077     if (g_isScanningInProgress)
1078     {
1079         int ret = bt_adapter_le_stop_scan();
1080         if (BT_ERROR_NONE != ret)
1081         {
1082             oc_mutex_unlock(g_isScanningInProgressMutex);
1083             OIC_LOG_V(ERROR, TAG, "bt_adapter_le_stop_scan failed[%s]",
1084                       CALEGetErrorMsg(ret));
1085             return;
1086         }
1087         g_isScanningInProgress = false;
1088         g_isUnicastScanInProgress= false;
1089     }
1090     else
1091     {
1092         OIC_LOG(DEBUG, TAG, "Ignore, scanning not in progress");
1093     }
1094     oc_mutex_unlock(g_isScanningInProgressMutex);
1095
1096     OIC_LOG(DEBUG, TAG, "OUT");
1097 }
1098
1099 void CAGattConnectThread (void *remoteAddress)
1100 {
1101     OIC_LOG(DEBUG, TAG, "IN ");
1102
1103     VERIFY_NON_NULL_VOID(remoteAddress, TAG, "remote address is NULL");
1104
1105     char *address  = (char *)remoteAddress;
1106
1107     OIC_LOG_V(DEBUG, TAG, "remote address is [%s]", address);
1108
1109     CAResult_t result = CALEGattConnect(address);
1110
1111     if (CA_STATUS_OK != result)
1112     {
1113         OIC_LOG_V(ERROR, TAG, "bt_gatt_connect failed for [%s]", address);
1114     }
1115
1116     OICFree(address);
1117
1118     OIC_LOG(DEBUG, TAG, "OUT");
1119 }
1120
1121 CAResult_t CALEGattConnect(const char *remoteAddress)
1122 {
1123     OIC_LOG(DEBUG, TAG, "IN");
1124
1125     VERIFY_NON_NULL_RET(remoteAddress, TAG,
1126                         "remote address is NULL", CA_STATUS_FAILED);
1127
1128     oc_mutex_lock(g_LEClientConnectMutex);
1129     CAResult_t result = CA_STATUS_OK;
1130
1131     int ret = bt_gatt_connect(remoteAddress, true);
1132     if (BT_ERROR_NONE != ret)
1133     {
1134         OIC_LOG_V(ERROR, TAG, "bt_gatt_connect Failed with ret value [%s] ",
1135                   CALEGetErrorMsg(ret));
1136         oc_mutex_unlock(g_LEClientConnectMutex);
1137         return CA_STATUS_FAILED;
1138     }
1139
1140     oc_mutex_unlock(g_LEClientConnectMutex);
1141
1142     OIC_LOG(DEBUG, TAG, "OUT");
1143     return result;
1144 }
1145
1146 CAResult_t CALEGattDisConnect(const char *remoteAddress)
1147 {
1148     OIC_LOG(DEBUG, TAG, "IN");
1149
1150     VERIFY_NON_NULL_RET(remoteAddress, TAG,
1151                         "remote address is NULL", CA_STATUS_FAILED);
1152
1153     int ret = bt_gatt_disconnect(remoteAddress);
1154
1155     if (BT_ERROR_NONE != ret)
1156     {
1157         OIC_LOG_V(ERROR, TAG, "bt_gatt_disconnect Failed with ret value [%s] ",
1158                   CALEGetErrorMsg(ret));
1159         return CA_STATUS_FAILED;
1160     }
1161
1162     OIC_LOG(DEBUG, TAG, "OUT");
1163     return CA_STATUS_OK;
1164 }
1165
1166 CAResult_t CAUpdateCharacteristicsToGattServerImpl(LEServerInfo *serverInfo,
1167         const uint8_t *data, const uint32_t dataLen)
1168 {
1169     OIC_LOG(DEBUG, TAG, "IN");
1170
1171     VERIFY_NON_NULL(serverInfo, TAG, "Server Info is NULL");
1172
1173     CALEGattStopDeviceScanning();
1174
1175     OIC_LOG_V(DEBUG, TAG, "Updating the data of length [%d] to [%s] ", dataLen,
1176               serverInfo->remoteAddress);
1177
1178     int result = bt_gatt_set_value(serverInfo->writeChar, (char *)data, dataLen);
1179
1180     if (BT_ERROR_NONE != result)
1181     {
1182         OIC_LOG_V(ERROR, TAG,
1183                   "bt_gatt_set_value Failed with return val [%s]",
1184                   CALEGetErrorMsg(result));
1185         goto exit;
1186     }
1187
1188     result = bt_gatt_client_write_value(serverInfo->writeChar, CALEGattCharacteristicWriteCb,
1189                                         NULL);
1190     if (BT_ERROR_NONE != result)
1191     {
1192         OIC_LOG_V(ERROR, TAG,
1193                   "bt_gatt_client_write_value Failed with return val [%s]",
1194                   CALEGetErrorMsg(result));
1195         goto exit;
1196     }
1197
1198     // wait for callback for write Characteristic with success to sent data
1199     OIC_LOG_V(DEBUG, TAG, "callback flag is %d", g_isSignalSetFlag);
1200     oc_mutex_lock(g_threadWriteCharacteristicMutex);
1201     if (!g_isSignalSetFlag)
1202     {
1203         OIC_LOG(DEBUG, TAG, "wait for callback to notify writeCharacteristic is success");
1204         if (OC_WAIT_SUCCESS != oc_cond_wait_for(g_threadWriteCharacteristicCond,
1205                                                 g_threadWriteCharacteristicMutex,
1206                                                 WAIT_TIME_WRITE_CHARACTERISTIC))
1207         {
1208             g_isSignalSetFlag = false;
1209             oc_mutex_unlock(g_threadWriteCharacteristicMutex);
1210             OIC_LOG(ERROR, TAG, "there is no response. write has failed");
1211             goto exit;
1212         }
1213     }
1214     // reset flag set by writeCharacteristic Callback
1215     g_isSignalSetFlag = false;
1216     oc_mutex_unlock(g_threadWriteCharacteristicMutex);
1217
1218     oc_mutex_lock(g_scanMutex);
1219     if (g_isMulticastInProgress || g_isUnicastScanInProgress)
1220     {
1221         if (CA_STATUS_OK != CALEGattStartDeviceScanning())
1222         {
1223             OIC_LOG(ERROR, TAG, "Could not start device scanning");
1224         }
1225     }
1226     oc_mutex_unlock(g_scanMutex);
1227     OIC_LOG(DEBUG, TAG, "OUT");
1228     return CA_STATUS_OK;
1229
1230 exit:
1231     oc_mutex_lock(g_scanMutex);
1232     if (g_isMulticastInProgress || g_isUnicastScanInProgress)
1233     {
1234         if (CA_STATUS_OK != CALEGattStartDeviceScanning())
1235         {
1236             OIC_LOG(ERROR, TAG, "Could not start device scanning");
1237         }
1238     }
1239     oc_mutex_unlock(g_scanMutex);
1240
1241     OIC_LOG(DEBUG, TAG, "OUT");
1242     return CA_STATUS_FAILED;
1243 }
1244
1245 void CADiscoverLEServicesThread(void *remoteAddress)
1246 {
1247     OIC_LOG(DEBUG, TAG, "IN");
1248
1249     VERIFY_NON_NULL_VOID(remoteAddress, TAG, "remote address is NULL");
1250
1251     char *address  = (char *)remoteAddress;
1252
1253     CAResult_t result = CALEGattDiscoverServices(address);
1254     if (CA_STATUS_OK != result)
1255     {
1256         OIC_LOG(ERROR, TAG, "CALEGattDiscoverServices failed");
1257     }
1258
1259     OICFree(address);
1260     OIC_LOG(DEBUG, TAG, "OUT");
1261 }
1262
1263 CAResult_t CALEGattDiscoverServices(const char *remoteAddress)
1264 {
1265     OIC_LOG(DEBUG, TAG, "IN");
1266
1267     VERIFY_NON_NULL_RET(remoteAddress, TAG,
1268                         "remote address is NULL", CA_STATUS_FAILED);
1269
1270     LEServerInfo *serverInfo = NULL;
1271     unsigned int mtu_size;
1272     oc_mutex_lock(g_LEServerListMutex);
1273     if (CA_STATUS_OK != CAGetLEServerInfo(g_LEServerList, remoteAddress, &serverInfo))
1274     {
1275         oc_mutex_unlock(g_LEServerListMutex);
1276         OIC_LOG_V(ERROR, TAG, "Could not get server info for [%s]", remoteAddress);
1277         CALEGattDisConnect(remoteAddress);
1278         return CA_STATUS_FAILED;
1279     }
1280
1281     bt_gatt_h serviceHandle = NULL;
1282     int32_t ret = bt_gatt_client_get_service(serverInfo->clientHandle, CA_GATT_SERVICE_UUID, &serviceHandle);
1283     if (BT_ERROR_NONE != ret || NULL == serviceHandle)
1284     {
1285         OIC_LOG_V(ERROR, TAG,
1286                   "bt_gatt_client_get_service Failed with ret value [%s] ", CALEGetErrorMsg(ret));
1287         goto error_exit;
1288     }
1289
1290     // Server will read data on this characteristic.
1291     bt_gatt_h writeChrHandle = NULL;
1292     ret = bt_gatt_service_get_characteristic(serviceHandle, CA_GATT_REQUEST_CHRC_UUID,
1293             &writeChrHandle);
1294     if (BT_ERROR_NONE != ret || NULL == writeChrHandle)
1295     {
1296         OIC_LOG_V(ERROR, TAG,
1297                   "bt_gatt_service_get_characteristic Failed with ret value [%s] ",
1298                   CALEGetErrorMsg(ret));
1299         goto error_exit;
1300     }
1301
1302     // Server will notify data on this characteristic.
1303     bt_gatt_h readChrHandle = NULL;
1304     ret = bt_gatt_service_get_characteristic(serviceHandle, CA_GATT_RESPONSE_CHRC_UUID,
1305             &readChrHandle);
1306     if (BT_ERROR_NONE != ret || NULL == readChrHandle)
1307     {
1308         OIC_LOG_V(ERROR, TAG,
1309                   "bt_gatt_service_get_characteristic Failed with ret value [%s] ",
1310                   CALEGetErrorMsg(ret));
1311         goto error_exit;
1312     }
1313
1314     //TODO: This data has to be freed while unsetting the callback.
1315     char *addr = OICStrdup(remoteAddress);
1316     if (NULL == addr)
1317     {
1318         OIC_LOG(ERROR, TAG, "addr is NULL");
1319         goto error_exit;
1320     }
1321
1322     ret = bt_gatt_client_set_characteristic_value_changed_cb(readChrHandle,
1323             CALEGattCharacteristicChangedCb,
1324             (void *)addr);
1325     if (BT_ERROR_NONE != ret)
1326     {
1327         OIC_LOG_V(ERROR, TAG,
1328                   "bt_gatt_client_set_characteristic_value_changed_cb Failed with ret value [%s]",
1329                   CALEGetErrorMsg(ret));
1330         goto error_exit;
1331     }
1332
1333     ret = bt_gatt_client_set_att_mtu_changed_cb(serverInfo->clientHandle,
1334             CALEGattClientMTUChangedCb,
1335             (void *)serverInfo->remoteAddress);
1336     if (BT_ERROR_NONE != ret)
1337     {
1338         OIC_LOG_V(ERROR, TAG,
1339                   "bt_gatt_client_set_att_mtu_changed_cb Failed with ret value [%s]",
1340                   CALEGetErrorMsg(ret));
1341         goto error_exit;
1342     }
1343
1344     oc_mutex_lock(g_threadMTUChangedMutex);
1345     ret = bt_gatt_client_request_att_mtu_change(serverInfo->clientHandle, CA_SUPPORTED_BLE_MTU_SIZE - CA_BLE_MTU_HEADER_SIZE);
1346     if (BT_ERROR_NONE != ret)
1347     {
1348         OIC_LOG_V(ERROR, TAG,
1349                   "bt_gatt_client_request_att_mtu_change Failed with ret value [%s]",
1350                   CALEGetErrorMsg(ret));
1351         oc_mutex_unlock(g_threadMTUChangedMutex);
1352         goto error_exit;
1353     }
1354
1355     OIC_LOG(DEBUG, TAG, "wait for callback to notify MTU Changed Callback");
1356     oc_cond_wait(g_threadMTUChangedCond, g_threadMTUChangedMutex);
1357     oc_mutex_unlock(g_threadMTUChangedMutex);
1358
1359     OIC_LOG(DEBUG, TAG, "Done MTU");
1360     ret = bt_gatt_client_get_att_mtu(serverInfo->clientHandle, &mtu_size);
1361     if (BT_ERROR_NONE != ret)
1362     {
1363         OIC_LOG_V(ERROR, TAG,
1364                   "bt_gatt_client_get_att_mtu Failed with ret value [%s]",
1365                   CALEGetErrorMsg(ret));
1366         goto error_exit;
1367     }
1368     OIC_LOG_V(DEBUG, TAG,"Negotiated MTU Size %d",mtu_size);
1369
1370     serverInfo->serviceHandle = serviceHandle;
1371     serverInfo->readChar = readChrHandle;
1372     serverInfo->writeChar = writeChrHandle;
1373     serverInfo->status = LE_STATUS_SERVICES_DISCOVERED;
1374     serverInfo->mtu_size = mtu_size;
1375
1376     while (serverInfo->pendingDataList)
1377     {
1378         LEData *leData = serverInfo->pendingDataList->data;
1379         if (CA_STATUS_OK != CAUpdateCharacteristicsToGattServerImpl(
1380                 serverInfo, leData->data, leData->dataLength))
1381         {
1382             OIC_LOG_V(ERROR, TAG, "Failed to send pending data to [%s]",
1383                       serverInfo->remoteAddress);
1384
1385             CADestroyLEDataList(&serverInfo->pendingDataList);
1386             break;
1387         }
1388         CARemoveLEDataFromList(&serverInfo->pendingDataList);
1389     }
1390     oc_mutex_unlock(g_LEServerListMutex);
1391
1392     OIC_LOG(DEBUG, TAG, "OUT");
1393     return CA_STATUS_OK;
1394
1395 error_exit:
1396     bt_gatt_client_destroy(serverInfo->clientHandle);
1397     serverInfo->clientHandle = NULL;
1398     oc_mutex_unlock(g_LEServerListMutex);
1399     CALEGattDisConnect(remoteAddress);
1400     return CA_STATUS_FAILED;
1401 }
1402
1403 CAResult_t CAUpdateCharacteristicsToGattServer(const char *remoteAddress,
1404         const uint8_t *data, const uint32_t dataLen,
1405         CALETransferType_t type, const int32_t position)
1406 {
1407     OIC_LOG(DEBUG, TAG, "IN");
1408
1409     VERIFY_NON_NULL(data, TAG, "data is NULL");
1410
1411     if (0 == dataLen)
1412     {
1413         OIC_LOG(ERROR, TAG, "dataLen is less than or equal zero. Invalid input!");
1414         return CA_STATUS_INVALID_PARAM;
1415     }
1416
1417     LEServerInfo *serverInfo = NULL;
1418     oc_mutex_lock(g_LEServerListMutex);
1419     if (LE_UNICAST == type)
1420     {
1421         if (CA_STATUS_OK != CAGetLEServerInfo(g_LEServerList, remoteAddress, &serverInfo))
1422         {
1423             OIC_LOG_V(DEBUG, TAG,
1424                       "Device with address [%s] not yet found, initiating scan",
1425                       remoteAddress);
1426
1427             char *addr = OICStrdup(remoteAddress);
1428             if (NULL == addr)
1429             {
1430                 oc_mutex_unlock(g_LEServerListMutex);
1431                 OIC_LOG(ERROR, TAG, "Device address is NULL");
1432                 return CA_STATUS_FAILED;
1433             }
1434             serverInfo = (LEServerInfo *)OICCalloc(1, sizeof(LEServerInfo));
1435             if (NULL == serverInfo)
1436             {
1437                 oc_mutex_unlock(g_LEServerListMutex);
1438                 OIC_LOG(ERROR, TAG, "Calloc failed");
1439                 OICFree(addr);
1440                 return CA_STATUS_FAILED;
1441             }
1442             serverInfo->remoteAddress = addr;
1443             serverInfo->status = LE_STATUS_UNICAST_PENDING;
1444
1445             if (CA_STATUS_OK != CAAddLEServerInfoToList(&g_LEServerList, serverInfo))
1446             {
1447                 oc_mutex_unlock(g_LEServerListMutex);
1448                 OIC_LOG_V(ERROR, TAG, "Could not add [%s] to server list", remoteAddress);
1449                 CAFreeLEServerInfo(serverInfo);
1450                 return CA_STATUS_FAILED;
1451             }
1452
1453             if (CA_STATUS_OK != CAAddLEDataToList(&serverInfo->pendingDataList, data, dataLen))
1454             {
1455                 oc_mutex_unlock(g_LEServerListMutex);
1456                 OIC_LOG(ERROR, TAG, "Could not add data to pending list");
1457                 return CA_STATUS_FAILED;
1458             }
1459         }
1460
1461         if(serverInfo->status == LE_STATUS_UNICAST_PENDING)
1462         {
1463             oc_mutex_lock(g_scanMutex);
1464             if (!g_isMulticastInProgress && !g_isUnicastScanInProgress)
1465             {
1466                 CAResult_t result = CALEGattStartDeviceScanning();
1467                 if (CA_STATUS_OK != result)
1468                 {
1469                     oc_mutex_unlock(g_scanMutex);
1470                     OIC_LOG(ERROR, TAG, "CALEGattStartDeviceScanning failed");
1471                     return CA_STATUS_FAILED;
1472                 }
1473                 g_isUnicastScanInProgress = true;
1474                 // Start Timer
1475                 oc_cond_signal(g_startTimerCond);
1476             }
1477             else
1478             {
1479                 g_isUnicastScanInProgress = true;
1480                 // Reset Timer
1481                 oc_cond_signal(g_scanningTimeCond);
1482             }
1483             oc_mutex_unlock(g_scanMutex);
1484
1485         }
1486
1487         if (serverInfo->status == LE_STATUS_DISCOVERED)
1488         {
1489             if (CA_STATUS_OK != CAAddLEDataToList(&serverInfo->pendingDataList, data, dataLen))
1490             {
1491                 oc_mutex_unlock(g_LEServerListMutex);
1492                 OIC_LOG(ERROR, TAG, "Could not add data to pending list");
1493                 return CA_STATUS_FAILED;
1494             }
1495
1496             bt_gatt_client_h clientHandle = NULL;
1497             int32_t ret = bt_gatt_client_create(serverInfo->remoteAddress, &clientHandle);
1498             if (BT_ERROR_NONE != ret || NULL == clientHandle)
1499             {
1500                 OIC_LOG_V(ERROR, TAG,
1501                           "bt_gatt_client_create Failed with ret value [%s] ", CALEGetErrorMsg(ret));
1502                 CALEGattDisConnect(serverInfo->remoteAddress);
1503                 return CA_STATUS_FAILED;
1504             }
1505             serverInfo->clientHandle = clientHandle;
1506
1507             serverInfo->status = LE_STATUS_CONNECTION_INITIATED;
1508             if (CA_STATUS_OK != CALEGattInitiateConnection(serverInfo->remoteAddress))
1509             {
1510                 OIC_LOG_V(ERROR, TAG, "Could not initiate connection to [%s]", serverInfo->remoteAddress);
1511                 serverInfo->status = LE_STATUS_DISCOVERED;
1512                 CADestroyLEDataList(&serverInfo->pendingDataList);
1513                 oc_mutex_unlock(g_LEServerListMutex);
1514                 return CA_STATUS_FAILED;
1515             }
1516         }
1517         else if (serverInfo->status < LE_STATUS_SERVICES_DISCOVERED)
1518         {
1519             if (CA_STATUS_OK != CAAddLEDataToList(&serverInfo->pendingDataList, data, dataLen))
1520             {
1521                 oc_mutex_unlock(g_LEServerListMutex);
1522                 OIC_LOG(ERROR, TAG, "Could not add data to pending list");
1523                 return CA_STATUS_FAILED;
1524             }
1525         }
1526         else
1527         {
1528             if (CA_STATUS_OK != CAUpdateCharacteristicsToGattServerImpl(serverInfo, data, dataLen))
1529             {
1530                 OIC_LOG_V(ERROR, TAG, "Could not update characteristic to gatt server [%s]",
1531                           serverInfo->remoteAddress);
1532                 oc_mutex_unlock(g_LEServerListMutex);
1533                 return CA_STATUS_FAILED;
1534             }
1535         }
1536     }
1537     else if (LE_MULTICAST == type)
1538     {
1539         OIC_LOG(ERROR, TAG, "LE_MULTICAST type Not used");
1540     }
1541     oc_mutex_unlock(g_LEServerListMutex);
1542     OIC_LOG(DEBUG, TAG, "OUT");
1543     return CA_STATUS_OK;
1544 }
1545
1546 CAResult_t CAUpdateCharacteristicsToAllGattServers(const uint8_t *data, uint32_t dataLen)
1547 {
1548     OIC_LOG(DEBUG,  TAG, "IN");
1549
1550     VERIFY_NON_NULL(data, TAG, "data is NULL");
1551
1552     if (0 == dataLen)
1553     {
1554         OIC_LOG(ERROR, TAG, "dataLen is less than or equal zero. Invalid input !");
1555         return CA_STATUS_INVALID_PARAM;
1556     }
1557
1558     oc_mutex_lock(g_LEServerListMutex);
1559     LEServerInfoList *curNode = g_LEServerList;
1560     while (curNode)
1561     {
1562         LEServerInfo *serverInfo = curNode->serverInfo;
1563         if (serverInfo->status == LE_STATUS_SERVICES_DISCOVERED)
1564         {
1565             if (CA_STATUS_OK != CAUpdateCharacteristicsToGattServerImpl(serverInfo, data, dataLen))
1566             {
1567                 OIC_LOG_V(ERROR, TAG, "Failed to update characteristics to gatt server [%s]",
1568                           serverInfo->remoteAddress);
1569             }
1570         }
1571         else if (serverInfo->status != LE_STATUS_INVALID)
1572         {
1573             if (CA_STATUS_OK != CAAddLEDataToList(&serverInfo->pendingDataList, data, dataLen))
1574             {
1575                 OIC_LOG(ERROR, TAG, "Failed to add to pending list");
1576             }
1577         }
1578         curNode = curNode->next;
1579     }
1580     oc_mutex_unlock(g_LEServerListMutex);
1581
1582     // Add the data to pending list.
1583     LEData *multicastData = (LEData *)OICCalloc(1, sizeof(LEData));
1584     if (NULL == multicastData)
1585     {
1586         OIC_LOG(ERROR, TAG, "Calloc failed");
1587         goto exit;
1588     }
1589     multicastData->data = OICCalloc(1, dataLen);
1590     if (NULL == multicastData->data)
1591     {
1592         OIC_LOG(ERROR, TAG, "Calloc failed");
1593         goto exit;
1594     }
1595     memcpy(multicastData->data, data, dataLen);
1596     multicastData->dataLength = dataLen;
1597
1598     oc_mutex_lock(g_multicastDataListMutex);
1599     if (NULL == g_multicastDataList)
1600     {
1601         g_multicastDataList = u_arraylist_create();
1602     }
1603     u_arraylist_add(g_multicastDataList, (void *)multicastData);
1604     oc_mutex_unlock(g_multicastDataListMutex);
1605
1606     // Start the scanning, if not started, else reset timer
1607     oc_mutex_lock(g_scanMutex);
1608     if (!g_isMulticastInProgress && !g_isUnicastScanInProgress)
1609     {
1610         CAResult_t result = CALEGattStartDeviceScanning();
1611         if (CA_STATUS_OK != result)
1612         {
1613             oc_mutex_unlock(g_scanMutex);
1614             OIC_LOG(ERROR, TAG, "CALEGattStartDeviceScanning Failed");
1615             goto exit;
1616         }
1617         g_isMulticastInProgress = true;
1618         // Start the timer by signalling it
1619         oc_cond_signal(g_startTimerCond);
1620     }
1621     else
1622     {
1623         g_isMulticastInProgress = true;
1624         // Reset timer
1625         oc_cond_signal(g_scanningTimeCond);
1626     }
1627     oc_mutex_unlock(g_scanMutex);
1628
1629 exit:
1630     OIC_LOG(DEBUG, TAG, "OUT ");
1631     return CA_STATUS_OK;
1632 }
1633
1634 uint16_t CALEClientGetMtuSize(const char* remote_address)
1635 {
1636     LEServerInfo *serverInfo = NULL;
1637     oc_mutex_lock(g_LEServerListMutex);
1638     if (CA_STATUS_OK == CAGetLEServerInfo(g_LEServerList, remote_address, &serverInfo))
1639     {
1640         if (serverInfo->status == LE_STATUS_SERVICES_DISCOVERED){
1641             OIC_LOG_V(DEBUG, TAG, "Mtu Size [%d]", serverInfo->mtu_size);
1642             oc_mutex_unlock(g_LEServerListMutex);
1643             OIC_LOG_V(INFO, TAG, "Test: returning Mtu Size [%d]", serverInfo->mtu_size - CA_BLE_MTU_HEADER_SIZE);
1644             return serverInfo->mtu_size - CA_BLE_MTU_HEADER_SIZE;
1645         }
1646     }
1647     oc_mutex_unlock(g_LEServerListMutex);
1648     return CA_DEFAULT_BLE_MTU_SIZE;
1649 }
1650
1651 bool CALEClientIsConnected(const char* address)
1652 {
1653     (void)address;
1654     //@Todo
1655     return true;
1656 }
1657
1658 CAResult_t CALEClientSendNegotiationMessage(const char* address)
1659 {
1660     /* MCD : change the log as INFO_PRIVATE for security */
1661     OIC_LOG_V(INFO_PRIVATE, TAG, "CALEClientSendNegotiationMessage(%s)", address);
1662     //@Todo
1663     //it will be implemented when tizen public 3.0 is released.
1664     return CA_NOT_SUPPORTED;
1665 }