2 * ******************************************************************
4 * Copyright 2016 Samsung Electronics All Rights Reserved.
6 * -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
20 * -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
23 package org.iotivity.base.examples;
25 import android.app.Activity;
26 import android.app.Fragment;
27 import android.bluetooth.BluetoothAdapter;
28 import android.bluetooth.BluetoothDevice;
29 import android.bluetooth.BluetoothGatt;
30 import android.bluetooth.BluetoothManager;
31 import android.bluetooth.le.BluetoothLeScanner;
32 import android.bluetooth.le.ScanCallback;
33 import android.bluetooth.le.ScanFilter;
34 import android.bluetooth.le.ScanResult;
35 import android.bluetooth.le.ScanSettings;
36 import android.content.Context;
37 import android.content.Intent;
38 import android.content.pm.PackageManager;
39 import android.os.Build;
40 import android.os.Bundle;
41 import android.os.Handler;
42 import android.os.ParcelUuid;
43 import android.util.Log;
44 import android.view.LayoutInflater;
45 import android.view.View;
46 import android.view.ViewGroup;
47 import android.widget.AdapterView;
48 import android.widget.ArrayAdapter;
49 import android.widget.Button;
50 import android.widget.ListView;
52 import org.iotivity.base.ModeType;
53 import org.iotivity.base.OcConnectivityType;
54 import org.iotivity.base.OcException;
55 import org.iotivity.base.OcPlatform;
56 import org.iotivity.base.OcResource;
57 import org.iotivity.base.PlatformConfig;
58 import org.iotivity.base.QualityOfService;
59 import org.iotivity.base.ServiceType;
60 import org.iotivity.ca.CaBtPairingInterface;
61 import org.iotivity.ca.CaInterface;
63 import java.util.ArrayList;
64 import java.util.EnumSet;
65 import java.util.List;
68 * This class is for testing of Bluetooth util.
70 public class BluetoothFragment extends Fragment implements
71 CaInterface.OnBtDeviceFoundListener,
72 CaInterface.OnConnectionManagerStateListener {
74 private static final String TAG = "OCF_SIMPLE_BLUETOOTH";
75 private static final String CA_GATT_SERVICE_UUID = "ADE3D529-C784-4F63-A987-EB69F70EE816";
77 private Activity mActivity;
78 private Context mContext;
79 private BluetoothAdapter mBluetoothAdapter;
80 private static final int REQUEST_ENABLE_BT = 1;
81 private static final long SCAN_PERIOD = 10000;
82 private BluetoothLeScanner mLEScanner;
83 private ScanSettings mScanSettings;
84 private List<ScanFilter> mScanFilters;
85 private BluetoothGatt mGatt;
86 private ArrayList<String> mItems;
87 private ArrayList<BluetoothDevice> mBluetoothDevices;
88 private ArrayAdapter<String> mAdapters;
90 private boolean mIsScanning;
91 private boolean mIsBTSelected;
93 private Button mBtButton;
94 private Button mLeButton;
97 public View onCreateView(LayoutInflater inflater, ViewGroup container,
98 Bundle savedInstanceState) {
99 View rootView = inflater.inflate(R.layout.fragment_bluetooth, container, false);
100 mBtButton = (Button) rootView.findViewById(R.id.btn_bt);
101 mBtButton.setOnClickListener(scanButtonListener(true));
103 mLeButton = (Button) rootView.findViewById(R.id.btn_le);
104 mLeButton.setOnClickListener(scanButtonListener(false));
106 ListView listView = (ListView) rootView.findViewById(R.id.list_view);
107 mItems = new ArrayList<String>();
108 mAdapters = new ArrayAdapter<String>(mActivity, android.R.layout.simple_list_item_1, mItems);
109 listView.setAdapter(mAdapters);
110 listView.setOnItemClickListener(itemClickListener);
111 listView.setOnItemLongClickListener(itemLongClickListener);
117 public void onCreate(Bundle savedInstanceState) {
118 super.onCreate(savedInstanceState);
119 mActivity = getActivity();
120 mContext = mActivity.getBaseContext();
122 mBluetoothDevices = new ArrayList<BluetoothDevice>();
124 if (!mActivity.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
125 Common.showToast(mContext, "BLE Not Supported");
127 final BluetoothManager bluetoothManager = (BluetoothManager) mActivity
128 .getSystemService(Context.BLUETOOTH_SERVICE);
129 mBluetoothAdapter = bluetoothManager.getAdapter();
131 PlatformConfig cfg = new PlatformConfig(mActivity, mContext,
136 QualityOfService.LOW);
138 OcPlatform.Configure(cfg);
139 CaInterface.startBtPairingService(mContext, this);
140 CaInterface.startManagerService(mContext, this);
144 public void onResume() {
146 if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
147 Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
148 startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
150 if (Build.VERSION.SDK_INT >= 21) {
151 mLEScanner = mBluetoothAdapter.getBluetoothLeScanner();
152 if (mScanSettings == null) {
153 mScanSettings = new ScanSettings.Builder()
154 .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
158 if (mScanFilters == null) {
159 mScanFilters = new ArrayList<ScanFilter>();
160 ScanFilter scanFilter = new ScanFilter.Builder()
161 .setServiceUuid(ParcelUuid.fromString(CA_GATT_SERVICE_UUID)).build();
162 mScanFilters.add(scanFilter);
169 public void onPause() {
171 if (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()) {
177 public void onDestroy() {
179 CaInterface.stopBtPairingService();
180 CaInterface.stopManagerService();
188 public void onActivityResult(int requestCode, int resultCode, Intent data) {
189 if (requestCode == REQUEST_ENABLE_BT) {
190 if (resultCode == Activity.RESULT_CANCELED) {
195 super.onActivityResult(requestCode, resultCode, data);
198 View.OnClickListener scanButtonListener(final boolean isBT) {
199 return new View.OnClickListener() {
201 public void onClick(View view) {
204 mBluetoothDevices.clear();
205 mAdapters.notifyDataSetChanged();
206 mIsBTSelected = isBT;
213 CaInterface.stopScan();
214 } catch (OcException e) {
217 mBtButton.setText(R.string.bt_scan);
218 mLeButton.setVisibility(View.VISIBLE);
222 CaInterface.startScan();
223 } catch (OcException e) {
226 mBtButton.setText(R.string.stop_scan);
227 mLeButton.setVisibility(View.GONE);
232 mLeButton.setText(R.string.le_scan);
233 mBtButton.setVisibility(View.VISIBLE);
236 mLeButton.setText(R.string.stop_scan);
237 mBtButton.setVisibility(View.GONE);
239 scanLeDevice(!mIsScanning);
241 mIsScanning = !mIsScanning;
247 public synchronized void onBtDeviceFound(BluetoothDevice device) throws OcException {
248 Log.i(TAG, "onBtDeviceFound address : " + device.getAddress());
250 addItemToList(device);
253 private AdapterView.OnItemClickListener itemClickListener = new AdapterView
254 .OnItemClickListener() {
255 public void onItemClick(AdapterView<?> adapterView, View clickedView, int pos, long id) {
256 StringBuilder sb = new StringBuilder();
259 sb.append("Pairing with : ");
261 CaInterface.createBond(mBluetoothDevices.get(pos));
262 } catch (OcException e) {
266 sb.append("Set Connect with : ");
268 final String address = mBluetoothDevices.get(pos).getAddress();
269 CaInterface.setAutoConnectionDevice(address);
270 OcPlatform.OnResourceFoundListener resourceFoundListener =
271 new OcPlatform.OnResourceFoundListener() {
273 public void onResourceFound(OcResource ocResource) {
274 Log.i(TAG, "onResourceFound : " + ocResource.getUri());
278 public void onFindResourceFailed(Throwable throwable, String uri) {
279 Log.i(TAG, "findResource request has failed");
280 Log.e(TAG, throwable.toString());
283 OcPlatform.findResource("", address + OcPlatform.WELL_KNOWN_QUERY,
284 EnumSet.of(OcConnectivityType.CT_ADAPTER_GATT_BTLE),
285 resourceFoundListener, QualityOfService.LOW);
286 } catch (OcException e) {
290 Common.showToast(mContext, sb.append(mItems.get(pos)).toString());
294 private AdapterView.OnItemLongClickListener itemLongClickListener = new AdapterView
295 .OnItemLongClickListener() {
297 public boolean onItemLongClick(AdapterView<?> adapterView, View view, int pos, long id) {
298 StringBuilder sb = new StringBuilder();
300 if (!mIsBTSelected) {
301 sb.append("Unset Connect with : ");
303 CaInterface.unsetAutoConnectionDevice(mBluetoothDevices.get(pos).getAddress());
304 } catch (OcException e) {
308 Common.showToast(mContext, sb.append(mItems.get(pos)).toString());
314 private void scanLeDevice(final boolean enable) {
316 new Handler().postDelayed(new Runnable() {
319 mLEScanner.stopScan(mScanCallback);
323 mLEScanner.startScan(mScanFilters, mScanSettings, mScanCallback);
325 mLEScanner.stopScan(mScanCallback);
329 private ScanCallback mScanCallback = new ScanCallback() {
331 public void onScanResult(int callbackType, ScanResult result) {
332 Log.i(TAG, "onScanResult : " + result.toString());
334 addItemToList(result.getDevice());
338 public void onScanFailed(int errorCode) {
339 Log.e(TAG, "Scan Failed, Error Code : " + errorCode);
343 private void addItemToList(BluetoothDevice btDevice) {
344 StringBuilder sb = new StringBuilder(btDevice.toString());
346 if (btDevice.getName() != null) {
347 sb.append(btDevice.getName().toString());
353 if (mItems.contains(sb.toString())) {
357 mItems.add(sb.toString());
358 mBluetoothDevices.add(btDevice);
359 mAdapters.notifyDataSetChanged();
364 public void onAdapterStateChanged(OcConnectivityType type, boolean enabled) {
365 final String msg = getString(R.string.action_onadapterstatechanged) + enabled;
367 mActivity.runOnUiThread(new Runnable() {
370 Common.showToast(mContext, msg);
376 public void onConnectionStateChanged(OcConnectivityType type,
377 String address, boolean connected) {
378 Log.i(TAG, "onConnectionStateChanged address: " + address);
379 final String msg = getString(R.string.action_onconnectionstatechanged) + connected;
381 mActivity.runOnUiThread(new Runnable() {
384 Common.showToast(mContext, msg);