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);
253 OIC_LOG_V(DEBUG, TAG, "Connected to [%s] ", remoteAddress);
255 char *addr = OICStrdup(remoteAddress);
257 ca_mutex_lock(g_LEClientThreadPoolMutex);
258 if (NULL == g_LEClientThreadPool)
260 OIC_LOG(ERROR, TAG, "g_LEClientThreadPool is NULL");
262 ca_mutex_unlock(g_LEClientThreadPoolMutex);
266 ret = ca_thread_pool_add_task(g_LEClientThreadPool, CADiscoverLEServicesThread,
268 if (CA_STATUS_OK != ret)
270 OIC_LOG_V(ERROR, TAG, "ca_thread_pool_add_task failed with ret [%d]", ret);
273 ca_mutex_unlock(g_LEClientThreadPoolMutex);
275 OIC_LOG(DEBUG, TAG, "OUT");
278 void CALEAdapterScanResultCb(int result, bt_adapter_le_device_scan_result_info_s *scanInfo,
281 OIC_LOG(DEBUG, TAG, "IN");
283 VERIFY_NON_NULL_VOID(scanInfo, TAG, "scanInfo");
284 VERIFY_NON_NULL_VOID(scanInfo->remote_address, TAG, "scanInfo->remote_address");
286 OIC_LOG_V(DEBUG, TAG, "Remote Address [%s]", scanInfo->remote_address);
287 OIC_LOG_V(DEBUG, TAG, "Scan Result [%d]", result);
288 OIC_LOG_V(DEBUG, TAG,
289 " Adv data len [%d] Scan data len[%d]RSSI [%d] Addr_type [%d] ",
290 scanInfo->adv_data_len, scanInfo->scan_data_len, scanInfo->rssi,
291 scanInfo->address_type);
293 // Check if device is already discovered.
294 if (CALEIsDeviceDiscovered(scanInfo->remote_address))
296 OIC_LOG_V(INFO, TAG, "Device[%s] is already discovered", scanInfo->remote_address);
300 // Stop the scan before invoking bt_gatt_connect().
301 CALEGattStopDeviceScanning();
303 ca_mutex_lock(g_deviceDiscoveredListMutex);
304 // Add the the device Discovered list.
305 if (NULL == g_deviceDiscoveredList)
307 g_deviceDiscoveredList = u_arraylist_create();
309 char *deviceAddr = OICStrdup(scanInfo->remote_address);
310 u_arraylist_add(g_deviceDiscoveredList, (void *) deviceAddr);
311 ca_mutex_unlock(g_deviceDiscoveredListMutex);
313 size_t len = strlen(scanInfo->remote_address);
315 char *addr = (char *)OICMalloc(sizeof(char) * (len + 1));
316 VERIFY_NON_NULL_VOID(addr, TAG, "Malloc failed");
318 strncpy(addr, scanInfo->remote_address, len + 1);
320 OIC_LOG_V(DEBUG, TAG,
321 "Trying to do Gatt connection to [%s]", addr);
323 ca_mutex_lock(g_LEClientThreadPoolMutex);
324 if (NULL == g_LEClientThreadPool)
326 OIC_LOG(ERROR, TAG, "g_LEClientThreadPool is NULL");
328 ca_mutex_unlock(g_LEClientThreadPoolMutex);
332 CAResult_t res = ca_thread_pool_add_task(g_LEClientThreadPool, CAGattConnectThread, addr);
333 if (CA_STATUS_OK != res)
335 OIC_LOG_V(ERROR, TAG,
336 "ca_thread_pool_add_task failed with ret [%d]", res);
339 ca_mutex_unlock(g_LEClientThreadPoolMutex);
340 OIC_LOG(DEBUG, TAG, "OUT");
343 void CASetLEClientThreadPoolHandle(ca_thread_pool_t handle)
345 OIC_LOG(DEBUG, TAG, "IN");
347 ca_mutex_lock(g_LEClientThreadPoolMutex);
348 g_LEClientThreadPool = handle;
349 ca_mutex_unlock(g_LEClientThreadPoolMutex);
351 OIC_LOG(DEBUG, TAG, "OUT");
354 void CASetLEReqRespClientCallback(CABLEDataReceivedCallback callback)
356 OIC_LOG(DEBUG, TAG, "IN");
358 ca_mutex_lock(g_LEReqRespClientCbMutex);
360 g_LEClientDataReceivedCallback = callback;
362 ca_mutex_unlock(g_LEReqRespClientCbMutex);
364 OIC_LOG(DEBUG, TAG, "OUT");
367 void CASetBLEClientErrorHandleCallback(CABLEErrorHandleCallback callback)
369 g_clientErrorCallback = callback;
372 CAResult_t CAStartLEGattClient()
374 OIC_LOG(DEBUG, TAG, "IN");
376 ca_mutex_lock(g_LEClientThreadPoolMutex);
377 if (NULL == g_LEClientThreadPool)
379 OIC_LOG(ERROR, TAG, "gBleServerThreadPool is NULL");
380 CATerminateGattClientMutexVariables();
381 ca_mutex_unlock(g_LEClientThreadPoolMutex);
382 return CA_STATUS_FAILED;
385 CAResult_t result = ca_thread_pool_add_task(g_LEClientThreadPool, CAStartLEGattClientThread,
387 if (CA_STATUS_OK != result)
389 OIC_LOG(ERROR, TAG, "ca_thread_pool_add_task failed");
390 CATerminateGattClientMutexVariables();
391 ca_mutex_unlock(g_LEClientThreadPoolMutex);
392 return CA_STATUS_FAILED;
394 ca_mutex_unlock(g_LEClientThreadPoolMutex);
396 OIC_LOG(DEBUG, TAG, "OUT");
400 void CAStartLEGattClientThread(void *data)
402 OIC_LOG(DEBUG, TAG, "IN");
404 ca_mutex_lock(g_LEClientStateMutex);
405 if (true == g_isLEGattClientStarted)
407 OIC_LOG(ERROR, TAG, "Gatt Client is already running!!");
408 ca_mutex_unlock(g_LEClientStateMutex);
412 CAResult_t result = CALEGattSetCallbacks();
413 if (CA_STATUS_OK != result)
415 OIC_LOG(ERROR, TAG, "CABleGattSetCallbacks Failed");
416 ca_mutex_unlock(g_LEClientStateMutex);
417 CATerminateLEGattClient();
421 g_isLEGattClientStarted = true;
422 ca_mutex_unlock(g_LEClientStateMutex);
424 ca_mutex_lock(g_LEClientThreadPoolMutex);
425 if (NULL == g_LEClientThreadPool)
427 OIC_LOG(ERROR, TAG, "gBleServerThreadPool is NULL");
428 CATerminateGattClientMutexVariables();
429 ca_mutex_unlock(g_LEClientThreadPoolMutex);
433 result = ca_thread_pool_add_task(g_LEClientThreadPool, CAStartTimerThread,
435 if (CA_STATUS_OK != result)
437 OIC_LOG(ERROR, TAG, "ca_thread_pool_add_task failed");
438 ca_mutex_unlock(g_LEClientThreadPoolMutex);
441 ca_mutex_unlock(g_LEClientThreadPoolMutex);
443 OIC_LOG(DEBUG, TAG, "Giving the control to threadPool");
445 GMainContext *thread_context = g_main_context_new();
447 g_eventLoop = g_main_loop_new(thread_context, FALSE);
449 g_main_context_push_thread_default(thread_context);
451 g_main_loop_run(g_eventLoop);
453 OIC_LOG(DEBUG, TAG, "OUT");
456 void CAStartTimerThread(void *data)
458 OIC_LOG(DEBUG, TAG, "IN");
459 while (g_isLEGattClientStarted)
461 ca_mutex_lock(g_multicastDataListMutex);
462 if (!g_isMulticastInProgress)
464 OIC_LOG(DEBUG, TAG, "waiting....");
465 ca_cond_wait(g_startTimerCond, g_multicastDataListMutex);
466 OIC_LOG(DEBUG, TAG, "Wake up");
467 g_isMulticastInProgress = true;
470 // Timed conditional wait for stopping the scan.
471 CAWaitResult_t ret = ca_cond_wait_for(g_scanningTimeCond, g_multicastDataListMutex,
473 if (CA_WAIT_TIMEDOUT == ret)
475 OIC_LOG(DEBUG, TAG, "Scan is timed Out");
477 CALEGattStopDeviceScanning();
479 // Clear the data list and device list.
480 u_arraylist_destroy(g_multicastDataList);
481 g_multicastDataList = NULL;
483 ca_mutex_lock(g_deviceDiscoveredListMutex);
484 u_arraylist_destroy(g_deviceDiscoveredList);
485 g_deviceDiscoveredList = NULL;
486 ca_mutex_unlock(g_deviceDiscoveredListMutex);
488 g_isMulticastInProgress = false;
490 ca_mutex_unlock(g_multicastDataListMutex);
493 OIC_LOG(DEBUG, TAG, "OUT");
496 void CAStopLEGattClient()
498 OIC_LOG(DEBUG, TAG, "IN");
500 ca_mutex_lock(g_LEClientStateMutex);
502 if (false == g_isLEGattClientStarted)
504 OIC_LOG(ERROR, TAG, "Gatt Client is not running to stop");
505 ca_mutex_unlock(g_LEClientStateMutex);
509 CALEGattUnSetCallbacks();
511 CALEGattStopDeviceScanning();
513 g_isLEGattClientStarted = false;
515 // Signal the conditions waiting in Start timer.
516 ca_cond_signal(g_startTimerCond);
517 ca_cond_signal(g_scanningTimeCond);
519 // Destroy the multicast data list and device list if not empty.
520 if (NULL != g_multicastDataList)
522 ca_mutex_lock(g_multicastDataListMutex);
523 u_arraylist_destroy(g_multicastDataList);
524 g_multicastDataList = NULL;
525 ca_mutex_unlock(g_multicastDataListMutex);
528 if (NULL != g_deviceDiscoveredList)
530 ca_mutex_lock(g_deviceDiscoveredListMutex);
531 u_arraylist_destroy(g_deviceDiscoveredList);
532 g_deviceDiscoveredList = NULL;
533 ca_mutex_unlock(g_deviceDiscoveredListMutex);
536 ca_mutex_lock(g_LEServerListMutex);
537 CAFreeLEServerList(g_LEServerList);
538 g_LEServerList = NULL;
539 ca_mutex_unlock(g_LEServerListMutex);
541 ca_mutex_lock(g_threadWriteCharacteristicMutex);
542 ca_cond_signal(g_threadWriteCharacteristicCond);
543 ca_mutex_unlock(g_threadWriteCharacteristicMutex);
545 CAResetRegisteredServiceCount();
547 GMainContext *context_event_loop = NULL;
548 // Required for waking up the thread which is running in gmain loop
549 if (NULL != g_eventLoop)
551 context_event_loop = g_main_loop_get_context(g_eventLoop);
553 if (context_event_loop)
555 OIC_LOG_V(DEBUG, TAG, "g_eventLoop context %x", context_event_loop);
556 g_main_context_wakeup(context_event_loop);
558 // Kill g main loops and kill threads.
559 g_main_loop_quit(g_eventLoop);
563 OIC_LOG(ERROR, TAG, "g_eventLoop context is NULL");
566 ca_mutex_unlock(g_LEClientStateMutex);
568 OIC_LOG(DEBUG, TAG, "OUT");
571 CAResult_t CAInitializeLEGattClient()
573 OIC_LOG(DEBUG, TAG, "Initialize GATT Client");
574 CAResult_t res = CAInitGattClientMutexVariables();
575 if (CA_STATUS_OK != res)
577 OIC_LOG(ERROR, TAG, "CAInitGattClientMutexVariables failed!");
578 CATerminateGattClientMutexVariables();
579 return CA_STATUS_FAILED;
584 void CATerminateLEGattClient()
586 OIC_LOG(DEBUG, TAG, "IN");
588 CATerminateGattClientMutexVariables();
590 OIC_LOG(DEBUG, TAG, "OUT");
593 CAResult_t CAInitGattClientMutexVariables()
595 OIC_LOG(DEBUG, TAG, "IN");
596 if (NULL == g_LEClientStateMutex)
598 g_LEClientStateMutex = ca_mutex_new();
599 if (NULL == g_LEClientStateMutex)
601 OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
602 return CA_STATUS_FAILED;
606 if (NULL == g_LEServerListMutex)
608 g_LEServerListMutex = ca_mutex_new();
609 if (NULL == g_LEServerListMutex)
611 OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
612 return CA_STATUS_FAILED;
616 if (NULL == g_LEReqRespClientCbMutex)
618 g_LEReqRespClientCbMutex = ca_mutex_new();
619 if (NULL == g_LEReqRespClientCbMutex)
621 OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
622 return CA_STATUS_FAILED;
626 if (NULL == g_LEClientThreadPoolMutex)
628 g_LEClientThreadPoolMutex = ca_mutex_new();
629 if (NULL == g_LEClientThreadPoolMutex)
631 OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
632 return CA_STATUS_FAILED;
636 if (NULL == g_LEClientConnectMutex)
638 g_LEClientConnectMutex = ca_mutex_new();
639 if (NULL == g_LEClientConnectMutex)
641 OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
642 return CA_STATUS_FAILED;
646 if (NULL == g_multicastDataListMutex)
648 g_multicastDataListMutex = ca_mutex_new();
649 if (NULL == g_multicastDataListMutex)
651 OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
652 return CA_STATUS_FAILED;
656 if (NULL == g_deviceDiscoveredListMutex)
658 g_deviceDiscoveredListMutex = ca_mutex_new();
659 if (NULL == g_deviceDiscoveredListMutex)
661 OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
662 return CA_STATUS_FAILED;
666 if (NULL == g_threadWriteCharacteristicMutex)
668 g_threadWriteCharacteristicMutex = ca_mutex_new();
669 if (NULL == g_threadWriteCharacteristicMutex)
671 OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
672 return CA_STATUS_FAILED;
676 if (NULL == g_startTimerCond)
678 g_startTimerCond = ca_cond_new();
679 if (NULL == g_startTimerCond)
681 OIC_LOG(ERROR, TAG, "ca_cond_new failed");
682 return CA_STATUS_FAILED;
686 if (NULL == g_scanningTimeCond)
688 g_scanningTimeCond = ca_cond_new();
689 if (NULL == g_scanningTimeCond)
691 OIC_LOG(ERROR, TAG, "ca_cond_new failed");
692 return CA_STATUS_FAILED;
696 if (NULL == g_threadWriteCharacteristicCond)
698 g_threadWriteCharacteristicCond = ca_cond_new();
699 if (NULL == g_threadWriteCharacteristicCond)
701 OIC_LOG(ERROR, TAG, "ca_cond_new failed");
702 return CA_STATUS_FAILED;
706 OIC_LOG(DEBUG, TAG, "OUT");
710 void CATerminateGattClientMutexVariables()
712 OIC_LOG(DEBUG, TAG, "IN");
714 ca_mutex_free(g_LEClientStateMutex);
715 g_LEClientStateMutex = NULL;
717 ca_mutex_free(g_LEServerListMutex);
718 g_LEServerListMutex = NULL;
720 ca_mutex_free(g_LEReqRespClientCbMutex);
721 g_LEReqRespClientCbMutex = NULL;
723 ca_mutex_free(g_LEClientConnectMutex);
724 g_LEClientConnectMutex = NULL;
726 ca_mutex_free(g_LEClientThreadPoolMutex);
727 g_LEClientThreadPoolMutex = NULL;
729 ca_mutex_free(g_multicastDataListMutex);
730 g_multicastDataListMutex = NULL;
732 ca_mutex_free(g_deviceDiscoveredListMutex);
733 g_deviceDiscoveredListMutex = NULL;
735 ca_mutex_free(g_threadWriteCharacteristicMutex);
736 g_threadWriteCharacteristicMutex = NULL;
738 ca_cond_free(g_startTimerCond);
739 g_startTimerCond = NULL;
741 ca_cond_free(g_scanningTimeCond);
742 g_scanningTimeCond = NULL;
744 ca_cond_free(g_threadWriteCharacteristicCond);
745 g_threadWriteCharacteristicCond = NULL;
746 g_isSignalSetFlag = false;
748 OIC_LOG(DEBUG, TAG, "OUT");
751 CAResult_t CALEGattSetCallbacks()
753 OIC_LOG(DEBUG, TAG, "IN");
755 OIC_LOG(DEBUG, TAG, "OUT");
759 void CALEGattUnSetCallbacks()
761 OIC_LOG(DEBUG, TAG, "IN");
763 bt_gatt_unset_connection_state_changed_cb();
765 int numOfServersConnected = CAGetRegisteredServiceCount();
766 LEServerInfo *leServerInfo = NULL;
768 for (int32_t index = 0; index < numOfServersConnected; index++)
770 CAGetLEServerInfoByPosition(g_LEServerList, index, &leServerInfo);
771 bt_gatt_client_unset_characteristic_value_changed_cb(leServerInfo->readChar);
773 OIC_LOG(DEBUG, TAG, "OUT");
776 CAResult_t CALEGattStartDeviceScanning()
778 OIC_LOG(DEBUG, TAG, "IN");
780 int ret = bt_adapter_le_start_scan(CALEAdapterScanResultCb, NULL);
781 if(BT_ERROR_NONE != ret)
783 OIC_LOG_V(ERROR, TAG, "bt_adapter_le_start_scan failed[%s]",
784 CALEGetErrorMsg(ret));
785 return CA_STATUS_FAILED;
788 OIC_LOG(DEBUG, TAG, "OUT");
792 void CALEGattStopDeviceScanning()
794 OIC_LOG(DEBUG, TAG, "IN");
796 int ret = bt_adapter_le_stop_scan();
797 if (BT_ERROR_NONE != ret)
799 OIC_LOG_V(ERROR, TAG, "bt_adapter_le_stop_scan failed[%s]",
800 CALEGetErrorMsg(ret));
803 OIC_LOG(DEBUG, TAG, "OUT");
806 void CAGattConnectThread (void *remoteAddress)
808 OIC_LOG(DEBUG, TAG, "IN ");
810 VERIFY_NON_NULL_VOID(remoteAddress, TAG, "remote address is NULL");
812 char *address = (char *)remoteAddress;
814 OIC_LOG_V(DEBUG, TAG, "remote address is [%s]", address);
816 CAResult_t result = CALEGattConnect(address);
818 if (CA_STATUS_OK != result)
820 OIC_LOG_V(ERROR, TAG, "bt_gatt_connect failed for [%s]", address);
825 OIC_LOG(DEBUG, TAG, "OUT");
828 CAResult_t CALEGattConnect(const char *remoteAddress)
830 OIC_LOG(DEBUG, TAG, "IN");
832 VERIFY_NON_NULL_RET(remoteAddress, TAG,
833 "remote address is NULL", CA_STATUS_FAILED);
835 ca_mutex_lock(g_LEClientConnectMutex);
836 bool isConnected = false;
837 int ret = bt_device_is_profile_connected(remoteAddress, BT_PROFILE_GATT, &isConnected);
838 if (BT_ERROR_NONE != ret)
840 OIC_LOG_V(ERROR, TAG, "bt_device_is_profile_connected Failed with ret value [%s] ",
841 CALEGetErrorMsg(ret));
842 ca_mutex_unlock(g_LEClientConnectMutex);
843 return CA_STATUS_FAILED;
846 CAResult_t result = CA_STATUS_OK;
849 ret = bt_gatt_connect(remoteAddress, true);
851 if (BT_ERROR_NONE != ret)
853 OIC_LOG_V(ERROR, TAG, "bt_gatt_connect Failed with ret value [%s] ",
854 CALEGetErrorMsg(ret));
855 ca_mutex_unlock(g_LEClientConnectMutex);
856 return CA_STATUS_FAILED;
861 OIC_LOG_V(INFO, TAG, "Remote address[%s] is already connected",
863 char *addr = OICStrdup(remoteAddress);
866 OIC_LOG(ERROR, TAG, "addr is NULL");
867 ca_mutex_unlock(g_LEClientConnectMutex);
868 return CA_STATUS_FAILED;
871 ca_mutex_lock(g_LEClientThreadPoolMutex);
872 if (NULL == g_LEClientThreadPool)
874 OIC_LOG(ERROR, TAG, "g_LEClientThreadPool is NULL");
876 ca_mutex_unlock(g_LEClientThreadPoolMutex);
877 ca_mutex_unlock(g_LEClientConnectMutex);
878 return CA_STATUS_FAILED;
881 result = ca_thread_pool_add_task(g_LEClientThreadPool, CADiscoverLEServicesThread,
883 if (CA_STATUS_OK != result)
885 OIC_LOG_V(ERROR, TAG, "ca_thread_pool_add_task failed with ret [%d]", result);
888 ca_mutex_unlock(g_LEClientThreadPoolMutex);
890 ca_mutex_unlock(g_LEClientConnectMutex);
892 OIC_LOG(DEBUG, TAG, "OUT");
896 CAResult_t CALEGattDisConnect(const char *remoteAddress)
898 OIC_LOG(DEBUG, TAG, "IN");
900 VERIFY_NON_NULL_RET(remoteAddress, TAG,
901 "remote address is NULL", CA_STATUS_FAILED);
903 int ret = bt_gatt_disconnect(remoteAddress);
905 if (BT_ERROR_NONE != ret)
907 OIC_LOG_V(ERROR, TAG, "bt_gatt_disconnect Failed with ret value [%d] ",
908 CALEGetErrorMsg(ret));
909 return CA_STATUS_FAILED;
912 OIC_LOG(DEBUG, TAG, "OUT");
916 void CADiscoverLEServicesThread (void *remoteAddress)
918 OIC_LOG(DEBUG, TAG, "IN");
920 VERIFY_NON_NULL_VOID(remoteAddress, TAG, "remote address is NULL");
922 char *address = (char *)remoteAddress;
924 CAResult_t result = CALEGattDiscoverServices(address);
925 if (CA_STATUS_OK != result)
927 OIC_LOG(ERROR, TAG, "CALEGattDiscoverServices failed");
931 OIC_LOG(DEBUG, TAG, "OUT");
934 CAResult_t CALEGattDiscoverServices(const char *remoteAddress)
936 OIC_LOG(DEBUG, TAG, "IN");
938 VERIFY_NON_NULL_RET(remoteAddress, TAG,
939 "remote address is NULL", CA_STATUS_FAILED);
941 bt_gatt_client_h clientHandle = NULL;
942 int32_t ret = bt_gatt_client_create(remoteAddress, &clientHandle);
943 if (BT_ERROR_NONE != ret || NULL == clientHandle)
945 OIC_LOG_V(ERROR, TAG,
946 "bt_gatt_client_create Failed with ret value [%s] ", CALEGetErrorMsg(ret));
947 CALEGattDisConnect(remoteAddress);
948 return CA_STATUS_FAILED;
951 bt_gatt_h serviceHandle = NULL;
952 ret = bt_gatt_client_get_service(clientHandle, CA_GATT_SERVICE_UUID, &serviceHandle);
953 if (BT_ERROR_NONE != ret || NULL == serviceHandle)
955 OIC_LOG_V(ERROR, TAG,
956 "bt_gatt_client_get_service Failed with ret value [%s] ", CALEGetErrorMsg(ret));
957 bt_gatt_client_destroy(clientHandle);
958 CALEGattDisConnect(remoteAddress);
959 return CA_STATUS_FAILED;
962 // Server will read data on this characteristic.
963 bt_gatt_h writeChrHandle = NULL;
964 ret = bt_gatt_service_get_characteristic(serviceHandle, CA_GATT_REQUEST_CHRC_UUID,
966 if (BT_ERROR_NONE != ret || NULL == writeChrHandle)
968 OIC_LOG_V(ERROR, TAG,
969 "bt_gatt_service_get_characteristic Failed with ret value [%s] ",
970 CALEGetErrorMsg(ret));
971 bt_gatt_client_destroy(clientHandle);
972 CALEGattDisConnect(remoteAddress);
973 return CA_STATUS_FAILED;
976 // Server will notify data on this characteristic.
977 bt_gatt_h readChrHandle = NULL;
978 ret = bt_gatt_service_get_characteristic(serviceHandle, CA_GATT_RESPONSE_CHRC_UUID,
980 if (BT_ERROR_NONE != ret || NULL == readChrHandle)
982 OIC_LOG_V(ERROR, TAG,
983 "bt_gatt_service_get_characteristic Failed with ret value [%s] ",
984 CALEGetErrorMsg(ret));
985 bt_gatt_client_destroy(clientHandle);
986 CALEGattDisConnect(remoteAddress);
987 return CA_STATUS_FAILED;
991 //TODO: This data has to be freed while unsetting the callback.
992 char *addr = OICStrdup(remoteAddress);
993 ret = bt_gatt_client_set_characteristic_value_changed_cb(readChrHandle,
994 CALEGattCharacteristicChangedCb,
996 if (BT_ERROR_NONE != ret)
998 OIC_LOG_V(ERROR, TAG,
999 "bt_gatt_client_set_characteristic_value_changed_cb Failed with ret value [%s]",
1000 CALEGetErrorMsg(ret));
1001 bt_gatt_client_destroy(clientHandle);
1002 CALEGattDisConnect(remoteAddress);
1003 return CA_STATUS_FAILED;
1006 LEServerInfo *serverInfo = (LEServerInfo *)OICCalloc(1, sizeof(LEServerInfo));
1007 if (NULL == serverInfo)
1009 OIC_LOG(ERROR, TAG, "Malloc failed");
1010 CALEGattDisConnect(remoteAddress);
1011 return CA_MEMORY_ALLOC_FAILED;
1013 serverInfo->clientHandle = clientHandle;
1014 serverInfo->serviceHandle = serviceHandle;
1015 serverInfo->readChar = readChrHandle;
1016 serverInfo->writeChar = writeChrHandle;
1017 serverInfo->remoteAddress = OICStrdup(remoteAddress);
1019 ca_mutex_lock(g_LEServerListMutex);
1020 CAResult_t result = CAAddLEServerInfoToList(&g_LEServerList, serverInfo);
1021 if (CA_STATUS_OK != result)
1023 OIC_LOG(ERROR, TAG, "CAAddBLEClientInfoToList failed");
1024 bt_gatt_client_destroy(clientHandle);
1025 CALEGattDisConnect(remoteAddress);
1026 return CA_STATUS_FAILED;
1028 ca_mutex_unlock(g_LEServerListMutex);
1030 // Send the data of pending multicast data list if any.
1031 if (g_multicastDataList)
1033 ca_mutex_lock(g_multicastDataListMutex);
1034 uint32_t arrayLength = u_arraylist_length(g_multicastDataList);
1035 for (int i = 0; i < arrayLength; i++)
1037 CALEData_t *multicastData = u_arraylist_get(g_multicastDataList, i);
1038 if (NULL == multicastData)
1040 OIC_LOG(DEBUG, TAG, "multicastData is NULL");
1043 CAUpdateCharacteristicsToGattServer(remoteAddress, multicastData->data,
1044 multicastData->dataLen, LE_UNICAST, 0);
1046 ca_mutex_unlock(g_multicastDataListMutex);
1049 OIC_LOG(DEBUG, TAG, "OUT");
1050 return CA_STATUS_OK;
1053 CAResult_t CAUpdateCharacteristicsToGattServer(const char *remoteAddress,
1054 const uint8_t *data, const uint32_t dataLen,
1055 CALETransferType_t type, const int32_t position)
1057 OIC_LOG(DEBUG, TAG, "IN");
1059 VERIFY_NON_NULL(data, TAG, "data is NULL");
1063 OIC_LOG(ERROR, TAG, "dataLen is less than or equal zero. Invalid input!");
1064 return CA_STATUS_INVALID_PARAM;
1067 LEServerInfo *leServerInfo = NULL;
1068 CAResult_t ret = CA_STATUS_FAILED;
1070 ca_mutex_lock(g_LEServerListMutex);
1071 if (LE_UNICAST == type)
1073 ret = CAGetLEServerInfo(g_LEServerList, remoteAddress, &leServerInfo);
1075 else if (LE_MULTICAST == type)
1077 ret = CAGetLEServerInfoByPosition(g_LEServerList, position, &leServerInfo);
1079 ca_mutex_unlock(g_LEServerListMutex);
1081 if (CA_STATUS_OK != ret)
1083 OIC_LOG(ERROR, TAG, "CAGetBLEServiceInfoByPosition is failed");
1084 return CA_STATUS_FAILED;
1087 VERIFY_NON_NULL(leServerInfo, TAG, "bleServiceInfo is NULL");
1089 OIC_LOG_V(DEBUG, TAG, "Updating the data of length [%d] to [%s] ", dataLen,
1090 leServerInfo->remoteAddress);
1092 int result = bt_gatt_set_value(leServerInfo->writeChar, (char *)data, dataLen);
1094 if (BT_ERROR_NONE != result)
1096 OIC_LOG_V(ERROR, TAG,
1097 "bt_gatt_set_value Failed with return val [%s]",
1098 CALEGetErrorMsg(result));
1099 return CA_STATUS_FAILED;
1102 result = bt_gatt_client_write_value(leServerInfo->writeChar, CALEGattCharacteristicWriteCb,
1104 if (BT_ERROR_NONE != result)
1106 OIC_LOG_V(ERROR, TAG,
1107 "bt_gatt_client_write_value Failed with return val [%s]",
1108 CALEGetErrorMsg(result));
1109 return CA_STATUS_FAILED;
1112 // wait for callback for write Characteristic with success to sent data
1113 OIC_LOG_V(DEBUG, TAG, "callback flag is %d", g_isSignalSetFlag);
1114 ca_mutex_lock(g_threadWriteCharacteristicMutex);
1115 if (!g_isSignalSetFlag)
1117 OIC_LOG(DEBUG, TAG, "wait for callback to notify writeCharacteristic is success");
1118 if (CA_WAIT_SUCCESS != ca_cond_wait_for(g_threadWriteCharacteristicCond,
1119 g_threadWriteCharacteristicMutex,
1120 WAIT_TIME_WRITE_CHARACTERISTIC))
1122 OIC_LOG(ERROR, TAG, "there is no response. write has failed");
1123 g_isSignalSetFlag = false;
1124 ca_mutex_unlock(g_threadWriteCharacteristicMutex);
1125 return CA_SEND_FAILED;
1128 // reset flag set by writeCharacteristic Callback
1129 g_isSignalSetFlag = false;
1130 ca_mutex_unlock(g_threadWriteCharacteristicMutex);
1132 OIC_LOG(DEBUG, TAG, "OUT");
1133 return CA_STATUS_OK;
1136 CAResult_t CAUpdateCharacteristicsToAllGattServers(const uint8_t *data, uint32_t dataLen)
1138 OIC_LOG(DEBUG, TAG, "IN");
1140 VERIFY_NON_NULL(data, TAG, "data is NULL");
1144 OIC_LOG(ERROR, TAG, "dataLen is less than or equal zero. Invalid input !");
1145 return CA_STATUS_INVALID_PARAM;
1148 int numOfServersConnected = CAGetRegisteredServiceCount();
1150 // Send data to already connected devices.
1151 for (int32_t pos = 0; pos < numOfServersConnected; pos++)
1153 /*remoteAddress will be NULL.
1154 Since we have to send to all destinations. pos will be used for getting remote address.
1156 int32_t ret = CAUpdateCharacteristicsToGattServer(NULL, data, dataLen, LE_MULTICAST, pos);
1158 if (CA_STATUS_OK != ret)
1160 OIC_LOG_V(ERROR, TAG,
1161 "CAUpdateCharacteristicsToGattServer Failed with return val [%d] ", ret);
1162 g_clientErrorCallback(NULL, data, dataLen, ret);
1166 // Add the data to pending list.
1167 CALEData_t *multicastData = (CALEData_t *)OICCalloc(1, sizeof(CALEData_t));
1168 if (NULL == multicastData)
1170 OIC_LOG(ERROR, TAG, "Calloc failed");
1173 multicastData->data = OICCalloc(1, dataLen);
1174 if (NULL == multicastData->data)
1176 OIC_LOG(ERROR, TAG, "Calloc failed");
1179 memcpy(multicastData->data, data, dataLen);
1180 multicastData->dataLen = dataLen;
1182 ca_mutex_lock(g_multicastDataListMutex);
1183 if (NULL == g_multicastDataList)
1185 g_multicastDataList = u_arraylist_create();
1187 u_arraylist_add(g_multicastDataList, (void *)multicastData);
1188 ca_mutex_unlock(g_multicastDataListMutex);
1190 // Start the scanning.
1191 CAResult_t result = CALEGattStartDeviceScanning();
1192 if (CA_STATUS_OK != result)
1194 OIC_LOG(ERROR, TAG, "CALEGattStartDeviceDiscovery Failed");
1198 // Start the timer by signalling it.
1199 ca_cond_signal(g_startTimerCond);
1202 OIC_LOG(DEBUG, TAG, "OUT ");
1203 return CA_STATUS_OK;