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 oc_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 oc_mutex g_deviceDiscoveredListMutex = NULL;
77 * Condition to start the timer for scanning.
79 static oc_cond g_startTimerCond = NULL;
82 * Condition for scanning Time interval.
84 static oc_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 oc_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 oc_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 oc_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 oc_mutex g_LEClientStateMutex = NULL;
120 * Mutex to synchronize the task to be pushed to thread pool.
122 static oc_mutex g_LEClientThreadPoolMutex = NULL;
125 * Mutex to synchronize the task to write characteristic one packet after another.
127 static oc_mutex g_threadWriteCharacteristicMutex = NULL;
130 * Condition for Writing characteristic.
132 static oc_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 bool CALEIsHaveService(bt_adapter_le_device_scan_result_info_s* scanInfo, char* service_uuid)
167 // For arduino servers, scan response will give the UUIDs advertised.
168 result = bt_adapter_le_get_scan_result_service_uuids(scanInfo,
169 BT_ADAPTER_LE_PACKET_SCAN_RESPONSE,
171 if (result == BT_ERROR_NONE && NULL != uuids)
174 for (i = 0; i < count; i++)
176 if (0 == strcasecmp(uuids[i], service_uuid))
178 OIC_LOG_V(DEBUG, TAG, "Service[%s] Found in %s",
179 uuids[i], scanInfo->remote_address);
187 // For android/tizen servers, advertising packet will give the UUIDs.
188 result = bt_adapter_le_get_scan_result_service_uuids(scanInfo,
189 BT_ADAPTER_LE_PACKET_ADVERTISING,
191 if (result == BT_ERROR_NONE && NULL != uuids)
194 for (i = 0; i < count; i++)
196 if (0 == strcasecmp(uuids[i], service_uuid))
198 OIC_LOG_V(DEBUG, TAG, "Service[%s] Found in %s",
199 uuids[i], scanInfo->remote_address);
210 bool CALEIsDeviceDiscovered(const char * address)
212 if (g_deviceDiscoveredList)
214 oc_mutex_lock(g_deviceDiscoveredListMutex);
215 uint32_t arrayLength = u_arraylist_length(g_deviceDiscoveredList);
216 for (uint32_t i = 0; i < arrayLength; i++)
218 char *deviceAddr = u_arraylist_get(g_deviceDiscoveredList, i);
219 if (0 == strcasecmp(deviceAddr, address))
221 oc_mutex_unlock(g_deviceDiscoveredListMutex);
226 oc_mutex_unlock(g_deviceDiscoveredListMutex);
231 void CALEGattCharacteristicChangedCb(bt_gatt_h characteristic,
233 int valueLen, void *userData)
235 (void)characteristic;
237 OIC_LOG(DEBUG, TAG, "IN");
238 OIC_LOG_V(DEBUG, TAG, "Changed characteristic value length [%d]", valueLen);
240 oc_mutex_lock(g_LEReqRespClientCbMutex);
241 if (NULL == g_LEClientDataReceivedCallback)
243 OIC_LOG(ERROR, TAG, "Request response callback is not set");
244 oc_mutex_unlock(g_LEReqRespClientCbMutex);
248 uint32_t sentLength = 0;
249 g_LEClientDataReceivedCallback(userData, (uint8_t *)value, valueLen, &sentLength);
251 OIC_LOG_V(DEBUG, TAG, "Recv data Length is %d", sentLength);
253 oc_mutex_unlock(g_LEReqRespClientCbMutex);
255 OIC_LOG(DEBUG, TAG, "OUT");
258 void CALEGattCharacteristicWriteCb(int result, bt_gatt_h reqHandle, void *userData)
263 OIC_LOG(DEBUG, TAG, "IN ");
265 if (BT_ERROR_NONE != result)
267 CALogSendStateInfo(CA_ADAPTER_GATT_BTLE, "", 0, -1,
268 false, "writeChar failure");
270 OIC_LOG(ERROR, TAG, "Write failed Need Retry ");
271 //Need to Implement retry mechanism
275 oc_mutex_lock(g_threadWriteCharacteristicMutex);
276 OIC_LOG(DEBUG, TAG, "g_isSignalSetFlag is set true and signal");
277 g_isSignalSetFlag = true;
278 oc_cond_signal(g_threadWriteCharacteristicCond);
279 oc_mutex_unlock(g_threadWriteCharacteristicMutex);
281 CALogSendStateInfo(CA_ADAPTER_GATT_BTLE, "", 0, -1,
282 true, "writeChar success");
285 OIC_LOG(DEBUG, TAG, "OUT ");
288 void CALEGattConnectionStateChanged(bool connected, const char *remoteAddress)
290 OIC_LOG(DEBUG, TAG, "IN ");
292 VERIFY_NON_NULL_VOID(remoteAddress, TAG, "remote address is NULL");
294 // Start the scanning.
295 CAResult_t ret = CALEGattStartDeviceScanning();
296 if (CA_STATUS_OK != ret)
298 OIC_LOG(ERROR, TAG, "CALEGattStartDeviceDiscovery Failed");
300 // Signal the start timer.
301 oc_cond_signal(g_scanningTimeCond);
305 OIC_LOG_V(DEBUG, TAG, "DisConnected from [%s] ", remoteAddress);
306 oc_mutex_lock(g_LEServerListMutex);
307 CARemoveLEServerInfoFromList(&g_LEServerList, remoteAddress);
308 oc_mutex_unlock(g_LEServerListMutex);
312 OIC_LOG_V(DEBUG, TAG, "Connected to [%s] ", remoteAddress);
314 char *addr = OICStrdup(remoteAddress);
317 OIC_LOG(ERROR, TAG, "addr is NULL");
321 oc_mutex_lock(g_LEClientThreadPoolMutex);
322 if (NULL == g_LEClientThreadPool)
324 OIC_LOG(ERROR, TAG, "g_LEClientThreadPool is NULL");
326 oc_mutex_unlock(g_LEClientThreadPoolMutex);
330 ret = ca_thread_pool_add_task(g_LEClientThreadPool, CADiscoverLEServicesThread,
332 if (CA_STATUS_OK != ret)
334 OIC_LOG_V(ERROR, TAG, "ca_thread_pool_add_task failed with ret [%d]", ret);
337 oc_mutex_unlock(g_LEClientThreadPoolMutex);
339 OIC_LOG(DEBUG, TAG, "OUT");
342 void CALEAdapterScanResultCb(int result, bt_adapter_le_device_scan_result_info_s *scanInfo,
347 OIC_LOG(DEBUG, TAG, "IN");
349 VERIFY_NON_NULL_VOID(scanInfo, TAG, "scanInfo");
350 VERIFY_NON_NULL_VOID(scanInfo->remote_address, TAG, "scanInfo->remote_address");
352 OIC_LOG_V(DEBUG, TAG, "Remote Address [%s]", scanInfo->remote_address);
353 OIC_LOG_V(DEBUG, TAG, "Scan Result [%d]", result);
354 OIC_LOG_V(DEBUG, TAG,
355 " Adv data len [%d] Scan data len[%d]RSSI [%d] Addr_type [%d] ",
356 scanInfo->adv_data_len, scanInfo->scan_data_len, scanInfo->rssi,
357 scanInfo->address_type);
359 // Check if device is already discovered.
360 if (CALEIsDeviceDiscovered(scanInfo->remote_address))
362 OIC_LOG_V(INFO, TAG, "Device[%s] is already discovered", scanInfo->remote_address);
366 if (!CALEIsHaveService(scanInfo, CA_GATT_SERVICE_UUID))
368 oc_mutex_lock(g_deviceDiscoveredListMutex);
369 // Add the the device Discovered list.
370 if (NULL == g_deviceDiscoveredList)
372 g_deviceDiscoveredList = u_arraylist_create();
374 char *deviceAddr = OICStrdup(scanInfo->remote_address);
375 if (NULL == deviceAddr)
377 OIC_LOG_V(ERROR, TAG, "Device address is NULL");
378 oc_mutex_unlock(g_deviceDiscoveredListMutex);
382 u_arraylist_add(g_deviceDiscoveredList, (void *) deviceAddr);
383 oc_mutex_unlock(g_deviceDiscoveredListMutex);
384 OIC_LOG_V(INFO, TAG, "Device[%s] is don't have service", scanInfo->remote_address);
388 // Stop the scan before invoking bt_gatt_connect().
389 CALEGattStopDeviceScanning();
391 size_t len = strlen(scanInfo->remote_address);
393 char *addr = (char *)OICMalloc(sizeof(char) * (len + 1));
394 VERIFY_NON_NULL_VOID(addr, TAG, "Malloc failed");
396 strncpy(addr, scanInfo->remote_address, len + 1);
398 OIC_LOG_V(DEBUG, TAG,
399 "Trying to do Gatt connection to [%s]", addr);
401 oc_mutex_lock(g_LEClientThreadPoolMutex);
402 if (NULL == g_LEClientThreadPool)
404 OIC_LOG(ERROR, TAG, "g_LEClientThreadPool is NULL");
406 oc_mutex_unlock(g_LEClientThreadPoolMutex);
410 CAResult_t res = ca_thread_pool_add_task(g_LEClientThreadPool, CAGattConnectThread, addr, NULL);
411 if (CA_STATUS_OK != res)
413 OIC_LOG_V(ERROR, TAG,
414 "ca_thread_pool_add_task failed with ret [%d]", res);
417 oc_mutex_unlock(g_LEClientThreadPoolMutex);
418 OIC_LOG(DEBUG, TAG, "OUT");
421 void CASetLEClientThreadPoolHandle(ca_thread_pool_t handle)
423 OIC_LOG(DEBUG, TAG, "IN");
425 oc_mutex_lock(g_LEClientThreadPoolMutex);
426 g_LEClientThreadPool = handle;
427 oc_mutex_unlock(g_LEClientThreadPoolMutex);
429 OIC_LOG(DEBUG, TAG, "OUT");
432 void CASetLEReqRespClientCallback(CABLEDataReceivedCallback callback)
434 OIC_LOG(DEBUG, TAG, "IN");
436 oc_mutex_lock(g_LEReqRespClientCbMutex);
438 g_LEClientDataReceivedCallback = callback;
440 oc_mutex_unlock(g_LEReqRespClientCbMutex);
442 OIC_LOG(DEBUG, TAG, "OUT");
445 void CASetBLEClientErrorHandleCallback(CABLEErrorHandleCallback callback)
447 g_clientErrorCallback = callback;
450 CAResult_t CAStartLEGattClient()
452 OIC_LOG(DEBUG, TAG, "IN");
454 oc_mutex_lock(g_LEClientStateMutex);
455 if (true == g_isLEGattClientStarted)
457 OIC_LOG(ERROR, TAG, "Gatt Client is already running!!");
458 oc_mutex_unlock(g_LEClientStateMutex);
459 return CA_STATUS_FAILED;
462 CAResult_t result = CALEGattSetCallbacks();
463 if (CA_STATUS_OK != result)
465 OIC_LOG(ERROR, TAG, "CABleGattSetCallbacks Failed");
466 oc_mutex_unlock(g_LEClientStateMutex);
467 CATerminateLEGattClient();
468 return CA_STATUS_FAILED;
471 g_isLEGattClientStarted = true;
472 oc_mutex_unlock(g_LEClientStateMutex);
474 oc_mutex_lock(g_LEClientThreadPoolMutex);
475 if (NULL == g_LEClientThreadPool)
477 OIC_LOG(ERROR, TAG, "gBleServerThreadPool is NULL");
478 CATerminateGattClientMutexVariables();
479 oc_mutex_unlock(g_LEClientThreadPoolMutex);
480 return CA_STATUS_FAILED;
483 result = ca_thread_pool_add_task(g_LEClientThreadPool, CAStartTimerThread,
485 if (CA_STATUS_OK != result)
487 OIC_LOG(ERROR, TAG, "ca_thread_pool_add_task failed");
488 CATerminateGattClientMutexVariables();
489 oc_mutex_unlock(g_LEClientThreadPoolMutex);
490 return CA_STATUS_FAILED;
492 oc_mutex_unlock(g_LEClientThreadPoolMutex);
494 OIC_LOG(DEBUG, TAG, "OUT");
498 void CAStartTimerThread(void *data)
502 OIC_LOG(DEBUG, TAG, "IN");
503 while (g_isLEGattClientStarted)
505 oc_mutex_lock(g_multicastDataListMutex);
506 if (!g_isMulticastInProgress)
508 OIC_LOG(DEBUG, TAG, "waiting....");
509 oc_cond_wait(g_startTimerCond, g_multicastDataListMutex);
510 OIC_LOG(DEBUG, TAG, "Wake up");
511 g_isMulticastInProgress = true;
513 if (!g_isLEGattClientStarted)
519 // Timed conditional wait for stopping the scan.
520 OCWaitResult_t ret = oc_cond_wait_for(g_scanningTimeCond, g_multicastDataListMutex,
522 if (OC_WAIT_TIMEDOUT == ret)
524 OIC_LOG(DEBUG, TAG, "Scan is timed Out");
526 CALEGattStopDeviceScanning();
528 // Clear the data list and device list.
529 u_arraylist_destroy(g_multicastDataList);
530 g_multicastDataList = NULL;
532 oc_mutex_lock(g_deviceDiscoveredListMutex);
533 u_arraylist_destroy(g_deviceDiscoveredList);
534 g_deviceDiscoveredList = NULL;
535 oc_mutex_unlock(g_deviceDiscoveredListMutex);
537 g_isMulticastInProgress = false;
539 oc_mutex_unlock(g_multicastDataListMutex);
542 OIC_LOG(DEBUG, TAG, "OUT");
545 void CAStopLEGattClient()
547 OIC_LOG(DEBUG, TAG, "IN");
549 oc_mutex_lock(g_LEClientStateMutex);
551 if (false == g_isLEGattClientStarted)
553 OIC_LOG(ERROR, TAG, "Gatt Client is not running to stop");
554 oc_mutex_unlock(g_LEClientStateMutex);
558 CALEGattUnSetCallbacks();
560 CALEGattStopDeviceScanning();
562 // this flag should be set before signal g_startTimerCond.
563 // since scan thread can be stopped through this flag.
564 g_isLEGattClientStarted = false;
566 // Signal the conditions waiting in Start timer.
567 oc_cond_signal(g_startTimerCond);
568 oc_cond_signal(g_scanningTimeCond);
570 // Destroy the multicast data list and device list if not empty.
571 if (NULL != g_multicastDataList)
573 oc_mutex_lock(g_multicastDataListMutex);
574 u_arraylist_destroy(g_multicastDataList);
575 g_multicastDataList = NULL;
576 oc_mutex_unlock(g_multicastDataListMutex);
579 if (NULL != g_deviceDiscoveredList)
581 oc_mutex_lock(g_deviceDiscoveredListMutex);
582 u_arraylist_destroy(g_deviceDiscoveredList);
583 g_deviceDiscoveredList = NULL;
584 oc_mutex_unlock(g_deviceDiscoveredListMutex);
587 oc_mutex_lock(g_LEServerListMutex);
588 CAFreeLEServerList(g_LEServerList);
589 g_LEServerList = NULL;
590 oc_mutex_unlock(g_LEServerListMutex);
592 oc_mutex_lock(g_threadWriteCharacteristicMutex);
593 oc_cond_signal(g_threadWriteCharacteristicCond);
594 oc_mutex_unlock(g_threadWriteCharacteristicMutex);
596 CAResetRegisteredServiceCount();
598 GMainContext *context_event_loop = NULL;
599 // Required for waking up the thread which is running in gmain loop
600 if (NULL != g_eventLoop)
602 context_event_loop = g_main_loop_get_context(g_eventLoop);
604 if (context_event_loop)
606 OIC_LOG_V(DEBUG, TAG, "g_eventLoop context %p", (void *)context_event_loop);
607 g_main_context_wakeup(context_event_loop);
609 // Kill g main loops and kill threads.
610 g_main_loop_quit(g_eventLoop);
614 OIC_LOG(ERROR, TAG, "g_eventLoop context is NULL");
617 oc_mutex_unlock(g_LEClientStateMutex);
619 OIC_LOG(DEBUG, TAG, "OUT");
622 CAResult_t CAInitializeLEGattClient()
624 OIC_LOG(DEBUG, TAG, "Initialize GATT Client");
625 CAResult_t res = CAInitGattClientMutexVariables();
626 if (CA_STATUS_OK != res)
628 OIC_LOG(ERROR, TAG, "CAInitGattClientMutexVariables failed!");
629 CATerminateGattClientMutexVariables();
630 return CA_STATUS_FAILED;
635 void CATerminateLEGattClient()
637 OIC_LOG(DEBUG, TAG, "IN");
639 CATerminateGattClientMutexVariables();
641 OIC_LOG(DEBUG, TAG, "OUT");
644 CAResult_t CAInitGattClientMutexVariables()
646 OIC_LOG(DEBUG, TAG, "IN");
647 if (NULL == g_LEClientStateMutex)
649 g_LEClientStateMutex = oc_mutex_new();
650 if (NULL == g_LEClientStateMutex)
652 OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
653 return CA_STATUS_FAILED;
657 if (NULL == g_LEServerListMutex)
659 g_LEServerListMutex = oc_mutex_new();
660 if (NULL == g_LEServerListMutex)
662 OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
663 return CA_STATUS_FAILED;
667 if (NULL == g_LEReqRespClientCbMutex)
669 g_LEReqRespClientCbMutex = oc_mutex_new();
670 if (NULL == g_LEReqRespClientCbMutex)
672 OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
673 return CA_STATUS_FAILED;
677 if (NULL == g_LEClientThreadPoolMutex)
679 g_LEClientThreadPoolMutex = oc_mutex_new();
680 if (NULL == g_LEClientThreadPoolMutex)
682 OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
683 return CA_STATUS_FAILED;
687 if (NULL == g_LEClientConnectMutex)
689 g_LEClientConnectMutex = oc_mutex_new();
690 if (NULL == g_LEClientConnectMutex)
692 OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
693 return CA_STATUS_FAILED;
697 if (NULL == g_multicastDataListMutex)
699 g_multicastDataListMutex = oc_mutex_new();
700 if (NULL == g_multicastDataListMutex)
702 OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
703 return CA_STATUS_FAILED;
707 if (NULL == g_deviceDiscoveredListMutex)
709 g_deviceDiscoveredListMutex = oc_mutex_new();
710 if (NULL == g_deviceDiscoveredListMutex)
712 OIC_LOG(ERROR, TAG, "oc_mutex_new failed");
713 return CA_STATUS_FAILED;
717 if (NULL == g_threadWriteCharacteristicMutex)
719 g_threadWriteCharacteristicMutex = oc_mutex_new();
720 if (NULL == g_threadWriteCharacteristicMutex)
722 OIC_LOG(ERROR, TAG, "oc_mutex_new has failed");
723 return CA_STATUS_FAILED;
727 if (NULL == g_startTimerCond)
729 g_startTimerCond = oc_cond_new();
730 if (NULL == g_startTimerCond)
732 OIC_LOG(ERROR, TAG, "oc_cond_new failed");
733 return CA_STATUS_FAILED;
737 if (NULL == g_scanningTimeCond)
739 g_scanningTimeCond = oc_cond_new();
740 if (NULL == g_scanningTimeCond)
742 OIC_LOG(ERROR, TAG, "oc_cond_new failed");
743 return CA_STATUS_FAILED;
747 if (NULL == g_threadWriteCharacteristicCond)
749 g_threadWriteCharacteristicCond = oc_cond_new();
750 if (NULL == g_threadWriteCharacteristicCond)
752 OIC_LOG(ERROR, TAG, "oc_cond_new failed");
753 return CA_STATUS_FAILED;
757 OIC_LOG(DEBUG, TAG, "OUT");
761 void CATerminateGattClientMutexVariables()
763 OIC_LOG(DEBUG, TAG, "IN");
765 oc_mutex_free(g_LEClientStateMutex);
766 g_LEClientStateMutex = NULL;
768 oc_mutex_free(g_LEServerListMutex);
769 g_LEServerListMutex = NULL;
771 oc_mutex_free(g_LEReqRespClientCbMutex);
772 g_LEReqRespClientCbMutex = NULL;
774 oc_mutex_free(g_LEClientConnectMutex);
775 g_LEClientConnectMutex = NULL;
777 oc_mutex_free(g_LEClientThreadPoolMutex);
778 g_LEClientThreadPoolMutex = NULL;
780 oc_mutex_free(g_multicastDataListMutex);
781 g_multicastDataListMutex = NULL;
783 oc_mutex_free(g_deviceDiscoveredListMutex);
784 g_deviceDiscoveredListMutex = NULL;
786 oc_mutex_free(g_threadWriteCharacteristicMutex);
787 g_threadWriteCharacteristicMutex = NULL;
789 oc_cond_free(g_startTimerCond);
790 g_startTimerCond = NULL;
792 oc_cond_free(g_scanningTimeCond);
793 g_scanningTimeCond = NULL;
795 oc_cond_free(g_threadWriteCharacteristicCond);
796 g_threadWriteCharacteristicCond = NULL;
797 g_isSignalSetFlag = false;
799 OIC_LOG(DEBUG, TAG, "OUT");
802 CAResult_t CALEGattSetCallbacks()
804 OIC_LOG(DEBUG, TAG, "IN");
806 OIC_LOG(DEBUG, TAG, "OUT");
810 void CALEGattUnSetCallbacks()
812 OIC_LOG(DEBUG, TAG, "IN");
814 int numOfServersConnected = CAGetRegisteredServiceCount();
815 LEServerInfo *leServerInfo = NULL;
817 for (int32_t index = 0; index < numOfServersConnected; index++)
819 CAGetLEServerInfoByPosition(g_LEServerList, index, &leServerInfo);
820 bt_gatt_client_unset_characteristic_value_changed_cb(leServerInfo->readChar);
822 OIC_LOG(DEBUG, TAG, "OUT");
825 CAResult_t CALEGattStartDeviceScanning()
827 OIC_LOG(DEBUG, TAG, "IN");
829 int ret = bt_adapter_le_start_scan(CALEAdapterScanResultCb, NULL);
830 if(BT_ERROR_NONE != ret)
832 OIC_LOG_V(ERROR, TAG, "bt_adapter_le_start_scan failed[%s]",
833 CALEGetErrorMsg(ret));
834 return CA_STATUS_FAILED;
837 OIC_LOG(DEBUG, TAG, "OUT");
841 void CALEGattStopDeviceScanning()
843 OIC_LOG(DEBUG, TAG, "IN");
845 int ret = bt_adapter_le_stop_scan();
846 if (BT_ERROR_NONE != ret)
848 OIC_LOG_V(ERROR, TAG, "bt_adapter_le_stop_scan failed[%s]",
849 CALEGetErrorMsg(ret));
852 OIC_LOG(DEBUG, TAG, "OUT");
855 void CAGattConnectThread (void *remoteAddress)
857 OIC_LOG(DEBUG, TAG, "IN ");
859 VERIFY_NON_NULL_VOID(remoteAddress, TAG, "remote address is NULL");
861 char *address = (char *)remoteAddress;
863 OIC_LOG_V(DEBUG, TAG, "remote address is [%s]", address);
865 CAResult_t result = CALEGattConnect(address);
867 if (CA_STATUS_OK != result)
869 OIC_LOG_V(ERROR, TAG, "bt_gatt_connect failed for [%s]", address);
874 OIC_LOG(DEBUG, TAG, "OUT");
877 CAResult_t CALEGattConnect(const char *remoteAddress)
879 OIC_LOG(DEBUG, TAG, "IN");
881 VERIFY_NON_NULL_RET(remoteAddress, TAG,
882 "remote address is NULL", CA_STATUS_FAILED);
884 oc_mutex_lock(g_LEClientConnectMutex);
885 bool isConnected = false;
886 int ret = bt_device_is_profile_connected(remoteAddress, BT_PROFILE_GATT, &isConnected);
887 if (BT_ERROR_NONE != ret)
889 OIC_LOG_V(ERROR, TAG, "bt_device_is_profile_connected Failed with ret value [%s] ",
890 CALEGetErrorMsg(ret));
891 oc_mutex_unlock(g_LEClientConnectMutex);
892 return CA_STATUS_FAILED;
895 CAResult_t result = CA_STATUS_OK;
898 ret = bt_gatt_connect(remoteAddress, true);
900 if (BT_ERROR_NONE != ret)
902 OIC_LOG_V(ERROR, TAG, "bt_gatt_connect Failed with ret value [%s] ",
903 CALEGetErrorMsg(ret));
904 oc_mutex_unlock(g_LEClientConnectMutex);
905 return CA_STATUS_FAILED;
910 OIC_LOG_V(INFO, TAG, "Remote address[%s] is already connected",
912 char *addr = OICStrdup(remoteAddress);
915 OIC_LOG(ERROR, TAG, "addr is NULL");
916 oc_mutex_unlock(g_LEClientConnectMutex);
917 return CA_STATUS_FAILED;
920 oc_mutex_lock(g_LEClientThreadPoolMutex);
921 if (NULL == g_LEClientThreadPool)
923 OIC_LOG(ERROR, TAG, "g_LEClientThreadPool is NULL");
925 oc_mutex_unlock(g_LEClientThreadPoolMutex);
926 oc_mutex_unlock(g_LEClientConnectMutex);
927 return CA_STATUS_FAILED;
930 result = ca_thread_pool_add_task(g_LEClientThreadPool, CADiscoverLEServicesThread,
932 if (CA_STATUS_OK != result)
934 OIC_LOG_V(ERROR, TAG, "ca_thread_pool_add_task failed with ret [%d]", result);
937 oc_mutex_unlock(g_LEClientThreadPoolMutex);
939 oc_mutex_unlock(g_LEClientConnectMutex);
941 OIC_LOG(DEBUG, TAG, "OUT");
945 CAResult_t CALEGattDisConnect(const char *remoteAddress)
947 OIC_LOG(DEBUG, TAG, "IN");
949 VERIFY_NON_NULL_RET(remoteAddress, TAG,
950 "remote address is NULL", CA_STATUS_FAILED);
952 int ret = bt_gatt_disconnect(remoteAddress);
954 if (BT_ERROR_NONE != ret)
956 OIC_LOG_V(ERROR, TAG, "bt_gatt_disconnect Failed with ret value [%s] ",
957 CALEGetErrorMsg(ret));
958 return CA_STATUS_FAILED;
961 OIC_LOG(DEBUG, TAG, "OUT");
965 void CADiscoverLEServicesThread (void *remoteAddress)
967 OIC_LOG(DEBUG, TAG, "IN");
969 VERIFY_NON_NULL_VOID(remoteAddress, TAG, "remote address is NULL");
971 char *address = (char *)remoteAddress;
973 CAResult_t result = CALEGattDiscoverServices(address);
974 if (CA_STATUS_OK != result)
976 OIC_LOG(ERROR, TAG, "CALEGattDiscoverServices failed");
980 OIC_LOG(DEBUG, TAG, "OUT");
983 CAResult_t CALEGattDiscoverServices(const char *remoteAddress)
985 OIC_LOG(DEBUG, TAG, "IN");
987 VERIFY_NON_NULL_RET(remoteAddress, TAG,
988 "remote address is NULL", CA_STATUS_FAILED);
990 LEServerInfo *leServerInfo = NULL;
991 CAResult_t result = CA_STATUS_FAILED;
993 oc_mutex_lock(g_LEServerListMutex);
994 result = CAGetLEServerInfo(g_LEServerList, remoteAddress, &leServerInfo);
995 oc_mutex_unlock(g_LEServerListMutex);
997 if (CA_STATUS_OK == result)
999 OIC_LOG_V(INFO, TAG, "Device[%s] is already discovered", leServerInfo->remoteAddress);
1001 // Send the data of pending multicast data list if any.
1002 if (g_multicastDataList)
1004 oc_mutex_lock(g_multicastDataListMutex);
1005 uint32_t arrayLength = u_arraylist_length(g_multicastDataList);
1006 for (uint32_t i = 0; i < arrayLength; i++)
1008 CALEData_t *multicastData = u_arraylist_get(g_multicastDataList, i);
1009 if (NULL == multicastData)
1011 OIC_LOG(DEBUG, TAG, "multicastData is NULL");
1014 CAUpdateCharacteristicsToGattServer(remoteAddress, multicastData->data,
1015 multicastData->dataLen, LE_UNICAST, 0);
1017 oc_mutex_unlock(g_multicastDataListMutex);
1020 OIC_LOG(DEBUG, TAG, "OUT");
1021 return CA_STATUS_OK;
1025 OIC_LOG_V(INFO, TAG, "CAGetLEServerInfo [%s] is failed, %d", remoteAddress, result);
1028 bt_gatt_client_h clientHandle = NULL;
1029 int32_t ret = bt_gatt_client_create(remoteAddress, &clientHandle);
1030 if (BT_ERROR_NONE != ret || NULL == clientHandle)
1032 OIC_LOG_V(ERROR, TAG,
1033 "bt_gatt_client_create Failed with ret value [%s] ", CALEGetErrorMsg(ret));
1034 return CA_STATUS_FAILED;
1037 bt_gatt_h serviceHandle = NULL;
1038 ret = bt_gatt_client_get_service(clientHandle, CA_GATT_SERVICE_UUID, &serviceHandle);
1039 if (BT_ERROR_NONE != ret || NULL == serviceHandle)
1041 OIC_LOG_V(ERROR, TAG,
1042 "bt_gatt_client_get_service Failed with ret value [%s] ", CALEGetErrorMsg(ret));
1043 bt_gatt_client_destroy(clientHandle);
1044 return CA_STATUS_FAILED;
1047 // Server will read data on this characteristic.
1048 bt_gatt_h writeChrHandle = NULL;
1049 ret = bt_gatt_service_get_characteristic(serviceHandle, CA_GATT_REQUEST_CHRC_UUID,
1051 if (BT_ERROR_NONE != ret || NULL == writeChrHandle)
1053 OIC_LOG_V(ERROR, TAG,
1054 "bt_gatt_service_get_characteristic Failed with ret value [%s] ",
1055 CALEGetErrorMsg(ret));
1056 bt_gatt_client_destroy(clientHandle);
1057 CALEGattDisConnect(remoteAddress);
1058 return CA_STATUS_FAILED;
1061 // Server will notify data on this characteristic.
1062 bt_gatt_h readChrHandle = NULL;
1063 ret = bt_gatt_service_get_characteristic(serviceHandle, CA_GATT_RESPONSE_CHRC_UUID,
1065 if (BT_ERROR_NONE != ret || NULL == readChrHandle)
1067 OIC_LOG_V(ERROR, TAG,
1068 "bt_gatt_service_get_characteristic Failed with ret value [%s] ",
1069 CALEGetErrorMsg(ret));
1070 bt_gatt_client_destroy(clientHandle);
1071 CALEGattDisConnect(remoteAddress);
1072 return CA_STATUS_FAILED;
1076 //TODO: This data has to be freed while unsetting the callback.
1077 char *addr = OICStrdup(remoteAddress);
1080 OIC_LOG(ERROR, TAG, "addr is NULL");
1081 bt_gatt_client_destroy(clientHandle);
1082 CALEGattDisConnect(remoteAddress);
1083 return CA_STATUS_FAILED;
1086 ret = bt_gatt_client_set_characteristic_value_changed_cb(readChrHandle,
1087 CALEGattCharacteristicChangedCb,
1089 if (BT_ERROR_NONE != ret)
1091 OIC_LOG_V(ERROR, TAG,
1092 "bt_gatt_client_set_characteristic_value_changed_cb Failed with ret value [%s]",
1093 CALEGetErrorMsg(ret));
1094 bt_gatt_client_destroy(clientHandle);
1095 CALEGattDisConnect(remoteAddress);
1096 return CA_STATUS_FAILED;
1099 LEServerInfo *serverInfo = (LEServerInfo *)OICCalloc(1, sizeof(LEServerInfo));
1100 if (NULL == serverInfo)
1102 OIC_LOG(ERROR, TAG, "Malloc failed");
1103 CALEGattDisConnect(remoteAddress);
1104 return CA_MEMORY_ALLOC_FAILED;
1106 serverInfo->clientHandle = clientHandle;
1107 serverInfo->serviceHandle = serviceHandle;
1108 serverInfo->readChar = readChrHandle;
1109 serverInfo->writeChar = writeChrHandle;
1110 serverInfo->remoteAddress = OICStrdup(remoteAddress);
1112 oc_mutex_lock(g_LEServerListMutex);
1113 result = CAAddLEServerInfoToList(&g_LEServerList, serverInfo);
1114 if (CA_STATUS_OK != result)
1116 OIC_LOG(ERROR, TAG, "CAAddLEServerInfoToList failed");
1117 bt_gatt_client_destroy(clientHandle);
1118 CALEGattDisConnect(remoteAddress);
1119 return CA_STATUS_FAILED;
1121 oc_mutex_unlock(g_LEServerListMutex);
1123 oc_mutex_lock(g_deviceDiscoveredListMutex);
1124 // Add the the device Discovered list.
1125 if (NULL == g_deviceDiscoveredList)
1127 g_deviceDiscoveredList = u_arraylist_create();
1129 char *deviceAddr = OICStrdup(remoteAddress);
1130 if (NULL == deviceAddr)
1132 OIC_LOG_V(ERROR, TAG, "Device address is NULL");
1133 oc_mutex_unlock(g_deviceDiscoveredListMutex);
1134 return CA_STATUS_FAILED;
1136 u_arraylist_add(g_deviceDiscoveredList, (void *) deviceAddr);
1137 oc_mutex_unlock(g_deviceDiscoveredListMutex);
1139 // Send the data of pending multicast data list if any.
1140 if (g_multicastDataList)
1142 oc_mutex_lock(g_multicastDataListMutex);
1143 uint32_t arrayLength = u_arraylist_length(g_multicastDataList);
1144 for (uint32_t i = 0; i < arrayLength; i++)
1146 CALEData_t *multicastData = u_arraylist_get(g_multicastDataList, i);
1147 if (NULL == multicastData)
1149 OIC_LOG(DEBUG, TAG, "multicastData is NULL");
1152 CAUpdateCharacteristicsToGattServer(remoteAddress, multicastData->data,
1153 multicastData->dataLen, LE_UNICAST, 0);
1155 oc_mutex_unlock(g_multicastDataListMutex);
1158 OIC_LOG(DEBUG, TAG, "OUT");
1159 return CA_STATUS_OK;
1162 CAResult_t CAUpdateCharacteristicsToGattServer(const char *remoteAddress,
1163 const uint8_t *data, const uint32_t dataLen,
1164 CALETransferType_t type, const int32_t position)
1166 OIC_LOG(DEBUG, TAG, "IN");
1168 VERIFY_NON_NULL(data, TAG, "data is NULL");
1172 OIC_LOG(ERROR, TAG, "dataLen is less than or equal zero. Invalid input!");
1173 return CA_STATUS_INVALID_PARAM;
1176 LEServerInfo *leServerInfo = NULL;
1177 CAResult_t ret = CA_STATUS_FAILED;
1179 oc_mutex_lock(g_LEServerListMutex);
1180 if (LE_UNICAST == type)
1182 ret = CAGetLEServerInfo(g_LEServerList, remoteAddress, &leServerInfo);
1184 else if (LE_MULTICAST == type)
1186 ret = CAGetLEServerInfoByPosition(g_LEServerList, position, &leServerInfo);
1188 oc_mutex_unlock(g_LEServerListMutex);
1190 if (CA_STATUS_OK != ret)
1192 OIC_LOG(ERROR, TAG, "CAGetBLEServiceInfoByPosition is failed");
1193 return CA_STATUS_FAILED;
1196 VERIFY_NON_NULL(leServerInfo, TAG, "bleServiceInfo is NULL");
1198 OIC_LOG_V(DEBUG, TAG, "Updating the data of length [%d] to [%s] ", dataLen,
1199 leServerInfo->remoteAddress);
1201 int result = bt_gatt_set_value(leServerInfo->writeChar, (char *)data, dataLen);
1203 if (BT_ERROR_NONE != result)
1205 OIC_LOG_V(ERROR, TAG,
1206 "bt_gatt_set_value Failed with return val [%s]",
1207 CALEGetErrorMsg(result));
1208 return CA_STATUS_FAILED;
1211 result = bt_gatt_client_write_value(leServerInfo->writeChar, CALEGattCharacteristicWriteCb,
1213 if (BT_ERROR_NONE != result)
1215 OIC_LOG_V(ERROR, TAG,
1216 "bt_gatt_client_write_value Failed with return val [%s]",
1217 CALEGetErrorMsg(result));
1218 return CA_STATUS_FAILED;
1221 // wait for callback for write Characteristic with success to sent data
1222 OIC_LOG_V(DEBUG, TAG, "callback flag is %d", g_isSignalSetFlag);
1223 oc_mutex_lock(g_threadWriteCharacteristicMutex);
1224 if (!g_isSignalSetFlag)
1226 OIC_LOG(DEBUG, TAG, "wait for callback to notify writeCharacteristic is success");
1227 if (OC_WAIT_SUCCESS != oc_cond_wait_for(g_threadWriteCharacteristicCond,
1228 g_threadWriteCharacteristicMutex,
1229 WAIT_TIME_WRITE_CHARACTERISTIC))
1231 OIC_LOG(ERROR, TAG, "there is no response. write has failed");
1232 g_isSignalSetFlag = false;
1233 oc_mutex_unlock(g_threadWriteCharacteristicMutex);
1234 return CA_SEND_FAILED;
1237 // reset flag set by writeCharacteristic Callback
1238 g_isSignalSetFlag = false;
1239 oc_mutex_unlock(g_threadWriteCharacteristicMutex);
1241 OIC_LOG(DEBUG, TAG, "OUT");
1242 return CA_STATUS_OK;
1245 CAResult_t CAUpdateCharacteristicsToAllGattServers(const uint8_t *data, uint32_t dataLen)
1247 OIC_LOG(DEBUG, TAG, "IN");
1249 VERIFY_NON_NULL(data, TAG, "data is NULL");
1253 OIC_LOG(ERROR, TAG, "dataLen is less than or equal zero. Invalid input !");
1254 return CA_STATUS_INVALID_PARAM;
1257 int numOfServersConnected = CAGetRegisteredServiceCount();
1259 // Send data to already connected devices.
1260 for (int32_t pos = 0; pos < numOfServersConnected; pos++)
1262 /*remoteAddress will be NULL.
1263 Since we have to send to all destinations. pos will be used for getting remote address.
1265 int32_t ret = CAUpdateCharacteristicsToGattServer(NULL, data, dataLen, LE_MULTICAST, pos);
1267 if (CA_STATUS_OK != ret)
1269 OIC_LOG_V(ERROR, TAG,
1270 "CAUpdateCharacteristicsToGattServer Failed with return val [%d] ", ret);
1271 g_clientErrorCallback(NULL, data, dataLen, ret);
1275 // Add the data to pending list.
1276 CALEData_t *multicastData = (CALEData_t *)OICCalloc(1, sizeof(CALEData_t));
1277 if (NULL == multicastData)
1279 OIC_LOG(ERROR, TAG, "Calloc failed");
1282 multicastData->data = OICCalloc(1, dataLen);
1283 if (NULL == multicastData->data)
1285 OIC_LOG(ERROR, TAG, "Calloc failed");
1288 memcpy(multicastData->data, data, dataLen);
1289 multicastData->dataLen = dataLen;
1291 oc_mutex_lock(g_multicastDataListMutex);
1292 if (NULL == g_multicastDataList)
1294 g_multicastDataList = u_arraylist_create();
1296 u_arraylist_add(g_multicastDataList, (void *)multicastData);
1297 oc_mutex_unlock(g_multicastDataListMutex);
1299 // Start the scanning.
1300 CAResult_t result = CALEGattStartDeviceScanning();
1301 if (CA_STATUS_OK != result)
1303 OIC_LOG(ERROR, TAG, "CALEGattStartDeviceDiscovery Failed");
1307 // Start the timer by signalling it.
1308 oc_cond_signal(g_startTimerCond);
1311 OIC_LOG(DEBUG, TAG, "OUT ");
1312 return CA_STATUS_OK;
1315 bool CALEClientIsConnected(const char* address)
1322 uint16_t CALEClientGetMtuSize(const char* address)
1324 VERIFY_NON_NULL_RET(address, TAG, "address is null", CA_DEFAULT_BLE_MTU_SIZE);
1326 //it should be implemented after update Tizen 3.0
1327 return CA_DEFAULT_BLE_MTU_SIZE;
1330 CAResult_t CALEClientSetMtuSize(const char* address, uint16_t mtuSize)
1334 VERIFY_NON_NULL(address, TAG, "address is null");
1336 //it should be implemented after update Tizen 3.0
1337 return CA_NOT_SUPPORTED;
1340 CAResult_t CALEClientSendNegotiationMessage(const char* address)
1342 OIC_LOG_V(DEBUG, TAG, "CALEClientSendNegotiationMessage(%s)", address);
1344 //it will be implemented when tizen public 3.0 is released.
1345 return CA_NOT_SUPPORTED;