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_LEClientStateMutex);
377 if (true == g_isLEGattClientStarted)
379 OIC_LOG(ERROR, TAG, "Gatt Client is already running!!");
380 ca_mutex_unlock(g_LEClientStateMutex);
381 return CA_STATUS_FAILED;
384 CAResult_t result = CALEGattSetCallbacks();
385 if (CA_STATUS_OK != result)
387 OIC_LOG(ERROR, TAG, "CABleGattSetCallbacks Failed");
388 ca_mutex_unlock(g_LEClientStateMutex);
389 CATerminateLEGattClient();
390 return CA_STATUS_FAILED;
393 g_isLEGattClientStarted = true;
394 ca_mutex_unlock(g_LEClientStateMutex);
396 ca_mutex_lock(g_LEClientThreadPoolMutex);
397 if (NULL == g_LEClientThreadPool)
399 OIC_LOG(ERROR, TAG, "gBleServerThreadPool is NULL");
400 CATerminateGattClientMutexVariables();
401 ca_mutex_unlock(g_LEClientThreadPoolMutex);
402 return CA_STATUS_FAILED;
405 result = ca_thread_pool_add_task(g_LEClientThreadPool, CAStartTimerThread,
407 if (CA_STATUS_OK != result)
409 OIC_LOG(ERROR, TAG, "ca_thread_pool_add_task failed");
410 CATerminateGattClientMutexVariables();
411 ca_mutex_unlock(g_LEClientThreadPoolMutex);
412 return CA_STATUS_FAILED;
414 ca_mutex_unlock(g_LEClientThreadPoolMutex);
416 OIC_LOG(DEBUG, TAG, "OUT");
420 void CAStartTimerThread(void *data)
422 OIC_LOG(DEBUG, TAG, "IN");
423 while (g_isLEGattClientStarted)
425 ca_mutex_lock(g_multicastDataListMutex);
426 if (!g_isMulticastInProgress)
428 OIC_LOG(DEBUG, TAG, "waiting....");
429 ca_cond_wait(g_startTimerCond, g_multicastDataListMutex);
430 OIC_LOG(DEBUG, TAG, "Wake up");
431 g_isMulticastInProgress = true;
434 // Timed conditional wait for stopping the scan.
435 CAWaitResult_t ret = ca_cond_wait_for(g_scanningTimeCond, g_multicastDataListMutex,
437 if (CA_WAIT_TIMEDOUT == ret)
439 OIC_LOG(DEBUG, TAG, "Scan is timed Out");
441 CALEGattStopDeviceScanning();
443 // Clear the data list and device list.
444 u_arraylist_destroy(g_multicastDataList);
445 g_multicastDataList = NULL;
447 ca_mutex_lock(g_deviceDiscoveredListMutex);
448 u_arraylist_destroy(g_deviceDiscoveredList);
449 g_deviceDiscoveredList = NULL;
450 ca_mutex_unlock(g_deviceDiscoveredListMutex);
452 g_isMulticastInProgress = false;
454 ca_mutex_unlock(g_multicastDataListMutex);
457 OIC_LOG(DEBUG, TAG, "OUT");
460 void CAStopLEGattClient()
462 OIC_LOG(DEBUG, TAG, "IN");
464 ca_mutex_lock(g_LEClientStateMutex);
466 if (false == g_isLEGattClientStarted)
468 OIC_LOG(ERROR, TAG, "Gatt Client is not running to stop");
469 ca_mutex_unlock(g_LEClientStateMutex);
473 CALEGattUnSetCallbacks();
475 CALEGattStopDeviceScanning();
477 g_isLEGattClientStarted = false;
479 // Signal the conditions waiting in Start timer.
480 ca_cond_signal(g_startTimerCond);
481 ca_cond_signal(g_scanningTimeCond);
483 // Destroy the multicast data list and device list if not empty.
484 if (NULL != g_multicastDataList)
486 ca_mutex_lock(g_multicastDataListMutex);
487 u_arraylist_destroy(g_multicastDataList);
488 g_multicastDataList = NULL;
489 ca_mutex_unlock(g_multicastDataListMutex);
492 if (NULL != g_deviceDiscoveredList)
494 ca_mutex_lock(g_deviceDiscoveredListMutex);
495 u_arraylist_destroy(g_deviceDiscoveredList);
496 g_deviceDiscoveredList = NULL;
497 ca_mutex_unlock(g_deviceDiscoveredListMutex);
500 ca_mutex_lock(g_LEServerListMutex);
501 CAFreeLEServerList(g_LEServerList);
502 g_LEServerList = NULL;
503 ca_mutex_unlock(g_LEServerListMutex);
505 ca_mutex_lock(g_threadWriteCharacteristicMutex);
506 ca_cond_signal(g_threadWriteCharacteristicCond);
507 ca_mutex_unlock(g_threadWriteCharacteristicMutex);
509 CAResetRegisteredServiceCount();
511 GMainContext *context_event_loop = NULL;
512 // Required for waking up the thread which is running in gmain loop
513 if (NULL != g_eventLoop)
515 context_event_loop = g_main_loop_get_context(g_eventLoop);
517 if (context_event_loop)
519 OIC_LOG_V(DEBUG, TAG, "g_eventLoop context %x", context_event_loop);
520 g_main_context_wakeup(context_event_loop);
522 // Kill g main loops and kill threads.
523 g_main_loop_quit(g_eventLoop);
527 OIC_LOG(ERROR, TAG, "g_eventLoop context is NULL");
530 ca_mutex_unlock(g_LEClientStateMutex);
532 OIC_LOG(DEBUG, TAG, "OUT");
535 CAResult_t CAInitializeLEGattClient()
537 OIC_LOG(DEBUG, TAG, "Initialize GATT Client");
538 CAResult_t res = CAInitGattClientMutexVariables();
539 if (CA_STATUS_OK != res)
541 OIC_LOG(ERROR, TAG, "CAInitGattClientMutexVariables failed!");
542 CATerminateGattClientMutexVariables();
543 return CA_STATUS_FAILED;
548 void CATerminateLEGattClient()
550 OIC_LOG(DEBUG, TAG, "IN");
552 CATerminateGattClientMutexVariables();
554 OIC_LOG(DEBUG, TAG, "OUT");
557 CAResult_t CAInitGattClientMutexVariables()
559 OIC_LOG(DEBUG, TAG, "IN");
560 if (NULL == g_LEClientStateMutex)
562 g_LEClientStateMutex = ca_mutex_new();
563 if (NULL == g_LEClientStateMutex)
565 OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
566 return CA_STATUS_FAILED;
570 if (NULL == g_LEServerListMutex)
572 g_LEServerListMutex = ca_mutex_new();
573 if (NULL == g_LEServerListMutex)
575 OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
576 return CA_STATUS_FAILED;
580 if (NULL == g_LEReqRespClientCbMutex)
582 g_LEReqRespClientCbMutex = ca_mutex_new();
583 if (NULL == g_LEReqRespClientCbMutex)
585 OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
586 return CA_STATUS_FAILED;
590 if (NULL == g_LEClientThreadPoolMutex)
592 g_LEClientThreadPoolMutex = ca_mutex_new();
593 if (NULL == g_LEClientThreadPoolMutex)
595 OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
596 return CA_STATUS_FAILED;
600 if (NULL == g_LEClientConnectMutex)
602 g_LEClientConnectMutex = ca_mutex_new();
603 if (NULL == g_LEClientConnectMutex)
605 OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
606 return CA_STATUS_FAILED;
610 if (NULL == g_multicastDataListMutex)
612 g_multicastDataListMutex = ca_mutex_new();
613 if (NULL == g_multicastDataListMutex)
615 OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
616 return CA_STATUS_FAILED;
620 if (NULL == g_deviceDiscoveredListMutex)
622 g_deviceDiscoveredListMutex = ca_mutex_new();
623 if (NULL == g_deviceDiscoveredListMutex)
625 OIC_LOG(ERROR, TAG, "ca_mutex_new failed");
626 return CA_STATUS_FAILED;
630 if (NULL == g_threadWriteCharacteristicMutex)
632 g_threadWriteCharacteristicMutex = ca_mutex_new();
633 if (NULL == g_threadWriteCharacteristicMutex)
635 OIC_LOG(ERROR, TAG, "ca_mutex_new has failed");
636 return CA_STATUS_FAILED;
640 if (NULL == g_startTimerCond)
642 g_startTimerCond = ca_cond_new();
643 if (NULL == g_startTimerCond)
645 OIC_LOG(ERROR, TAG, "ca_cond_new failed");
646 return CA_STATUS_FAILED;
650 if (NULL == g_scanningTimeCond)
652 g_scanningTimeCond = ca_cond_new();
653 if (NULL == g_scanningTimeCond)
655 OIC_LOG(ERROR, TAG, "ca_cond_new failed");
656 return CA_STATUS_FAILED;
660 if (NULL == g_threadWriteCharacteristicCond)
662 g_threadWriteCharacteristicCond = ca_cond_new();
663 if (NULL == g_threadWriteCharacteristicCond)
665 OIC_LOG(ERROR, TAG, "ca_cond_new failed");
666 return CA_STATUS_FAILED;
670 OIC_LOG(DEBUG, TAG, "OUT");
674 void CATerminateGattClientMutexVariables()
676 OIC_LOG(DEBUG, TAG, "IN");
678 ca_mutex_free(g_LEClientStateMutex);
679 g_LEClientStateMutex = NULL;
681 ca_mutex_free(g_LEServerListMutex);
682 g_LEServerListMutex = NULL;
684 ca_mutex_free(g_LEReqRespClientCbMutex);
685 g_LEReqRespClientCbMutex = NULL;
687 ca_mutex_free(g_LEClientConnectMutex);
688 g_LEClientConnectMutex = NULL;
690 ca_mutex_free(g_LEClientThreadPoolMutex);
691 g_LEClientThreadPoolMutex = NULL;
693 ca_mutex_free(g_multicastDataListMutex);
694 g_multicastDataListMutex = NULL;
696 ca_mutex_free(g_deviceDiscoveredListMutex);
697 g_deviceDiscoveredListMutex = NULL;
699 ca_mutex_free(g_threadWriteCharacteristicMutex);
700 g_threadWriteCharacteristicMutex = NULL;
702 ca_cond_free(g_startTimerCond);
703 g_startTimerCond = NULL;
705 ca_cond_free(g_scanningTimeCond);
706 g_scanningTimeCond = NULL;
708 ca_cond_free(g_threadWriteCharacteristicCond);
709 g_threadWriteCharacteristicCond = NULL;
710 g_isSignalSetFlag = false;
712 OIC_LOG(DEBUG, TAG, "OUT");
715 CAResult_t CALEGattSetCallbacks()
717 OIC_LOG(DEBUG, TAG, "IN");
719 OIC_LOG(DEBUG, TAG, "OUT");
723 void CALEGattUnSetCallbacks()
725 OIC_LOG(DEBUG, TAG, "IN");
727 bt_gatt_unset_connection_state_changed_cb();
729 int numOfServersConnected = CAGetRegisteredServiceCount();
730 LEServerInfo *leServerInfo = NULL;
732 for (int32_t index = 0; index < numOfServersConnected; index++)
734 CAGetLEServerInfoByPosition(g_LEServerList, index, &leServerInfo);
735 bt_gatt_client_unset_characteristic_value_changed_cb(leServerInfo->readChar);
737 OIC_LOG(DEBUG, TAG, "OUT");
740 CAResult_t CALEGattStartDeviceScanning()
742 OIC_LOG(DEBUG, TAG, "IN");
744 int ret = bt_adapter_le_start_scan(CALEAdapterScanResultCb, NULL);
745 if(BT_ERROR_NONE != ret)
747 OIC_LOG_V(ERROR, TAG, "bt_adapter_le_start_scan failed[%s]",
748 CALEGetErrorMsg(ret));
749 return CA_STATUS_FAILED;
752 OIC_LOG(DEBUG, TAG, "OUT");
756 void CALEGattStopDeviceScanning()
758 OIC_LOG(DEBUG, TAG, "IN");
760 int ret = bt_adapter_le_stop_scan();
761 if (BT_ERROR_NONE != ret)
763 OIC_LOG_V(ERROR, TAG, "bt_adapter_le_stop_scan failed[%s]",
764 CALEGetErrorMsg(ret));
767 OIC_LOG(DEBUG, TAG, "OUT");
770 void CAGattConnectThread (void *remoteAddress)
772 OIC_LOG(DEBUG, TAG, "IN ");
774 VERIFY_NON_NULL_VOID(remoteAddress, TAG, "remote address is NULL");
776 char *address = (char *)remoteAddress;
778 OIC_LOG_V(DEBUG, TAG, "remote address is [%s]", address);
780 CAResult_t result = CALEGattConnect(address);
782 if (CA_STATUS_OK != result)
784 OIC_LOG_V(ERROR, TAG, "bt_gatt_connect failed for [%s]", address);
789 OIC_LOG(DEBUG, TAG, "OUT");
792 CAResult_t CALEGattConnect(const char *remoteAddress)
794 OIC_LOG(DEBUG, TAG, "IN");
796 VERIFY_NON_NULL_RET(remoteAddress, TAG,
797 "remote address is NULL", CA_STATUS_FAILED);
799 ca_mutex_lock(g_LEClientConnectMutex);
800 bool isConnected = false;
801 int ret = bt_device_is_profile_connected(remoteAddress, BT_PROFILE_GATT, &isConnected);
802 if (BT_ERROR_NONE != ret)
804 OIC_LOG_V(ERROR, TAG, "bt_device_is_profile_connected Failed with ret value [%s] ",
805 CALEGetErrorMsg(ret));
806 ca_mutex_unlock(g_LEClientConnectMutex);
807 return CA_STATUS_FAILED;
810 CAResult_t result = CA_STATUS_OK;
813 ret = bt_gatt_connect(remoteAddress, true);
815 if (BT_ERROR_NONE != ret)
817 OIC_LOG_V(ERROR, TAG, "bt_gatt_connect Failed with ret value [%s] ",
818 CALEGetErrorMsg(ret));
819 ca_mutex_unlock(g_LEClientConnectMutex);
820 return CA_STATUS_FAILED;
825 OIC_LOG_V(INFO, TAG, "Remote address[%s] is already connected",
827 char *addr = OICStrdup(remoteAddress);
830 OIC_LOG(ERROR, TAG, "addr is NULL");
831 ca_mutex_unlock(g_LEClientConnectMutex);
832 return CA_STATUS_FAILED;
835 ca_mutex_lock(g_LEClientThreadPoolMutex);
836 if (NULL == g_LEClientThreadPool)
838 OIC_LOG(ERROR, TAG, "g_LEClientThreadPool is NULL");
840 ca_mutex_unlock(g_LEClientThreadPoolMutex);
841 ca_mutex_unlock(g_LEClientConnectMutex);
842 return CA_STATUS_FAILED;
845 result = ca_thread_pool_add_task(g_LEClientThreadPool, CADiscoverLEServicesThread,
847 if (CA_STATUS_OK != result)
849 OIC_LOG_V(ERROR, TAG, "ca_thread_pool_add_task failed with ret [%d]", result);
852 ca_mutex_unlock(g_LEClientThreadPoolMutex);
854 ca_mutex_unlock(g_LEClientConnectMutex);
856 OIC_LOG(DEBUG, TAG, "OUT");
860 CAResult_t CALEGattDisConnect(const char *remoteAddress)
862 OIC_LOG(DEBUG, TAG, "IN");
864 VERIFY_NON_NULL_RET(remoteAddress, TAG,
865 "remote address is NULL", CA_STATUS_FAILED);
867 int ret = bt_gatt_disconnect(remoteAddress);
869 if (BT_ERROR_NONE != ret)
871 OIC_LOG_V(ERROR, TAG, "bt_gatt_disconnect Failed with ret value [%d] ",
872 CALEGetErrorMsg(ret));
873 return CA_STATUS_FAILED;
876 OIC_LOG(DEBUG, TAG, "OUT");
880 void CADiscoverLEServicesThread (void *remoteAddress)
882 OIC_LOG(DEBUG, TAG, "IN");
884 VERIFY_NON_NULL_VOID(remoteAddress, TAG, "remote address is NULL");
886 char *address = (char *)remoteAddress;
888 CAResult_t result = CALEGattDiscoverServices(address);
889 if (CA_STATUS_OK != result)
891 OIC_LOG(ERROR, TAG, "CALEGattDiscoverServices failed");
895 OIC_LOG(DEBUG, TAG, "OUT");
898 CAResult_t CALEGattDiscoverServices(const char *remoteAddress)
900 OIC_LOG(DEBUG, TAG, "IN");
902 VERIFY_NON_NULL_RET(remoteAddress, TAG,
903 "remote address is NULL", CA_STATUS_FAILED);
905 bt_gatt_client_h clientHandle = NULL;
906 int32_t ret = bt_gatt_client_create(remoteAddress, &clientHandle);
907 if (BT_ERROR_NONE != ret || NULL == clientHandle)
909 OIC_LOG_V(ERROR, TAG,
910 "bt_gatt_client_create Failed with ret value [%s] ", CALEGetErrorMsg(ret));
911 CALEGattDisConnect(remoteAddress);
912 return CA_STATUS_FAILED;
915 bt_gatt_h serviceHandle = NULL;
916 ret = bt_gatt_client_get_service(clientHandle, CA_GATT_SERVICE_UUID, &serviceHandle);
917 if (BT_ERROR_NONE != ret || NULL == serviceHandle)
919 OIC_LOG_V(ERROR, TAG,
920 "bt_gatt_client_get_service Failed with ret value [%s] ", CALEGetErrorMsg(ret));
921 bt_gatt_client_destroy(clientHandle);
922 CALEGattDisConnect(remoteAddress);
923 return CA_STATUS_FAILED;
926 // Server will read data on this characteristic.
927 bt_gatt_h writeChrHandle = NULL;
928 ret = bt_gatt_service_get_characteristic(serviceHandle, CA_GATT_REQUEST_CHRC_UUID,
930 if (BT_ERROR_NONE != ret || NULL == writeChrHandle)
932 OIC_LOG_V(ERROR, TAG,
933 "bt_gatt_service_get_characteristic Failed with ret value [%s] ",
934 CALEGetErrorMsg(ret));
935 bt_gatt_client_destroy(clientHandle);
936 CALEGattDisConnect(remoteAddress);
937 return CA_STATUS_FAILED;
940 // Server will notify data on this characteristic.
941 bt_gatt_h readChrHandle = NULL;
942 ret = bt_gatt_service_get_characteristic(serviceHandle, CA_GATT_RESPONSE_CHRC_UUID,
944 if (BT_ERROR_NONE != ret || NULL == readChrHandle)
946 OIC_LOG_V(ERROR, TAG,
947 "bt_gatt_service_get_characteristic Failed with ret value [%s] ",
948 CALEGetErrorMsg(ret));
949 bt_gatt_client_destroy(clientHandle);
950 CALEGattDisConnect(remoteAddress);
951 return CA_STATUS_FAILED;
955 //TODO: This data has to be freed while unsetting the callback.
956 char *addr = OICStrdup(remoteAddress);
957 ret = bt_gatt_client_set_characteristic_value_changed_cb(readChrHandle,
958 CALEGattCharacteristicChangedCb,
960 if (BT_ERROR_NONE != ret)
962 OIC_LOG_V(ERROR, TAG,
963 "bt_gatt_client_set_characteristic_value_changed_cb Failed with ret value [%s]",
964 CALEGetErrorMsg(ret));
965 bt_gatt_client_destroy(clientHandle);
966 CALEGattDisConnect(remoteAddress);
967 return CA_STATUS_FAILED;
970 LEServerInfo *serverInfo = (LEServerInfo *)OICCalloc(1, sizeof(LEServerInfo));
971 if (NULL == serverInfo)
973 OIC_LOG(ERROR, TAG, "Malloc failed");
974 CALEGattDisConnect(remoteAddress);
975 return CA_MEMORY_ALLOC_FAILED;
977 serverInfo->clientHandle = clientHandle;
978 serverInfo->serviceHandle = serviceHandle;
979 serverInfo->readChar = readChrHandle;
980 serverInfo->writeChar = writeChrHandle;
981 serverInfo->remoteAddress = OICStrdup(remoteAddress);
983 ca_mutex_lock(g_LEServerListMutex);
984 CAResult_t result = CAAddLEServerInfoToList(&g_LEServerList, serverInfo);
985 if (CA_STATUS_OK != result)
987 OIC_LOG(ERROR, TAG, "CAAddBLEClientInfoToList failed");
988 bt_gatt_client_destroy(clientHandle);
989 CALEGattDisConnect(remoteAddress);
990 return CA_STATUS_FAILED;
992 ca_mutex_unlock(g_LEServerListMutex);
994 // Send the data of pending multicast data list if any.
995 if (g_multicastDataList)
997 ca_mutex_lock(g_multicastDataListMutex);
998 uint32_t arrayLength = u_arraylist_length(g_multicastDataList);
999 for (int i = 0; i < arrayLength; i++)
1001 CALEData_t *multicastData = u_arraylist_get(g_multicastDataList, i);
1002 if (NULL == multicastData)
1004 OIC_LOG(DEBUG, TAG, "multicastData is NULL");
1007 CAUpdateCharacteristicsToGattServer(remoteAddress, multicastData->data,
1008 multicastData->dataLen, LE_UNICAST, 0);
1010 ca_mutex_unlock(g_multicastDataListMutex);
1013 OIC_LOG(DEBUG, TAG, "OUT");
1014 return CA_STATUS_OK;
1017 CAResult_t CAUpdateCharacteristicsToGattServer(const char *remoteAddress,
1018 const uint8_t *data, const uint32_t dataLen,
1019 CALETransferType_t type, const int32_t position)
1021 OIC_LOG(DEBUG, TAG, "IN");
1023 VERIFY_NON_NULL(data, TAG, "data is NULL");
1027 OIC_LOG(ERROR, TAG, "dataLen is less than or equal zero. Invalid input!");
1028 return CA_STATUS_INVALID_PARAM;
1031 LEServerInfo *leServerInfo = NULL;
1032 CAResult_t ret = CA_STATUS_FAILED;
1034 ca_mutex_lock(g_LEServerListMutex);
1035 if (LE_UNICAST == type)
1037 ret = CAGetLEServerInfo(g_LEServerList, remoteAddress, &leServerInfo);
1039 else if (LE_MULTICAST == type)
1041 ret = CAGetLEServerInfoByPosition(g_LEServerList, position, &leServerInfo);
1043 ca_mutex_unlock(g_LEServerListMutex);
1045 if (CA_STATUS_OK != ret)
1047 OIC_LOG(ERROR, TAG, "CAGetBLEServiceInfoByPosition is failed");
1048 return CA_STATUS_FAILED;
1051 VERIFY_NON_NULL(leServerInfo, TAG, "bleServiceInfo is NULL");
1053 OIC_LOG_V(DEBUG, TAG, "Updating the data of length [%d] to [%s] ", dataLen,
1054 leServerInfo->remoteAddress);
1056 int result = bt_gatt_set_value(leServerInfo->writeChar, (char *)data, dataLen);
1058 if (BT_ERROR_NONE != result)
1060 OIC_LOG_V(ERROR, TAG,
1061 "bt_gatt_set_value Failed with return val [%s]",
1062 CALEGetErrorMsg(result));
1063 return CA_STATUS_FAILED;
1066 result = bt_gatt_client_write_value(leServerInfo->writeChar, CALEGattCharacteristicWriteCb,
1068 if (BT_ERROR_NONE != result)
1070 OIC_LOG_V(ERROR, TAG,
1071 "bt_gatt_client_write_value Failed with return val [%s]",
1072 CALEGetErrorMsg(result));
1073 return CA_STATUS_FAILED;
1076 // wait for callback for write Characteristic with success to sent data
1077 OIC_LOG_V(DEBUG, TAG, "callback flag is %d", g_isSignalSetFlag);
1078 ca_mutex_lock(g_threadWriteCharacteristicMutex);
1079 if (!g_isSignalSetFlag)
1081 OIC_LOG(DEBUG, TAG, "wait for callback to notify writeCharacteristic is success");
1082 if (CA_WAIT_SUCCESS != ca_cond_wait_for(g_threadWriteCharacteristicCond,
1083 g_threadWriteCharacteristicMutex,
1084 WAIT_TIME_WRITE_CHARACTERISTIC))
1086 OIC_LOG(ERROR, TAG, "there is no response. write has failed");
1087 g_isSignalSetFlag = false;
1088 ca_mutex_unlock(g_threadWriteCharacteristicMutex);
1089 return CA_SEND_FAILED;
1092 // reset flag set by writeCharacteristic Callback
1093 g_isSignalSetFlag = false;
1094 ca_mutex_unlock(g_threadWriteCharacteristicMutex);
1096 OIC_LOG(DEBUG, TAG, "OUT");
1097 return CA_STATUS_OK;
1100 CAResult_t CAUpdateCharacteristicsToAllGattServers(const uint8_t *data, uint32_t dataLen)
1102 OIC_LOG(DEBUG, TAG, "IN");
1104 VERIFY_NON_NULL(data, TAG, "data is NULL");
1108 OIC_LOG(ERROR, TAG, "dataLen is less than or equal zero. Invalid input !");
1109 return CA_STATUS_INVALID_PARAM;
1112 int numOfServersConnected = CAGetRegisteredServiceCount();
1114 // Send data to already connected devices.
1115 for (int32_t pos = 0; pos < numOfServersConnected; pos++)
1117 /*remoteAddress will be NULL.
1118 Since we have to send to all destinations. pos will be used for getting remote address.
1120 int32_t ret = CAUpdateCharacteristicsToGattServer(NULL, data, dataLen, LE_MULTICAST, pos);
1122 if (CA_STATUS_OK != ret)
1124 OIC_LOG_V(ERROR, TAG,
1125 "CAUpdateCharacteristicsToGattServer Failed with return val [%d] ", ret);
1126 g_clientErrorCallback(NULL, data, dataLen, ret);
1130 // Add the data to pending list.
1131 CALEData_t *multicastData = (CALEData_t *)OICCalloc(1, sizeof(CALEData_t));
1132 if (NULL == multicastData)
1134 OIC_LOG(ERROR, TAG, "Calloc failed");
1137 multicastData->data = OICCalloc(1, dataLen);
1138 if (NULL == multicastData->data)
1140 OIC_LOG(ERROR, TAG, "Calloc failed");
1143 memcpy(multicastData->data, data, dataLen);
1144 multicastData->dataLen = dataLen;
1146 ca_mutex_lock(g_multicastDataListMutex);
1147 if (NULL == g_multicastDataList)
1149 g_multicastDataList = u_arraylist_create();
1151 u_arraylist_add(g_multicastDataList, (void *)multicastData);
1152 ca_mutex_unlock(g_multicastDataListMutex);
1154 // Start the scanning.
1155 CAResult_t result = CALEGattStartDeviceScanning();
1156 if (CA_STATUS_OK != result)
1158 OIC_LOG(ERROR, TAG, "CALEGattStartDeviceDiscovery Failed");
1162 // Start the timer by signalling it.
1163 ca_cond_signal(g_startTimerCond);
1166 OIC_LOG(DEBUG, TAG, "OUT ");
1167 return CA_STATUS_OK;