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