1 /* ****************************************************************
3 * Copyright 2014 Samsung Electronics All Rights Reserved.
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 ******************************************************************/
21 #include "caleclient.h"
26 #include <arpa/inet.h>
27 #include <sys/types.h>
28 #include <sys/socket.h>
29 #include <netinet/in.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"
42 * Logging tag for module name.
44 #define TAG "OIC_CA_LE_CLIENT"
46 #define MICROSECS_PER_SEC 1000000
47 #define WAIT_TIME_WRITE_CHARACTERISTIC 10 * MICROSECS_PER_SEC
49 uint64_t const TIMEOUT = 30 * MICROSECS_PER_SEC;
52 * Flag to check if multicast is already in progress.
54 static bool g_isMulticastInProgress = false;
57 * Pending multicast data list to be sent.
59 static u_arraylist_t *g_multicastDataList = NULL;
62 * Mutex to synchronize the access to Pending multicast data list.
64 static ca_mutex g_multicastDataListMutex = NULL;
67 * List of devices discovered.
69 static u_arraylist_t *g_deviceDiscoveredList = NULL;
72 * Mutex to synchronize the access to discovered devices list.
74 static ca_mutex g_deviceDiscoveredListMutex = NULL;
77 * Condition to start the timer for scanning.
79 static ca_cond g_startTimerCond = NULL;
82 * Condition for scanning Time interval.
84 static ca_cond g_scanningTimeCond = NULL;
87 * This contains the list of OIC services a client connect tot.
89 static LEServerInfoList *g_LEServerList = NULL;
92 * Mutex to synchronize access to BleServiceList.
94 static ca_mutex g_LEServerListMutex = NULL;
97 * Boolean variable to keep the state of the GATT Client.
99 static bool g_isLEGattClientStarted = false;
102 * Mutex to synchronize access to the requestResponse callback to be called
103 * when the data needs to be sent from GATTClient.
105 static ca_mutex g_LEReqRespClientCbMutex = NULL;
108 * Mutex to synchronize access to the requestResponse callback to be called
109 * when the data needs to be sent from GATTClient.
111 static ca_mutex g_LEClientConnectMutex = NULL;
114 * Mutex to synchronize the calls to be done to the platform from GATTClient
115 * interfaces from different threads.
117 static ca_mutex g_LEClientStateMutex = NULL;
120 * Mutex to synchronize the task to be pushed to thread pool.
122 static ca_mutex g_LEClientThreadPoolMutex = NULL;
125 * Mutex to synchronize the task to write characteristic one packet after another.
127 static ca_mutex g_threadWriteCharacteristicMutex = NULL;
130 * Condition for Writing characteristic.
132 static ca_cond g_threadWriteCharacteristicCond = NULL;
135 * Flag to check status of write characteristic.
137 static bool g_isSignalSetFlag = false;
140 * Maintains the callback to be notified on receival of network packets from other
143 static CABLEDataReceivedCallback g_LEClientDataReceivedCallback = NULL;
146 * callback to update the error to le adapter
148 static CABLEErrorHandleCallback g_clientErrorCallback;
151 * gmainLoop to manage the threads to receive the callback from the platfrom.
153 static GMainLoop *g_eventLoop = NULL;
156 * Reference to threadpool
158 static ca_thread_pool_t g_LEClientThreadPool = NULL;
160 bt_scan_filter_h g_scanFilter = NULL;
162 bool CALEIsDeviceDiscovered(const char * address)
164 OIC_LOG(DEBUG, TAG, "IN");
165 if (g_deviceDiscoveredList)
167 ca_mutex_lock(g_deviceDiscoveredListMutex);
168 uint32_t arrayLength = u_arraylist_length(g_deviceDiscoveredList);
169 for (int i = 0; i < arrayLength; i++)
171 char *deviceAddr = u_arraylist_get(g_deviceDiscoveredList, i);
172 if (0 == strcasecmp(deviceAddr, address))
174 OIC_LOG(DEBUG, TAG, "Device Found");
175 ca_mutex_unlock(g_deviceDiscoveredListMutex);
180 ca_mutex_unlock(g_deviceDiscoveredListMutex);
182 OIC_LOG(DEBUG, TAG, "OUT");
186 void CALEGattCharacteristicChangedCb(bt_gatt_h characteristic,
188 int valueLen, void *userData)
190 OIC_LOG(DEBUG, TAG, "IN");
191 OIC_LOG_V(DEBUG, TAG, "Changed characteristic value length [%d]", valueLen);
193 ca_mutex_lock(g_LEReqRespClientCbMutex);
194 if (NULL == g_LEClientDataReceivedCallback)
196 OIC_LOG(ERROR, TAG, "Request response callback is not set");
197 ca_mutex_unlock(g_LEReqRespClientCbMutex);
201 uint32_t sentLength = 0;
202 g_LEClientDataReceivedCallback(userData, (uint8_t *)value, valueLen, &sentLength);
204 OIC_LOG_V(DEBUG, TAG, "Sent data Length is %d", sentLength);
206 ca_mutex_unlock(g_LEReqRespClientCbMutex);
208 OIC_LOG(DEBUG, TAG, "OUT");
211 void CALEGattCharacteristicWriteCb(int result, bt_gatt_h reqHandle, void *userData)
213 OIC_LOG(DEBUG, TAG, "IN ");
215 if (BT_ERROR_NONE != result)
217 OIC_LOG(ERROR, TAG, "Write failed Need Retry ");
218 //Need to Implement retry mechanism
222 ca_mutex_lock(g_threadWriteCharacteristicMutex);
223 OIC_LOG(DEBUG, TAG, "g_isSignalSetFlag is set true and signal");
224 g_isSignalSetFlag = true;
225 ca_cond_signal(g_threadWriteCharacteristicCond);
226 ca_mutex_unlock(g_threadWriteCharacteristicMutex);
229 OIC_LOG(DEBUG, TAG, "OUT ");
232 void CALEGattConnectionStateChanged(bool connected, const char *remoteAddress)
234 OIC_LOG(DEBUG, TAG, "IN ");
236 VERIFY_NON_NULL_VOID(remoteAddress, TAG, "remote address is NULL");
238 // Start the scanning.
239 CAResult_t ret = CALEGattStartDeviceScanning();
240 if (CA_STATUS_OK != ret)
242 OIC_LOG(ERROR, TAG, "CALEGattStartDeviceDiscovery Failed");
244 // Signal the start timer.
245 ca_cond_signal(g_scanningTimeCond);
249 OIC_LOG_V(DEBUG, TAG, "DisConnected from [%s] ", remoteAddress);
250 ca_mutex_lock(g_LEServerListMutex);
251 CARemoveLEServerInfoFromList(&g_LEServerList, remoteAddress);
252 ca_mutex_unlock(g_LEServerListMutex);
256 OIC_LOG_V(DEBUG, TAG, "Connected to [%s] ", remoteAddress);
258 char *addr = OICStrdup(remoteAddress);
260 ca_mutex_lock(g_LEClientThreadPoolMutex);
261 if (NULL == g_LEClientThreadPool)
263 OIC_LOG(ERROR, TAG, "g_LEClientThreadPool is NULL");
265 ca_mutex_unlock(g_LEClientThreadPoolMutex);
269 ret = ca_thread_pool_add_task(g_LEClientThreadPool, CADiscoverLEServicesThread,
271 if (CA_STATUS_OK != ret)
273 OIC_LOG_V(ERROR, TAG, "ca_thread_pool_add_task failed with ret [%d]", ret);
276 ca_mutex_unlock(g_LEClientThreadPoolMutex);
278 OIC_LOG(DEBUG, TAG, "OUT");
281 void CALEAdapterScanResultCb(int result, bt_adapter_le_device_scan_result_info_s *scanInfo,
284 OIC_LOG(DEBUG, TAG, "IN");
286 VERIFY_NON_NULL_VOID(scanInfo, TAG, "scanInfo");
287 VERIFY_NON_NULL_VOID(scanInfo->remote_address, TAG, "scanInfo->remote_address");
289 OIC_LOG_V(DEBUG, TAG, "Remote Address [%s]", scanInfo->remote_address);
290 OIC_LOG_V(DEBUG, TAG, "Scan Result [%d]", result);
291 OIC_LOG_V(DEBUG, TAG,
292 " Adv data len [%d] Scan data len[%d]RSSI [%d] Addr_type [%d] ",
293 scanInfo->adv_data_len, scanInfo->scan_data_len, scanInfo->rssi,
294 scanInfo->address_type);
296 // Check if device is already discovered.
297 if (CALEIsDeviceDiscovered(scanInfo->remote_address))
299 OIC_LOG_V(INFO, TAG, "Device[%s] is already discovered", scanInfo->remote_address);
303 // Stop the scan before invoking bt_gatt_connect().
304 CALEGattStopDeviceScanning();
306 ca_mutex_lock(g_deviceDiscoveredListMutex);
307 // Add the the device Discovered list.
308 if (NULL == g_deviceDiscoveredList)
310 g_deviceDiscoveredList = u_arraylist_create();
312 char *deviceAddr = OICStrdup(scanInfo->remote_address);
313 u_arraylist_add(g_deviceDiscoveredList, (void *) deviceAddr);
314 ca_mutex_unlock(g_deviceDiscoveredListMutex);
316 size_t len = strlen(scanInfo->remote_address);
318 char *addr = (char *)OICMalloc(sizeof(char) * (len + 1));
319 VERIFY_NON_NULL_VOID(addr, TAG, "Malloc failed");
321 strncpy(addr, scanInfo->remote_address, len + 1);
323 OIC_LOG_V(DEBUG, TAG,
324 "Trying to do Gatt connection to [%s]", addr);
326 ca_mutex_lock(g_LEClientThreadPoolMutex);
327 if (NULL == g_LEClientThreadPool)
329 OIC_LOG(ERROR, TAG, "g_LEClientThreadPool is NULL");
331 ca_mutex_unlock(g_LEClientThreadPoolMutex);
335 CAResult_t res = ca_thread_pool_add_task(g_LEClientThreadPool, CAGattConnectThread, addr);
336 if (CA_STATUS_OK != res)
338 OIC_LOG_V(ERROR, TAG,
339 "ca_thread_pool_add_task failed with ret [%d]", res);
342 ca_mutex_unlock(g_LEClientThreadPoolMutex);
343 OIC_LOG(DEBUG, TAG, "OUT");
346 void CASetLEClientThreadPoolHandle(ca_thread_pool_t handle)
348 OIC_LOG(DEBUG, TAG, "IN");
350 ca_mutex_lock(g_LEClientThreadPoolMutex);
351 g_LEClientThreadPool = handle;
352 ca_mutex_unlock(g_LEClientThreadPoolMutex);
354 OIC_LOG(DEBUG, TAG, "OUT");
357 void CASetLEReqRespClientCallback(CABLEDataReceivedCallback callback)
359 OIC_LOG(DEBUG, TAG, "IN");
361 ca_mutex_lock(g_LEReqRespClientCbMutex);
363 g_LEClientDataReceivedCallback = callback;
365 ca_mutex_unlock(g_LEReqRespClientCbMutex);
367 OIC_LOG(DEBUG, TAG, "OUT");
370 void CASetBLEClientErrorHandleCallback(CABLEErrorHandleCallback callback)
372 g_clientErrorCallback = callback;
375 CAResult_t CAStartLEGattClient()
377 OIC_LOG(DEBUG, TAG, "IN");
379 ca_mutex_lock(g_LEClientStateMutex);
380 if (true == g_isLEGattClientStarted)
382 OIC_LOG(ERROR, TAG, "Gatt Client is already running!!");
383 ca_mutex_unlock(g_LEClientStateMutex);
384 return CA_STATUS_FAILED;
387 CAResult_t result = CALEGattSetCallbacks();
388 if (CA_STATUS_OK != result)
390 OIC_LOG(ERROR, TAG, "CABleGattSetCallbacks Failed");
391 ca_mutex_unlock(g_LEClientStateMutex);
392 CATerminateLEGattClient();
393 return CA_STATUS_FAILED;
396 g_isLEGattClientStarted = true;
397 ca_mutex_unlock(g_LEClientStateMutex);
399 ca_mutex_lock(g_LEClientThreadPoolMutex);
400 if (NULL == g_LEClientThreadPool)
402 OIC_LOG(ERROR, TAG, "gBleServerThreadPool is NULL");
403 CATerminateGattClientMutexVariables();
404 ca_mutex_unlock(g_LEClientThreadPoolMutex);
405 return CA_STATUS_FAILED;
408 result = ca_thread_pool_add_task(g_LEClientThreadPool, CAStartTimerThread,
410 if (CA_STATUS_OK != result)
412 OIC_LOG(ERROR, TAG, "ca_thread_pool_add_task failed");
413 CATerminateGattClientMutexVariables();
414 ca_mutex_unlock(g_LEClientThreadPoolMutex);
415 return CA_STATUS_FAILED;
417 ca_mutex_unlock(g_LEClientThreadPoolMutex);
419 OIC_LOG(DEBUG, TAG, "OUT");
423 void CAStartTimerThread(void *data)
425 OIC_LOG(DEBUG, TAG, "IN");
426 while (g_isLEGattClientStarted)
428 ca_mutex_lock(g_multicastDataListMutex);
429 if (!g_isMulticastInProgress)
431 OIC_LOG(DEBUG, TAG, "waiting....");
432 ca_cond_wait(g_startTimerCond, g_multicastDataListMutex);
433 OIC_LOG(DEBUG, TAG, "Wake up");
434 g_isMulticastInProgress = true;
437 // Timed conditional wait for stopping the scan.
438 CAWaitResult_t ret = ca_cond_wait_for(g_scanningTimeCond, g_multicastDataListMutex,
440 if (CA_WAIT_TIMEDOUT == ret)
442 OIC_LOG(DEBUG, TAG, "Scan is timed Out");
444 CALEGattStopDeviceScanning();
446 // Clear the data list and device list.
447 u_arraylist_destroy(g_multicastDataList);
448 g_multicastDataList = NULL;
450 ca_mutex_lock(g_deviceDiscoveredListMutex);
451 u_arraylist_destroy(g_deviceDiscoveredList);
452 g_deviceDiscoveredList = NULL;
453 ca_mutex_unlock(g_deviceDiscoveredListMutex);
455 g_isMulticastInProgress = false;
457 ca_mutex_unlock(g_multicastDataListMutex);
460 OIC_LOG(DEBUG, TAG, "OUT");
463 void CAStopLEGattClient()
465 OIC_LOG(DEBUG, TAG, "IN");
467 ca_mutex_lock(g_LEClientStateMutex);
469 if (false == g_isLEGattClientStarted)
471 OIC_LOG(ERROR, TAG, "Gatt Client is not running to stop");
472 ca_mutex_unlock(g_LEClientStateMutex);
476 CALEGattUnSetCallbacks();
478 CALEGattStopDeviceScanning();
480 g_isLEGattClientStarted = false;
482 // Signal the conditions waiting in Start timer.
483 ca_cond_signal(g_startTimerCond);
484 ca_cond_signal(g_scanningTimeCond);
486 // Destroy the multicast data list and device list if not empty.
487 if (NULL != g_multicastDataList)
489 ca_mutex_lock(g_multicastDataListMutex);
490 u_arraylist_destroy(g_multicastDataList);
491 g_multicastDataList = NULL;
492 ca_mutex_unlock(g_multicastDataListMutex);
495 if (NULL != g_deviceDiscoveredList)
497 ca_mutex_lock(g_deviceDiscoveredListMutex);
498 u_arraylist_destroy(g_deviceDiscoveredList);
499 g_deviceDiscoveredList = NULL;
500 ca_mutex_unlock(g_deviceDiscoveredListMutex);
503 ca_mutex_lock(g_LEServerListMutex);
504 CAFreeLEServerList(g_LEServerList);
505 g_LEServerList = NULL;
506 ca_mutex_unlock(g_LEServerListMutex);
508 ca_mutex_lock(g_threadWriteCharacteristicMutex);
509 ca_cond_signal(g_threadWriteCharacteristicCond);
510 ca_mutex_unlock(g_threadWriteCharacteristicMutex);
512 CAResetRegisteredServiceCount();
514 GMainContext *context_event_loop = NULL;
515 // Required for waking up the thread which is running in gmain loop
516 if (NULL != g_eventLoop)
518 context_event_loop = g_main_loop_get_context(g_eventLoop);
520 if (context_event_loop)
522 OIC_LOG_V(DEBUG, TAG, "g_eventLoop context %x", context_event_loop);
523 g_main_context_wakeup(context_event_loop);
525 // Kill g main loops and kill threads.
526 g_main_loop_quit(g_eventLoop);
530 OIC_LOG(ERROR, TAG, "g_eventLoop context is NULL");
533 ca_mutex_unlock(g_LEClientStateMutex);
535 OIC_LOG(DEBUG, TAG, "OUT");
538 CAResult_t CAInitializeLEGattClient()
540 OIC_LOG(DEBUG, TAG, "Initialize GATT Client");
541 CAResult_t res = CAInitGattClientMutexVariables();
542 if (CA_STATUS_OK != res)
544 OIC_LOG(ERROR, TAG, "CAInitGattClientMutexVariables failed!");
545 CATerminateGattClientMutexVariables();
546 return CA_STATUS_FAILED;
551 void CATerminateLEGattClient()
553 OIC_LOG(DEBUG, TAG, "IN");
555 CATerminateGattClientMutexVariables();
557 OIC_LOG(DEBUG, TAG, "OUT");
560 CAResult_t CAInitGattClientMutexVariables()
562 OIC_LOG(DEBUG, TAG, "IN");
563 if (NULL == g_LEClientStateMutex)
565 g_LEClientStateMutex = ca_mutex_new();
566 if (NULL == g_LEClientStateMutex)
568 OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
569 return CA_STATUS_FAILED;
573 if (NULL == g_LEServerListMutex)
575 g_LEServerListMutex = ca_mutex_new();
576 if (NULL == g_LEServerListMutex)
578 OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
579 return CA_STATUS_FAILED;
583 if (NULL == g_LEReqRespClientCbMutex)
585 g_LEReqRespClientCbMutex = ca_mutex_new();
586 if (NULL == g_LEReqRespClientCbMutex)
588 OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
589 return CA_STATUS_FAILED;
593 if (NULL == g_LEClientThreadPoolMutex)
595 g_LEClientThreadPoolMutex = ca_mutex_new();
596 if (NULL == g_LEClientThreadPoolMutex)
598 OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
599 return CA_STATUS_FAILED;
603 if (NULL == g_LEClientConnectMutex)
605 g_LEClientConnectMutex = ca_mutex_new();
606 if (NULL == g_LEClientConnectMutex)
608 OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
609 return CA_STATUS_FAILED;
613 if (NULL == g_multicastDataListMutex)
615 g_multicastDataListMutex = ca_mutex_new();
616 if (NULL == g_multicastDataListMutex)
618 OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
619 return CA_STATUS_FAILED;
623 if (NULL == g_deviceDiscoveredListMutex)
625 g_deviceDiscoveredListMutex = ca_mutex_new();
626 if (NULL == g_deviceDiscoveredListMutex)
628 OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
629 return CA_STATUS_FAILED;
633 if (NULL == g_threadWriteCharacteristicMutex)
635 g_threadWriteCharacteristicMutex = ca_mutex_new();
636 if (NULL == g_threadWriteCharacteristicMutex)
638 OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
639 return CA_STATUS_FAILED;
643 if (NULL == g_startTimerCond)
645 g_startTimerCond = ca_cond_new();
646 if (NULL == g_startTimerCond)
648 OIC_LOG(ERROR, TAG, "ca_cond_new failed");
649 return CA_STATUS_FAILED;
653 if (NULL == g_scanningTimeCond)
655 g_scanningTimeCond = ca_cond_new();
656 if (NULL == g_scanningTimeCond)
658 OIC_LOG(ERROR, TAG, "ca_cond_new failed");
659 return CA_STATUS_FAILED;
663 if (NULL == g_threadWriteCharacteristicCond)
665 g_threadWriteCharacteristicCond = ca_cond_new();
666 if (NULL == g_threadWriteCharacteristicCond)
668 OIC_LOG(ERROR, TAG, "ca_cond_new failed");
669 return CA_STATUS_FAILED;
673 OIC_LOG(DEBUG, TAG, "OUT");
677 void CATerminateGattClientMutexVariables()
679 OIC_LOG(DEBUG, TAG, "IN");
681 ca_mutex_free(g_LEClientStateMutex);
682 g_LEClientStateMutex = NULL;
684 ca_mutex_free(g_LEServerListMutex);
685 g_LEServerListMutex = NULL;
687 ca_mutex_free(g_LEReqRespClientCbMutex);
688 g_LEReqRespClientCbMutex = NULL;
690 ca_mutex_free(g_LEClientConnectMutex);
691 g_LEClientConnectMutex = NULL;
693 ca_mutex_free(g_LEClientThreadPoolMutex);
694 g_LEClientThreadPoolMutex = NULL;
696 ca_mutex_free(g_multicastDataListMutex);
697 g_multicastDataListMutex = NULL;
699 ca_mutex_free(g_deviceDiscoveredListMutex);
700 g_deviceDiscoveredListMutex = NULL;
702 ca_mutex_free(g_threadWriteCharacteristicMutex);
703 g_threadWriteCharacteristicMutex = NULL;
705 ca_cond_free(g_startTimerCond);
706 g_startTimerCond = NULL;
708 ca_cond_free(g_scanningTimeCond);
709 g_scanningTimeCond = NULL;
711 ca_cond_free(g_threadWriteCharacteristicCond);
712 g_threadWriteCharacteristicCond = NULL;
713 g_isSignalSetFlag = false;
715 OIC_LOG(DEBUG, TAG, "OUT");
718 CAResult_t CALEGattSetCallbacks()
720 OIC_LOG(DEBUG, TAG, "IN");
722 OIC_LOG(DEBUG, TAG, "OUT");
726 void CALEGattUnSetCallbacks()
728 OIC_LOG(DEBUG, TAG, "IN");
730 bt_gatt_unset_connection_state_changed_cb();
732 int numOfServersConnected = CAGetRegisteredServiceCount();
733 LEServerInfo *leServerInfo = NULL;
735 for (int32_t index = 0; index < numOfServersConnected; index++)
737 CAGetLEServerInfoByPosition(g_LEServerList, index, &leServerInfo);
738 bt_gatt_client_unset_characteristic_value_changed_cb(leServerInfo->readChar);
740 OIC_LOG(DEBUG, TAG, "OUT");
743 CAResult_t CALEGattStartDeviceScanning()
745 OIC_LOG(DEBUG, TAG, "IN");
747 int ret = bt_adapter_le_start_scan(CALEAdapterScanResultCb, NULL);
748 if(BT_ERROR_NONE != ret)
750 OIC_LOG_V(ERROR, TAG, "bt_adapter_le_start_scan failed[%s]",
751 CALEGetErrorMsg(ret));
752 return CA_STATUS_FAILED;
755 OIC_LOG(DEBUG, TAG, "OUT");
759 void CALEGattStopDeviceScanning()
761 OIC_LOG(DEBUG, TAG, "IN");
763 int ret = bt_adapter_le_stop_scan();
764 if (BT_ERROR_NONE != ret)
766 OIC_LOG_V(ERROR, TAG, "bt_adapter_le_stop_scan failed[%s]",
767 CALEGetErrorMsg(ret));
770 OIC_LOG(DEBUG, TAG, "OUT");
773 void CAGattConnectThread (void *remoteAddress)
775 OIC_LOG(DEBUG, TAG, "IN ");
777 VERIFY_NON_NULL_VOID(remoteAddress, TAG, "remote address is NULL");
779 char *address = (char *)remoteAddress;
781 OIC_LOG_V(DEBUG, TAG, "remote address is [%s]", address);
783 CAResult_t result = CALEGattConnect(address);
785 if (CA_STATUS_OK != result)
787 OIC_LOG_V(ERROR, TAG, "bt_gatt_connect failed for [%s]", address);
792 OIC_LOG(DEBUG, TAG, "OUT");
795 CAResult_t CALEGattConnect(const char *remoteAddress)
797 OIC_LOG(DEBUG, TAG, "IN");
799 VERIFY_NON_NULL_RET(remoteAddress, TAG,
800 "remote address is NULL", CA_STATUS_FAILED);
802 ca_mutex_lock(g_LEClientConnectMutex);
803 bool isConnected = false;
804 int ret = bt_device_is_profile_connected(remoteAddress, BT_PROFILE_GATT, &isConnected);
805 if (BT_ERROR_NONE != ret)
807 OIC_LOG_V(ERROR, TAG, "bt_device_is_profile_connected Failed with ret value [%s] ",
808 CALEGetErrorMsg(ret));
809 ca_mutex_unlock(g_LEClientConnectMutex);
810 return CA_STATUS_FAILED;
813 CAResult_t result = CA_STATUS_OK;
816 ret = bt_gatt_connect(remoteAddress, true);
818 if (BT_ERROR_NONE != ret)
820 OIC_LOG_V(ERROR, TAG, "bt_gatt_connect Failed with ret value [%s] ",
821 CALEGetErrorMsg(ret));
822 ca_mutex_unlock(g_LEClientConnectMutex);
823 return CA_STATUS_FAILED;
828 OIC_LOG_V(INFO, TAG, "Remote address[%s] is already connected",
830 char *addr = OICStrdup(remoteAddress);
833 OIC_LOG(ERROR, TAG, "addr is NULL");
834 ca_mutex_unlock(g_LEClientConnectMutex);
835 return CA_STATUS_FAILED;
838 ca_mutex_lock(g_LEClientThreadPoolMutex);
839 if (NULL == g_LEClientThreadPool)
841 OIC_LOG(ERROR, TAG, "g_LEClientThreadPool is NULL");
843 ca_mutex_unlock(g_LEClientThreadPoolMutex);
844 ca_mutex_unlock(g_LEClientConnectMutex);
845 return CA_STATUS_FAILED;
848 result = ca_thread_pool_add_task(g_LEClientThreadPool, CADiscoverLEServicesThread,
850 if (CA_STATUS_OK != result)
852 OIC_LOG_V(ERROR, TAG, "ca_thread_pool_add_task failed with ret [%d]", result);
855 ca_mutex_unlock(g_LEClientThreadPoolMutex);
857 ca_mutex_unlock(g_LEClientConnectMutex);
859 OIC_LOG(DEBUG, TAG, "OUT");
863 CAResult_t CALEGattDisConnect(const char *remoteAddress)
865 OIC_LOG(DEBUG, TAG, "IN");
867 VERIFY_NON_NULL_RET(remoteAddress, TAG,
868 "remote address is NULL", CA_STATUS_FAILED);
870 int ret = bt_gatt_disconnect(remoteAddress);
872 if (BT_ERROR_NONE != ret)
874 OIC_LOG_V(ERROR, TAG, "bt_gatt_disconnect Failed with ret value [%d] ",
875 CALEGetErrorMsg(ret));
876 return CA_STATUS_FAILED;
879 OIC_LOG(DEBUG, TAG, "OUT");
883 void CADiscoverLEServicesThread (void *remoteAddress)
885 OIC_LOG(DEBUG, TAG, "IN");
887 VERIFY_NON_NULL_VOID(remoteAddress, TAG, "remote address is NULL");
889 char *address = (char *)remoteAddress;
891 CAResult_t result = CALEGattDiscoverServices(address);
892 if (CA_STATUS_OK != result)
894 OIC_LOG(ERROR, TAG, "CALEGattDiscoverServices failed");
898 OIC_LOG(DEBUG, TAG, "OUT");
901 CAResult_t CALEGattDiscoverServices(const char *remoteAddress)
903 OIC_LOG(DEBUG, TAG, "IN");
905 VERIFY_NON_NULL_RET(remoteAddress, TAG,
906 "remote address is NULL", CA_STATUS_FAILED);
908 bt_gatt_client_h clientHandle = NULL;
909 int32_t ret = bt_gatt_client_create(remoteAddress, &clientHandle);
910 if (BT_ERROR_NONE != ret || NULL == clientHandle)
912 OIC_LOG_V(ERROR, TAG,
913 "bt_gatt_client_create Failed with ret value [%s] ", CALEGetErrorMsg(ret));
914 CALEGattDisConnect(remoteAddress);
915 return CA_STATUS_FAILED;
918 bt_gatt_h serviceHandle = NULL;
919 ret = bt_gatt_client_get_service(clientHandle, CA_GATT_SERVICE_UUID, &serviceHandle);
920 if (BT_ERROR_NONE != ret || NULL == serviceHandle)
922 OIC_LOG_V(ERROR, TAG,
923 "bt_gatt_client_get_service Failed with ret value [%s] ", CALEGetErrorMsg(ret));
924 bt_gatt_client_destroy(clientHandle);
925 CALEGattDisConnect(remoteAddress);
926 return CA_STATUS_FAILED;
929 // Server will read data on this characteristic.
930 bt_gatt_h writeChrHandle = NULL;
931 ret = bt_gatt_service_get_characteristic(serviceHandle, CA_GATT_REQUEST_CHRC_UUID,
933 if (BT_ERROR_NONE != ret || NULL == writeChrHandle)
935 OIC_LOG_V(ERROR, TAG,
936 "bt_gatt_service_get_characteristic Failed with ret value [%s] ",
937 CALEGetErrorMsg(ret));
938 bt_gatt_client_destroy(clientHandle);
939 CALEGattDisConnect(remoteAddress);
940 return CA_STATUS_FAILED;
943 // Server will notify data on this characteristic.
944 bt_gatt_h readChrHandle = NULL;
945 ret = bt_gatt_service_get_characteristic(serviceHandle, CA_GATT_RESPONSE_CHRC_UUID,
947 if (BT_ERROR_NONE != ret || NULL == readChrHandle)
949 OIC_LOG_V(ERROR, TAG,
950 "bt_gatt_service_get_characteristic Failed with ret value [%s] ",
951 CALEGetErrorMsg(ret));
952 bt_gatt_client_destroy(clientHandle);
953 CALEGattDisConnect(remoteAddress);
954 return CA_STATUS_FAILED;
958 //TODO: This data has to be freed while unsetting the callback.
959 char *addr = OICStrdup(remoteAddress);
960 ret = bt_gatt_client_set_characteristic_value_changed_cb(readChrHandle,
961 CALEGattCharacteristicChangedCb,
963 if (BT_ERROR_NONE != ret)
965 OIC_LOG_V(ERROR, TAG,
966 "bt_gatt_client_set_characteristic_value_changed_cb Failed with ret value [%s]",
967 CALEGetErrorMsg(ret));
968 bt_gatt_client_destroy(clientHandle);
969 CALEGattDisConnect(remoteAddress);
970 return CA_STATUS_FAILED;
973 LEServerInfo *serverInfo = (LEServerInfo *)OICCalloc(1, sizeof(LEServerInfo));
974 if (NULL == serverInfo)
976 OIC_LOG(ERROR, TAG, "Malloc failed");
977 CALEGattDisConnect(remoteAddress);
978 return CA_MEMORY_ALLOC_FAILED;
980 serverInfo->clientHandle = clientHandle;
981 serverInfo->serviceHandle = serviceHandle;
982 serverInfo->readChar = readChrHandle;
983 serverInfo->writeChar = writeChrHandle;
984 serverInfo->remoteAddress = OICStrdup(remoteAddress);
986 ca_mutex_lock(g_LEServerListMutex);
987 CAResult_t result = CAAddLEServerInfoToList(&g_LEServerList, serverInfo);
988 if (CA_STATUS_OK != result)
990 OIC_LOG(ERROR, TAG, "CAAddLEServerInfoToList failed");
991 bt_gatt_client_destroy(clientHandle);
992 CALEGattDisConnect(remoteAddress);
993 return CA_STATUS_FAILED;
995 ca_mutex_unlock(g_LEServerListMutex);
997 // Send the data of pending multicast data list if any.
998 if (g_multicastDataList)
1000 ca_mutex_lock(g_multicastDataListMutex);
1001 uint32_t arrayLength = u_arraylist_length(g_multicastDataList);
1002 for (int i = 0; i < arrayLength; i++)
1004 CALEData_t *multicastData = u_arraylist_get(g_multicastDataList, i);
1005 if (NULL == multicastData)
1007 OIC_LOG(DEBUG, TAG, "multicastData is NULL");
1010 CAUpdateCharacteristicsToGattServer(remoteAddress, multicastData->data,
1011 multicastData->dataLen, LE_UNICAST, 0);
1013 ca_mutex_unlock(g_multicastDataListMutex);
1016 OIC_LOG(DEBUG, TAG, "OUT");
1017 return CA_STATUS_OK;
1020 CAResult_t CAUpdateCharacteristicsToGattServer(const char *remoteAddress,
1021 const uint8_t *data, const uint32_t dataLen,
1022 CALETransferType_t type, const int32_t position)
1024 OIC_LOG(DEBUG, TAG, "IN");
1026 VERIFY_NON_NULL(data, TAG, "data is NULL");
1030 OIC_LOG(ERROR, TAG, "dataLen is less than or equal zero. Invalid input!");
1031 return CA_STATUS_INVALID_PARAM;
1034 LEServerInfo *leServerInfo = NULL;
1035 CAResult_t ret = CA_STATUS_FAILED;
1037 ca_mutex_lock(g_LEServerListMutex);
1038 if (LE_UNICAST == type)
1040 ret = CAGetLEServerInfo(g_LEServerList, remoteAddress, &leServerInfo);
1042 else if (LE_MULTICAST == type)
1044 ret = CAGetLEServerInfoByPosition(g_LEServerList, position, &leServerInfo);
1046 ca_mutex_unlock(g_LEServerListMutex);
1048 if (CA_STATUS_OK != ret)
1050 OIC_LOG(ERROR, TAG, "CAGetBLEServiceInfoByPosition is failed");
1051 return CA_STATUS_FAILED;
1054 VERIFY_NON_NULL(leServerInfo, TAG, "bleServiceInfo is NULL");
1056 OIC_LOG_V(DEBUG, TAG, "Updating the data of length [%d] to [%s] ", dataLen,
1057 leServerInfo->remoteAddress);
1059 int result = bt_gatt_set_value(leServerInfo->writeChar, (char *)data, dataLen);
1061 if (BT_ERROR_NONE != result)
1063 OIC_LOG_V(ERROR, TAG,
1064 "bt_gatt_set_value Failed with return val [%s]",
1065 CALEGetErrorMsg(result));
1066 return CA_STATUS_FAILED;
1069 result = bt_gatt_client_write_value(leServerInfo->writeChar, CALEGattCharacteristicWriteCb,
1071 if (BT_ERROR_NONE != result)
1073 OIC_LOG_V(ERROR, TAG,
1074 "bt_gatt_client_write_value Failed with return val [%s]",
1075 CALEGetErrorMsg(result));
1076 return CA_STATUS_FAILED;
1079 // wait for callback for write Characteristic with success to sent data
1080 OIC_LOG_V(DEBUG, TAG, "callback flag is %d", g_isSignalSetFlag);
1081 ca_mutex_lock(g_threadWriteCharacteristicMutex);
1082 if (!g_isSignalSetFlag)
1084 OIC_LOG(DEBUG, TAG, "wait for callback to notify writeCharacteristic is success");
1085 if (CA_WAIT_SUCCESS != ca_cond_wait_for(g_threadWriteCharacteristicCond,
1086 g_threadWriteCharacteristicMutex,
1087 WAIT_TIME_WRITE_CHARACTERISTIC))
1089 OIC_LOG(ERROR, TAG, "there is no response. write has failed");
1090 g_isSignalSetFlag = false;
1091 ca_mutex_unlock(g_threadWriteCharacteristicMutex);
1092 return CA_SEND_FAILED;
1095 // reset flag set by writeCharacteristic Callback
1096 g_isSignalSetFlag = false;
1097 ca_mutex_unlock(g_threadWriteCharacteristicMutex);
1099 OIC_LOG(DEBUG, TAG, "OUT");
1100 return CA_STATUS_OK;
1103 CAResult_t CAUpdateCharacteristicsToAllGattServers(const uint8_t *data, uint32_t dataLen)
1105 OIC_LOG(DEBUG, TAG, "IN");
1107 VERIFY_NON_NULL(data, TAG, "data is NULL");
1111 OIC_LOG(ERROR, TAG, "dataLen is less than or equal zero. Invalid input !");
1112 return CA_STATUS_INVALID_PARAM;
1115 int numOfServersConnected = CAGetRegisteredServiceCount();
1117 // Send data to already connected devices.
1118 for (int32_t pos = 0; pos < numOfServersConnected; pos++)
1120 /*remoteAddress will be NULL.
1121 Since we have to send to all destinations. pos will be used for getting remote address.
1123 int32_t ret = CAUpdateCharacteristicsToGattServer(NULL, data, dataLen, LE_MULTICAST, pos);
1125 if (CA_STATUS_OK != ret)
1127 OIC_LOG_V(ERROR, TAG,
1128 "CAUpdateCharacteristicsToGattServer Failed with return val [%d] ", ret);
1129 g_clientErrorCallback(NULL, data, dataLen, ret);
1133 // Add the data to pending list.
1134 CALEData_t *multicastData = (CALEData_t *)OICCalloc(1, sizeof(CALEData_t));
1135 if (NULL == multicastData)
1137 OIC_LOG(ERROR, TAG, "Calloc failed");
1140 multicastData->data = OICCalloc(1, dataLen);
1141 if (NULL == multicastData->data)
1143 OIC_LOG(ERROR, TAG, "Calloc failed");
1146 memcpy(multicastData->data, data, dataLen);
1147 multicastData->dataLen = dataLen;
1149 ca_mutex_lock(g_multicastDataListMutex);
1150 if (NULL == g_multicastDataList)
1152 g_multicastDataList = u_arraylist_create();
1154 u_arraylist_add(g_multicastDataList, (void *)multicastData);
1155 ca_mutex_unlock(g_multicastDataListMutex);
1157 // Start the scanning.
1158 CAResult_t result = CALEGattStartDeviceScanning();
1159 if (CA_STATUS_OK != result)
1161 OIC_LOG(ERROR, TAG, "CALEGattStartDeviceDiscovery Failed");
1165 // Start the timer by signalling it.
1166 ca_cond_signal(g_startTimerCond);
1169 OIC_LOG(DEBUG, TAG, "OUT ");
1170 return CA_STATUS_OK;