aboutsummaryrefslogtreecommitdiff
path: root/TrustAgent/src
diff options
context:
space:
mode:
authorHongwei Wang <hwwang@google.com>2018-03-05 14:53:21 -0800
committerHongwei Wang <hwwang@google.com>2018-03-05 16:41:59 -0800
commitf62d655edb8b017f993c919bb2abe177bfcac410 (patch)
tree5324673aacd36e498fca68bf59093eb2ec96fca3 /TrustAgent/src
parentef7ed130d56c70bcc08da3aeeebc025eca24e791 (diff)
downloadCar-f62d655edb8b017f993c919bb2abe177bfcac410.tar.gz
Removes the client portion of CarTrustAgent
Bug: 74193712 Test: run on Mojave Change-Id: I2f0ea08c148551cc336c8429e5a33fe94e1477c5
Diffstat (limited to 'TrustAgent/src')
-rw-r--r--TrustAgent/src/com/android/car/trust/CarBleTrustAgent.java102
-rw-r--r--TrustAgent/src/com/android/car/trust/CarEnrolmentActivity.java192
-rw-r--r--TrustAgent/src/com/android/car/trust/CarEnrolmentService.java15
-rw-r--r--TrustAgent/src/com/android/car/trust/CarUnlockService.java1
-rw-r--r--TrustAgent/src/com/android/car/trust/MainActivity.java94
-rw-r--r--TrustAgent/src/com/android/car/trust/PhoneEnrolmentActivity.java52
-rw-r--r--TrustAgent/src/com/android/car/trust/PhoneEnrolmentController.java209
-rw-r--r--TrustAgent/src/com/android/car/trust/PhoneUnlockActivity.java46
-rw-r--r--TrustAgent/src/com/android/car/trust/PhoneUnlockController.java174
-rw-r--r--TrustAgent/src/com/android/car/trust/comms/SimpleBleClient.java380
-rw-r--r--TrustAgent/src/com/android/car/trust/comms/SimpleBleServer.java202
-rw-r--r--TrustAgent/src/com/android/car/trust/comms/Utils.java (renamed from TrustAgent/src/com/android/car/trust/Utils.java)12
12 files changed, 244 insertions, 1235 deletions
diff --git a/TrustAgent/src/com/android/car/trust/CarBleTrustAgent.java b/TrustAgent/src/com/android/car/trust/CarBleTrustAgent.java
index 997f02856e..5094c0b61e 100644
--- a/TrustAgent/src/com/android/car/trust/CarBleTrustAgent.java
+++ b/TrustAgent/src/com/android/car/trust/CarBleTrustAgent.java
@@ -59,7 +59,6 @@ public class CarBleTrustAgent extends TrustAgentService {
public static final String INTENT_EXTRA_TOKEN_HANDLE = "extra-token-handle";
public static final String INTENT_EXTRA_TOKEN_STATUS = "extra-token-status";
-
private static final String TAG = "CarBleTrustAgent";
private static final long TRUST_DURATION_MS = TimeUnit.MINUTES.toMicros(5);
@@ -94,6 +93,53 @@ public class CarBleTrustAgent extends TrustAgentService {
}
};
+ private final SimpleBleServer.ConnectionCallback mConnectionCallback
+ = new SimpleBleServer.ConnectionCallback() {
+ @Override
+ public void onServerStarted() {
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "BLE server started");
+ }
+ }
+
+ @Override
+ public void onServerStartFailed(int errorCode) {
+ Log.w(TAG, "BLE server failed to start. Error Code: " + errorCode);
+ }
+
+ @Override
+ public void onDeviceConnected(BluetoothDevice device) {
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "BLE device connected. Name: " + device.getName()
+ + " Address: " + device.getAddress());
+ }
+ }
+ };
+
+ private final ServiceConnection mServiceConnection = new ServiceConnection() {
+ @Override
+ public void onServiceConnected(ComponentName className, IBinder service) {
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "CarUnlockService connected");
+ }
+
+ mBleServiceBound = true;
+ CarUnlockService.UnlockServiceBinder binder
+ = (CarUnlockService.UnlockServiceBinder) service;
+ mCarUnlockService = binder.getService();
+ mCarUnlockService.addUnlockServiceCallback(CarBleTrustAgent.this::unlock);
+ mCarUnlockService.registerConnectionCallback(mConnectionCallback);
+ maybeStartBleUnlockService();
+ }
+
+ @Override
+ public void onServiceDisconnected(ComponentName arg0) {
+ mCarUnlockService = null;
+ mBleServiceBound = false;
+ }
+
+ };
+
@Override
public void onTrustTimeout() {
super.onTrustTimeout();
@@ -146,60 +192,6 @@ public class CarBleTrustAgent extends TrustAgentService {
super.onDestroy();
}
- private SimpleBleServer.ConnectionListener mConnectionListener
- = new SimpleBleServer.ConnectionListener() {
- @Override
- public void onServerStarted() {
- if (Log.isLoggable(TAG, Log.DEBUG)) {
- Log.d(TAG, "BLE server started");
- }
- }
-
- @Override
- public void onServerStartFailed(int errorCode) {
- Log.w(TAG, "BLE server failed to start. Error Code: " + errorCode);
- }
-
- @Override
- public void onDeviceConnected(BluetoothDevice device) {
- if (Log.isLoggable(TAG, Log.DEBUG)) {
- Log.d(TAG, "BLE device connected. Name: " + device.getName()
- + " Address: " + device.getAddress());
- }
- }
- };
-
- private CarUnlockService.UnlockServiceCallback mUnlockCallback
- = new CarUnlockService.UnlockServiceCallback() {
- @Override
- public void unlockDevice(byte[] token, long handle) {
- unlock(token, handle);
- }
- };
-
- private ServiceConnection mServiceConnection = new ServiceConnection() {
-
- public void onServiceConnected(ComponentName className, IBinder service) {
- if (Log.isLoggable(TAG, Log.DEBUG)) {
- Log.d(TAG, "CarUnlockService connected");
- }
-
- mBleServiceBound = true;
- CarUnlockService.UnlockServiceBinder binder
- = (CarUnlockService.UnlockServiceBinder) service;
- mCarUnlockService = binder.getService();
- mCarUnlockService.addUnlockServiceCallback(mUnlockCallback);
- mCarUnlockService.addConnectionListener(mConnectionListener);
- maybeStartBleUnlockService();
- }
-
- public void onServiceDisconnected(ComponentName arg0) {
- mCarUnlockService = null;
- mBleServiceBound = false;
- }
-
- };
-
private void maybeStartBleUnlockService() {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Trying to open a Ble GATT server");
diff --git a/TrustAgent/src/com/android/car/trust/CarEnrolmentActivity.java b/TrustAgent/src/com/android/car/trust/CarEnrolmentActivity.java
index 89e68fe87c..dcf836b755 100644
--- a/TrustAgent/src/com/android/car/trust/CarEnrolmentActivity.java
+++ b/TrustAgent/src/com/android/car/trust/CarEnrolmentActivity.java
@@ -15,6 +15,12 @@
*/
package com.android.car.trust;
+import static com.android.car.trust.CarBleTrustAgent.ACTION_ADD_TOKEN_RESULT;
+import static com.android.car.trust.CarBleTrustAgent.ACTION_TOKEN_STATUS_RESULT;
+import static com.android.car.trust.CarBleTrustAgent.INTENT_EXTRA_TOKEN_HANDLE;
+import static com.android.car.trust.CarBleTrustAgent.INTENT_EXTRA_TOKEN_STATUS;
+
+import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
@@ -24,50 +30,29 @@ import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
+import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
-import android.view.View;
-import android.widget.Button;
import android.widget.TextView;
-import com.android.car.trust.CarEnrolmentService.EnrolmentCallback;
-import com.android.car.trust.comms.SimpleBleServer.ConnectionListener;
-import static com.android.car.trust.CarBleTrustAgent.ACTION_ADD_TOKEN_RESULT;
-import static com.android.car.trust.CarBleTrustAgent.ACTION_TOKEN_STATUS_RESULT;
-import static com.android.car.trust.CarBleTrustAgent.INTENT_EXTRA_TOKEN_HANDLE;
-import static com.android.car.trust.CarBleTrustAgent.INTENT_EXTRA_TOKEN_STATUS;
+import com.android.car.trust.CarEnrolmentService.EnrolmentListener;
+import com.android.car.trust.comms.SimpleBleServer.ConnectionCallback;
/**
* Setup activity that binds {@link CarEnrolmentService} and starts the enrolment process.
*/
public class CarEnrolmentActivity extends Activity {
- private static String TAG = "CarEnrolment";
- private static String SP_HANDLE_KEY = "sp-test";
-
- private TextView mOutputText;
- private TextView mStartButton;
-
- private long mHandle;
-
- private CarEnrolmentService mEnrolmentService;
-
- private BluetoothDevice mDevice;
-
- private boolean mServiceBound;
-
- private LocalBroadcastManager mLocalBroadcastManager;
-
- private SharedPreferences mPrefs;
+ private static final String TAG = "CarEnrolment";
+ private static final String SP_HANDLE_KEY = "sp-test";
+ private static final int FINE_LOCATION_REQUEST_CODE = 42;
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
- intent.getPackage();
-
String action = intent.getAction();
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Received broadcast: " + action);
@@ -79,13 +64,10 @@ public class CarEnrolmentActivity extends Activity {
} else if (ACTION_ADD_TOKEN_RESULT.equals(action)) {
final long handle = intent.getLongExtra(INTENT_EXTRA_TOKEN_HANDLE, -1);
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mPrefs.edit().putLong(SP_HANDLE_KEY, handle).apply();
- if (Log.isLoggable(TAG, Log.DEBUG)) {
- Log.d(TAG, "stored new handle");
- }
+ runOnUiThread(() -> {
+ mPrefs.edit().putLong(SP_HANDLE_KEY, handle).apply();
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "stored new handle");
}
});
@@ -96,66 +78,96 @@ public class CarEnrolmentActivity extends Activity {
}
};
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
-
- setContentView(R.layout.car_client);
- mOutputText = (TextView) findViewById(R.id.textfield);
-
- final Intent intent = new Intent(this, CarEnrolmentService.class);
-
- mPrefs = PreferenceManager.getDefaultSharedPreferences(this /* context */);
-
- IntentFilter filter = new IntentFilter();
- filter.addAction(ACTION_TOKEN_STATUS_RESULT);
- filter.addAction(ACTION_ADD_TOKEN_RESULT);
+ private final ConnectionCallback mConnectionCallback = new ConnectionCallback() {
+ @Override
+ public void onServerStarted() {
+ appendOutputText("Server started");
+ }
- mLocalBroadcastManager = LocalBroadcastManager.getInstance(this /* context */);
- mLocalBroadcastManager.registerReceiver(mReceiver, filter);
+ @Override
+ public void onServerStartFailed(int errorCode) {
+ appendOutputText("Server failed to start, error code: " + errorCode);
+ }
- mStartButton = (Button) findViewById(R.id.start_button);
- mStartButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- // binding the service will start it if not started.
- bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
- }
- });
+ @Override
+ public void onDeviceConnected(BluetoothDevice device) {
+ mDevice = device;
+ appendOutputText("Device connected: " + device.getName()
+ + " addr: " + device.getAddress());
+ }
+ };
- Button revokeButton = (Button) findViewById(R.id.revoke_trust_button);
- revokeButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- Intent intent = new Intent(CarBleTrustAgent.ACTION_REVOKE_TRUST);
- intent.setPackage(getPackageName());
- sendBroadcast(intent);
- }
- });
- }
+ private final EnrolmentListener mEnrolmentListener = (byte[] token) -> {
+ appendOutputText("Enrolment data received ");
+ addEscrowToken(token);
+ };
- private ServiceConnection mServiceConnection = new ServiceConnection() {
+ private final ServiceConnection mServiceConnection = new ServiceConnection() {
+ @Override
public void onServiceConnected(ComponentName className,
IBinder service) {
mServiceBound = true;
CarEnrolmentService.EnrolmentServiceBinder binder
= (CarEnrolmentService.EnrolmentServiceBinder) service;
mEnrolmentService = binder.getService();
- mEnrolmentService.addEnrolmentCallback(mEnrolmentCallback);
- mEnrolmentService.addConnectionListener(mConnectionListener);
+ mEnrolmentService.addEnrolmentCallback(mEnrolmentListener);
+ mEnrolmentService.registerConnectionCallback(mConnectionCallback);
mEnrolmentService.start();
}
+ @Override
public void onServiceDisconnected(ComponentName arg0) {
mEnrolmentService = null;
mServiceBound = false;
}
};
+ private TextView mOutputText;
+ private long mHandle;
+ private CarEnrolmentService mEnrolmentService;
+ private BluetoothDevice mDevice;
+ private boolean mServiceBound;
+ private LocalBroadcastManager mLocalBroadcastManager;
+ private SharedPreferences mPrefs;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+
+ setContentView(R.layout.car_enrolment_activity);
+ mOutputText = findViewById(R.id.textfield);
+ mPrefs = PreferenceManager.getDefaultSharedPreferences(this /* context */);
+
+ IntentFilter filter = new IntentFilter();
+ filter.addAction(ACTION_TOKEN_STATUS_RESULT);
+ filter.addAction(ACTION_ADD_TOKEN_RESULT);
+
+ mLocalBroadcastManager = LocalBroadcastManager.getInstance(this /* context */);
+ mLocalBroadcastManager.registerReceiver(mReceiver, filter);
+
+ findViewById(R.id.start_button).setOnClickListener((view) -> {
+ Intent bindIntent = new Intent(this, CarEnrolmentService.class);
+ bindService(bindIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
+ });
+
+ findViewById(R.id.revoke_trust_button).setOnClickListener((view) -> {
+ Intent revokeIntent = new Intent(CarBleTrustAgent.ACTION_REVOKE_TRUST);
+ revokeIntent.setPackage(getPackageName());
+ sendBroadcast(revokeIntent);
+ });
+ }
+
@Override
- public void onResume() {
+ protected void onResume() {
super.onResume();
+ if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) !=
+ PackageManager.PERMISSION_GRANTED) {
+ requestPermissions(
+ new String[] { android.Manifest.permission.ACCESS_FINE_LOCATION },
+ FINE_LOCATION_REQUEST_CODE);
+ }
+
if (!mPrefs.contains(SP_HANDLE_KEY)) {
appendOutputText("No handles found.");
return;
@@ -174,7 +186,7 @@ public class CarEnrolmentActivity extends Activity {
}
@Override
- public void onDestroy() {
+ protected void onDestroy() {
if (mServiceBound) {
unbindService(mServiceConnection);
}
@@ -182,41 +194,9 @@ public class CarEnrolmentActivity extends Activity {
}
private void appendOutputText(final String text) {
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mOutputText.append("\n" + text);
- }
- });
+ runOnUiThread(() -> mOutputText.append("\n" + text));
}
- private ConnectionListener mConnectionListener = new ConnectionListener() {
- @Override
- public void onServerStarted() {
- appendOutputText("Server started");
- }
-
- @Override
- public void onServerStartFailed(int errorCode) {
- appendOutputText("Server failed to start, error code: " + errorCode);
- }
-
- @Override
- public void onDeviceConnected(BluetoothDevice device) {
- mDevice = device;
- appendOutputText("Device connected: " + device.getName()
- + " addr: " + device.getAddress());
- }
- };
-
- private EnrolmentCallback mEnrolmentCallback = new EnrolmentCallback() {
- @Override
- public void onEnrolmentDataReceived(byte[] token) {
- appendOutputText("Enrolment data received ");
- addEscrowToken(token);
- }
- };
-
private void isTokenActive(long handle) throws RemoteException {
Intent intent = new Intent();
intent.setAction(CarBleTrustAgent.ACTION_IS_TOKEN_ACTIVE);
diff --git a/TrustAgent/src/com/android/car/trust/CarEnrolmentService.java b/TrustAgent/src/com/android/car/trust/CarEnrolmentService.java
index e6bbee2116..18fbf84101 100644
--- a/TrustAgent/src/com/android/car/trust/CarEnrolmentService.java
+++ b/TrustAgent/src/com/android/car/trust/CarEnrolmentService.java
@@ -23,9 +23,12 @@ import android.os.Binder;
import android.os.IBinder;
import android.os.ParcelUuid;
import android.util.Log;
+
import com.android.car.trust.comms.SimpleBleServer;
+import com.android.car.trust.comms.Utils;
import java.util.HashSet;
+import java.util.Set;
import java.util.UUID;
/**
@@ -34,7 +37,7 @@ import java.util.UUID;
public class CarEnrolmentService extends SimpleBleServer {
private static final String TAG = "CarEnrolmentService";
- public interface EnrolmentCallback {
+ public interface EnrolmentListener {
void onEnrolmentDataReceived(byte[] token);
}
@@ -42,14 +45,12 @@ public class CarEnrolmentService extends SimpleBleServer {
private BluetoothGattCharacteristic mEnrolmentEscrowToken;
private BluetoothGattCharacteristic mEnrolmentTokenHandle;
- private HashSet<EnrolmentCallback> mCallbacks;
-
+ private final Set<EnrolmentListener> mEnrolmentListeners = new HashSet<>();
private final IBinder mBinder = new EnrolmentServiceBinder();
@Override
public void onCreate() {
super.onCreate();
- mCallbacks = new HashSet<>();
setupEnrolmentService();
}
@@ -73,7 +74,7 @@ public class CarEnrolmentService extends SimpleBleServer {
Log.d(TAG, "Enrolment token received, value: " + Utils.getLong(value));
}
- for (EnrolmentCallback callback : mCallbacks) {
+ for (EnrolmentListener callback : mEnrolmentListeners) {
callback.onEnrolmentDataReceived(value);
}
}
@@ -85,8 +86,8 @@ public class CarEnrolmentService extends SimpleBleServer {
//Enrolment service should not have any read requests.
}
- public void addEnrolmentCallback(EnrolmentCallback callback) {
- mCallbacks.add(callback);
+ public void addEnrolmentCallback(EnrolmentListener callback) {
+ mEnrolmentListeners.add(callback);
}
public void sendHandle(long handle, BluetoothDevice device) {
diff --git a/TrustAgent/src/com/android/car/trust/CarUnlockService.java b/TrustAgent/src/com/android/car/trust/CarUnlockService.java
index 0c1bc8938a..499238151c 100644
--- a/TrustAgent/src/com/android/car/trust/CarUnlockService.java
+++ b/TrustAgent/src/com/android/car/trust/CarUnlockService.java
@@ -24,6 +24,7 @@ import android.os.IBinder;
import android.os.ParcelUuid;
import android.util.Log;
import com.android.car.trust.comms.SimpleBleServer;
+import com.android.car.trust.comms.Utils;
import java.util.UUID;
diff --git a/TrustAgent/src/com/android/car/trust/MainActivity.java b/TrustAgent/src/com/android/car/trust/MainActivity.java
deleted file mode 100644
index 8c1348bc23..0000000000
--- a/TrustAgent/src/com/android/car/trust/MainActivity.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License
- */
-package com.android.car.trust;
-
-import android.app.Activity;
-import android.content.Intent;
-import android.content.pm.PackageManager;
-import android.os.Bundle;
-import android.view.View;
-import android.widget.Button;
-
-/**
- * Selects whether the device is started as the car or remote device.
- */
-public class MainActivity extends Activity {
- private static final int FINE_LOCATION_REQUEST_CODE = 13;
-
- private Button mCarEnrolmentButton;
- private Button mPhoneEnrolmentButton;
- private Button mPhoneUnlockButton;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main_app);
- mCarEnrolmentButton = (Button) findViewById(R.id.car_button);
- mPhoneEnrolmentButton = (Button) findViewById(R.id.phone_enrolment_button);
- mPhoneUnlockButton = (Button) findViewById(R.id.phone_unlock_button);
-
- mCarEnrolmentButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- Intent intent = new Intent(MainActivity.this /* context */,
- CarEnrolmentActivity.class);
- startActivity(intent);
- }
- });
-
- mPhoneEnrolmentButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- Intent intent = new Intent(MainActivity.this /* context */,
- PhoneEnrolmentActivity.class);
- startActivity(intent);
- }
- });
-
- mPhoneUnlockButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- Intent intent = new Intent(MainActivity.this /* context */,
- PhoneUnlockActivity.class);
- startActivity(intent);
- }
- });
-
- if (!checkPermissionGranted()) {
- requestPermissions(new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
- FINE_LOCATION_REQUEST_CODE);
- // If location access isn't granted, BLE scanning will fail.
- mCarEnrolmentButton.setEnabled(false);
- mPhoneEnrolmentButton.setEnabled(false);
- mPhoneUnlockButton.setEnabled(false);
- }
- }
-
- @Override
- public void onRequestPermissionsResult(int requestCode,
- String permissions[], int[] grantResults) {
- if (requestCode == FINE_LOCATION_REQUEST_CODE && checkPermissionGranted()) {
- mCarEnrolmentButton.setEnabled(true);
- mPhoneEnrolmentButton.setEnabled(true);
- mPhoneUnlockButton.setEnabled(true);
- }
- }
-
- private boolean checkPermissionGranted() {
- return checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
- == PackageManager.PERMISSION_GRANTED;
- }
-} \ No newline at end of file
diff --git a/TrustAgent/src/com/android/car/trust/PhoneEnrolmentActivity.java b/TrustAgent/src/com/android/car/trust/PhoneEnrolmentActivity.java
deleted file mode 100644
index 6e187e2fac..0000000000
--- a/TrustAgent/src/com/android/car/trust/PhoneEnrolmentActivity.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License
- */
-package com.android.car.trust;
-
-import android.app.Activity;
-import android.os.Bundle;
-import android.widget.Button;
-import android.widget.TextView;
-
-/**
- * Activity to allow the user to add an escrow token to a remote device. <p/>
- *
- * For this to work properly, the correct permissions must be set in the system config. In AOSP,
- * this config is in frameworks/base/core/res/res/values/config.xml <p/>
- *
- * The config must set config_allowEscrowTokenForTrustAgent to true. For the desired car
- * experience, the config should also set config_strongAuthRequiredOnBoot to false.
- */
-public class PhoneEnrolmentActivity extends Activity {
- private Button mScanButton;
- private Button mEnrollButton;
-
- private TextView mTextOutput;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.phone_client);
-
- mScanButton = (Button) findViewById(R.id.ble_scan_btn);
- mEnrollButton = (Button) findViewById(R.id.action_button);
- mEnrollButton.setText(getString(R.string.enroll_button));
-
- mTextOutput = (TextView) findViewById(R.id.output);
-
- PhoneEnrolmentController controller = new PhoneEnrolmentController(this /* context */);
- controller.bind(mTextOutput, mScanButton, mEnrollButton);
- }
-}
diff --git a/TrustAgent/src/com/android/car/trust/PhoneEnrolmentController.java b/TrustAgent/src/com/android/car/trust/PhoneEnrolmentController.java
deleted file mode 100644
index b887dc4ff9..0000000000
--- a/TrustAgent/src/com/android/car/trust/PhoneEnrolmentController.java
+++ /dev/null
@@ -1,209 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License
- */
-package com.android.car.trust;
-
-import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothGatt;
-import android.bluetooth.BluetoothGattCharacteristic;
-import android.bluetooth.BluetoothGattService;
-import android.content.Context;
-import android.content.SharedPreferences;
-import android.os.Handler;
-import android.os.ParcelUuid;
-import android.preference.PreferenceManager;
-import android.util.Base64;
-import android.util.Log;
-import android.view.View;
-import android.widget.Button;
-import android.widget.TextView;
-import com.android.car.trust.comms.SimpleBleClient;
-
-import java.nio.ByteBuffer;
-import java.util.Random;
-import java.util.UUID;
-
-/**
- * A controller that sets up a {@link SimpleBleClient} to connect to the BLE enrollment service.
- * It also binds the UI components to control the enrollment process.
- */
-public class PhoneEnrolmentController {
- private static final String TAG = "PhoneEnrolmentCtlr";
- private String mTokenHandleKey;
- private String mEscrowTokenKey;
-
- // BLE characteristics associated with the enrollment/add escrow token service.
- private BluetoothGattCharacteristic mEnrolmentTokenHandle;
- private BluetoothGattCharacteristic mEnrolmentEscrowToken;
-
- private ParcelUuid mEnrolmentServiceUuid;
-
- private SimpleBleClient mClient;
- private Context mContext;
-
- private TextView mTextView;
- private Handler mHandler;
-
- private Button mScanButton;
- private Button mEnrolButton;
-
- public PhoneEnrolmentController(Context context) {
- mContext = context;
-
- mTokenHandleKey = context.getString(R.string.pref_key_token_handle);
- mEscrowTokenKey = context.getString(R.string.pref_key_escrow_token);
-
- mClient = new SimpleBleClient(context);
- mEnrolmentServiceUuid = new ParcelUuid(
- UUID.fromString(mContext.getString(R.string.enrollment_service_uuid)));
- mClient.addCallback(mCallback /* callback */);
-
- mHandler = new Handler(mContext.getMainLooper());
- }
-
- /**
- * Binds the views to the actions that can be performed by this controller.
- *
- * @param textView A text view used to display results from various BLE actions
- * @param scanButton Button used to start scanning for available BLE devices.
- * @param enrolButton Button used to send new escrow token to remote device.
- */
- public void bind(TextView textView, Button scanButton, Button enrolButton) {
- mTextView = textView;
- mScanButton = scanButton;
- mEnrolButton = enrolButton;
-
- mScanButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- mClient.start(mEnrolmentServiceUuid);
- }
- });
-
- mEnrolButton.setEnabled(false);
- mEnrolButton.setAlpha(0.3f);
- mEnrolButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- appendOutputText("Sending new escrow token to remote device");
-
- byte[] token = generateEscrowToken();
- sendEnrolmentRequest(token);
-
- // WARNING: Store the token so it can be used later for unlocking. This token
- // should NEVER be stored on the device that is being unlocked. It should
- // always be securely stored on a remote device that will trigger the unlock.
- storeToken(token);
- }
- });
- }
-
- /**
- * @return A random byte array that is used as the escrow token for remote device unlock.
- */
- private byte[] generateEscrowToken() {
- Random random = new Random();
- ByteBuffer buffer = ByteBuffer.allocate(Long.SIZE / Byte.SIZE);
- buffer.putLong(0, random.nextLong());
- return buffer.array();
- }
-
- private void sendEnrolmentRequest(byte[] token) {
- mEnrolmentEscrowToken.setValue(token);
- mClient.writeCharacteristic(mEnrolmentEscrowToken);
- storeToken(token);
- }
-
- private SimpleBleClient.ClientCallback mCallback = new SimpleBleClient.ClientCallback() {
- @Override
- public void onDeviceConnected(BluetoothDevice device) {
- appendOutputText("Device connected: " + device.getName()
- + " addr: " + device.getAddress());
- }
-
- @Override
- public void onDeviceDisconnected() {
- appendOutputText("Device disconnected");
- }
-
- @Override
- public void onCharacteristicChanged(BluetoothGatt gatt,
- BluetoothGattCharacteristic characteristic) {
-
- if (Log.isLoggable(TAG, Log.DEBUG)) {
- Log.d(TAG, "onCharacteristicChanged: " + Utils.getLong(characteristic.getValue()));
- }
-
- if (characteristic.getUuid().equals(mEnrolmentTokenHandle.getUuid())) {
- // Store the new token handle that the BLE server is sending us. This required
- // to unlock the device.
- long handle = Utils.getLong(characteristic.getValue());
- storeHandle(handle);
- appendOutputText("Token handle received: " + handle);
- }
- }
-
- @Override
- public void onServiceDiscovered(BluetoothGattService service) {
- if (!service.getUuid().equals(mEnrolmentServiceUuid.getUuid())) {
- if (Log.isLoggable(TAG, Log.DEBUG)) {
- Log.d(TAG, "Service UUID: " + service.getUuid()
- + " does not match Enrolment UUID " + mEnrolmentServiceUuid.getUuid());
- }
- return;
- }
-
- if (Log.isLoggable(TAG, Log.DEBUG)) {
- Log.d(TAG, "Enrolment Service # characteristics: "
- + service.getCharacteristics().size());
- }
- mEnrolmentEscrowToken
- = Utils.getCharacteristic(R.string.enrollment_token_uuid, service, mContext);
- mEnrolmentTokenHandle
- = Utils.getCharacteristic(R.string.enrollment_handle_uuid, service, mContext);
- mClient.setCharacteristicNotification(mEnrolmentTokenHandle, true /* enable */);
- appendOutputText("Enrolment BLE client successfully connected");
-
- mHandler.post(new Runnable() {
- @Override
- public void run() {
- // Services are now set up, allow users to enrol new escrow tokens.
- mEnrolButton.setEnabled(true);
- mEnrolButton.setAlpha(1.0f);
- }
- });
- }
- };
-
- private void storeHandle(long handle) {
- SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
- prefs.edit().putLong(mTokenHandleKey, handle).apply();
- }
-
- private void storeToken(byte[] token) {
- SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
- String byteArray = Base64.encodeToString(token, Base64.DEFAULT);
- prefs.edit().putString(mEscrowTokenKey, byteArray).apply();
- }
-
- private void appendOutputText(final String text) {
- mHandler.post(new Runnable() {
- @Override
- public void run() {
- mTextView.append("\n" + text);
- }
- });
- }
-}
diff --git a/TrustAgent/src/com/android/car/trust/PhoneUnlockActivity.java b/TrustAgent/src/com/android/car/trust/PhoneUnlockActivity.java
deleted file mode 100644
index 767e1c5fd4..0000000000
--- a/TrustAgent/src/com/android/car/trust/PhoneUnlockActivity.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License
- */
-package com.android.car.trust;
-
-import android.app.Activity;
-import android.os.Bundle;
-import android.widget.Button;
-import android.widget.TextView;
-
-/**
- * Activity to allow the user to unlock a remote devices with the stored escrow token.
- */
-public class PhoneUnlockActivity extends Activity {
- private Button mScannButton;
- private Button mUnlockButton;
-
- private TextView mTextOutput;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.phone_client);
-
- mScannButton = (Button) findViewById(R.id.ble_scan_btn);
- mUnlockButton = (Button) findViewById(R.id.action_button);
- mUnlockButton.setText(getString(R.string.unlock_button));
-
- mTextOutput = (TextView) findViewById(R.id.output);
-
- PhoneUnlockController controller = new PhoneUnlockController(this /* context */);
- controller.bind(mTextOutput, mScannButton, mUnlockButton);
- }
-}
diff --git a/TrustAgent/src/com/android/car/trust/PhoneUnlockController.java b/TrustAgent/src/com/android/car/trust/PhoneUnlockController.java
deleted file mode 100644
index c956333215..0000000000
--- a/TrustAgent/src/com/android/car/trust/PhoneUnlockController.java
+++ /dev/null
@@ -1,174 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License
- */
-package com.android.car.trust;
-
-import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothGatt;
-import android.bluetooth.BluetoothGattCharacteristic;
-import android.bluetooth.BluetoothGattService;
-import android.content.Context;
-import android.content.SharedPreferences;
-import android.os.Handler;
-import android.os.ParcelUuid;
-import android.preference.PreferenceManager;
-import android.util.Base64;
-import android.util.Log;
-import android.view.View;
-import android.widget.Button;
-import android.widget.TextView;
-import com.android.car.trust.comms.SimpleBleClient;
-
-import java.util.UUID;
-
-/**
- * A controller that sets up a {@link SimpleBleClient} to connect to the BLE unlock service.
- */
-public class PhoneUnlockController {
- private static final String TAG = "PhoneUnlockController";
-
- private String mTokenHandleKey;
- private String mEscrowTokenKey;
-
- // BLE characteristics associated with the enrolment/add escrow token service.
- private BluetoothGattCharacteristic mUnlockTokenHandle;
- private BluetoothGattCharacteristic mUnlockEscrowToken;
-
- private ParcelUuid mUnlockServiceUuid;
-
- private SimpleBleClient mClient;
- private Context mContext;
-
- private TextView mTextView;
- private Handler mHandler;
-
- private Button mScanButton;
- private Button mUnlockButton;
-
- public PhoneUnlockController(Context context) {
- mContext = context;
-
- mTokenHandleKey = context.getString(R.string.pref_key_token_handle);
- mEscrowTokenKey = context.getString(R.string.pref_key_escrow_token);
-
- mClient = new SimpleBleClient(context);
- mUnlockServiceUuid = new ParcelUuid(
- UUID.fromString(mContext.getString(R.string.unlock_service_uuid)));
- mClient.addCallback(mCallback /* callback */);
-
- mHandler = new Handler(mContext.getMainLooper());
- }
-
- /**
- * Binds the views to the actions that can be performed by this controller.
- *
- * @param textView A text view used to display results from various BLE actions
- * @param scanButton Button used to start scanning for available BLE devices.
- * @param enrolButton Button used to send new escrow token to remote device.
- */
- public void bind(TextView textView, Button scanButton, Button enrolButton) {
- mTextView = textView;
- mScanButton = scanButton;
- mUnlockButton = enrolButton;
-
- mScanButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- mClient.start(mUnlockServiceUuid);
- }
- });
-
- mUnlockButton.setEnabled(false);
- mUnlockButton.setAlpha(0.3f);
- mUnlockButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- appendOutputText("Sending unlock token and handle to remote device");
- sendUnlockRequest();
- }
- });
- }
-
- private void sendUnlockRequest() {
- // Retrieve stored token and handle and write to remote device.
- SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
- long handle = prefs.getLong(mTokenHandleKey, -1);
- byte[] token = Base64.decode(prefs.getString(mEscrowTokenKey, null), Base64.DEFAULT);
-
- mUnlockEscrowToken.setValue(token);
- mUnlockTokenHandle.setValue(Utils.getBytes(handle));
-
- mClient.writeCharacteristic(mUnlockEscrowToken);
- mClient.writeCharacteristic(mUnlockTokenHandle);
- }
-
- private SimpleBleClient.ClientCallback mCallback = new SimpleBleClient.ClientCallback() {
- @Override
- public void onDeviceConnected(BluetoothDevice device) {
- appendOutputText("Device connected: " + device.getName()
- + " addr: " + device.getAddress());
- }
-
- @Override
- public void onDeviceDisconnected() {
- appendOutputText("Device disconnected");
- }
-
- @Override
- public void onCharacteristicChanged(BluetoothGatt gatt,
- BluetoothGattCharacteristic characteristic) {
- // Not expecting any characteristics changes for the unlocking client.
- }
-
- @Override
- public void onServiceDiscovered(BluetoothGattService service) {
- if (!service.getUuid().equals(mUnlockServiceUuid.getUuid())) {
- if (Log.isLoggable(TAG, Log.DEBUG)) {
- Log.d(TAG, "Service UUID: " + service.getUuid()
- + " does not match Enrolment UUID " + mUnlockServiceUuid.getUuid());
- }
- return;
- }
-
- if (Log.isLoggable(TAG, Log.DEBUG)) {
- Log.d(TAG, "Unlock Service # characteristics: "
- + service.getCharacteristics().size());
- }
- mUnlockEscrowToken
- = Utils.getCharacteristic(R.string.unlock_escrow_token_uiid, service, mContext);
- mUnlockTokenHandle
- = Utils.getCharacteristic(R.string.unlock_handle_uiid, service, mContext);
- appendOutputText("Unlock BLE client successfully connected");
-
- mHandler.post(new Runnable() {
- @Override
- public void run() {
- // Services are now set up, allow users to enrol new escrow tokens.
- mUnlockButton.setEnabled(true);
- mUnlockButton.setAlpha(1.0f);
- }
- });
- }
- };
-
- private void appendOutputText(final String text) {
- mHandler.post(new Runnable() {
- @Override
- public void run() {
- mTextView.append("\n" + text);
- }
- });
- }
-}
diff --git a/TrustAgent/src/com/android/car/trust/comms/SimpleBleClient.java b/TrustAgent/src/com/android/car/trust/comms/SimpleBleClient.java
deleted file mode 100644
index 77bf2d3c2c..0000000000
--- a/TrustAgent/src/com/android/car/trust/comms/SimpleBleClient.java
+++ /dev/null
@@ -1,380 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License
- */
-package com.android.car.trust.comms;
-
-import android.bluetooth.BluetoothDevice;
-import android.bluetooth.BluetoothGatt;
-import android.bluetooth.BluetoothGattCallback;
-import android.bluetooth.BluetoothGattCharacteristic;
-import android.bluetooth.BluetoothGattService;
-import android.bluetooth.BluetoothManager;
-import android.bluetooth.BluetoothProfile;
-import android.bluetooth.le.BluetoothLeScanner;
-import android.bluetooth.le.ScanCallback;
-import android.bluetooth.le.ScanFilter;
-import android.bluetooth.le.ScanResult;
-import android.bluetooth.le.ScanSettings;
-import android.content.Context;
-import android.os.Handler;
-import android.os.ParcelUuid;
-import android.support.annotation.NonNull;
-import android.util.Log;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Queue;
-import java.util.concurrent.ConcurrentLinkedQueue;
-
-/**
- * A simple client that supports the scanning and connecting to available BLE devices. Should be
- * used along with {@link SimpleBleServer}.
- */
-public class SimpleBleClient {
- public interface ClientCallback {
- /**
- * Called when a device that has a matching service UUID is found.
- **/
- void onDeviceConnected(BluetoothDevice device);
-
- void onDeviceDisconnected();
-
- void onCharacteristicChanged(BluetoothGatt gatt,
- BluetoothGattCharacteristic characteristic);
-
- /**
- * Called for each {@link BluetoothGattService} that is discovered on the
- * {@link BluetoothDevice} after a matching scan result and connection.
- *
- * @param service {@link BluetoothGattService} that has been discovered.
- */
- void onServiceDiscovered(BluetoothGattService service);
- }
-
- /**
- * Wrapper class to allow queuing of BLE actions. The BLE stack allows only one action to be
- * executed at a time.
- */
- public static class BleAction {
- public static final int ACTION_WRITE = 0;
- public static final int ACTION_READ = 1;
-
- private int mAction;
- private BluetoothGattCharacteristic mCharacteristic;
-
- public BleAction(BluetoothGattCharacteristic characteristic, int action) {
- mAction = action;
- mCharacteristic = characteristic;
- }
-
- public int getAction() {
- return mAction;
- }
-
- public BluetoothGattCharacteristic getCharacteristic() {
- return mCharacteristic;
- }
- }
-
- private static final String TAG = "SimpleBleClient";
- private static final long SCAN_TIME_MS = 10000;
-
- private Queue<BleAction> mBleActionQueue = new ConcurrentLinkedQueue<BleAction>();
-
- private BluetoothManager mBtManager;
- private BluetoothLeScanner mScanner;
-
- protected BluetoothGatt mBtGatt;
-
- private List<ClientCallback> mCallbacks;
- private ParcelUuid mServiceUuid;
- private Context mContext;
-
- public SimpleBleClient(@NonNull Context context) {
- mContext = context;
- mBtManager = (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE);
- mScanner = mBtManager.getAdapter().getBluetoothLeScanner();
- mCallbacks = new ArrayList<>();
- }
-
- /**
- * Start scanning for a BLE devices with the specified service uuid.
- *
- * @param parcelUuid {@link ParcelUuid} used to identify the device that should be used for
- * this client. This uuid should be the same as the one that is set in the
- * {@link android.bluetooth.le.AdvertiseData.Builder} by the advertising
- * device.
- */
- public void start(ParcelUuid parcelUuid) {
- mServiceUuid = parcelUuid;
-
- // We only want to scan for devices that have the correct uuid set in its advertise data.
- List<ScanFilter> filters = new ArrayList<ScanFilter>();
- ScanFilter.Builder serviceFilter = new ScanFilter.Builder();
- serviceFilter.setServiceUuid(mServiceUuid);
- filters.add(serviceFilter.build());
-
- ScanSettings.Builder settings = new ScanSettings.Builder();
- settings.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY);
-
- if (Log.isLoggable(TAG, Log.DEBUG)) {
- Log.d(TAG, "Start scanning for uuid: " + mServiceUuid.getUuid());
- }
- mScanner.startScan(filters, settings.build(), mScanCallback);
-
- Handler handler = new Handler();
- handler.postDelayed(new Runnable() {
- @Override
- public void run() {
- mScanner.stopScan(mScanCallback);
- if (Log.isLoggable(TAG, Log.DEBUG)) {
- Log.d(TAG, "Stopping Scanner");
- }
- }
- }, SCAN_TIME_MS);
- }
-
- private boolean hasServiceUuid(ScanResult result) {
- if (result.getScanRecord() == null
- || result.getScanRecord().getServiceUuids() == null
- || result.getScanRecord().getServiceUuids().size() == 0) {
- return false;
- }
- return true;
- }
-
- /**
- * Writes to a {@link BluetoothGattCharacteristic} if possible, or queues the action until
- * other actions are complete.
- *
- * @param characteristic {@link BluetoothGattCharacteristic} to be written
- */
- public void writeCharacteristic(BluetoothGattCharacteristic characteristic) {
- processAction(new BleAction(characteristic, BleAction.ACTION_WRITE));
- }
-
- /**
- * Reads a {@link BluetoothGattCharacteristic} if possible, or queues the read action until
- * other actions are complete.
- *
- * @param characteristic {@link BluetoothGattCharacteristic} to be read.
- */
- public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
- processAction(new BleAction(characteristic, BleAction.ACTION_READ));
- }
-
- /**
- * Enable or disable notification for specified {@link BluetoothGattCharacteristic}.
- *
- * @param characteristic The {@link BluetoothGattCharacteristic} for which to enable
- * notifications.
- * @param enabled True if notifications should be enabled, false otherwise.
- */
- public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
- boolean enabled) {
- mBtGatt.setCharacteristicNotification(characteristic, enabled);
- }
-
- /**
- * Add a {@link ClientCallback} to listen for updates from BLE components
- */
- public void addCallback(ClientCallback callback) {
- mCallbacks.add(callback);
- }
-
- public void removeCallback(ClientCallback callback) {
- mCallbacks.remove(callback);
- }
-
- private void processAction(BleAction action) {
- // Only execute actions if the queue is empty.
- if (mBleActionQueue.size() > 0) {
- mBleActionQueue.add(action);
- return;
- }
-
- mBleActionQueue.add(action);
- executeAction(mBleActionQueue.peek());
- }
-
- private void processNextAction() {
- mBleActionQueue.poll();
- executeAction(mBleActionQueue.peek());
- }
-
- private void executeAction(BleAction action) {
- if (action == null) {
- return;
- }
-
- if (Log.isLoggable(TAG, Log.DEBUG)) {
- Log.d(TAG, "Executing BLE Action type: " + action.getAction());
- }
-
- int actionType = action.getAction();
- switch (actionType) {
- case BleAction.ACTION_WRITE:
- mBtGatt.writeCharacteristic(action.getCharacteristic());
- break;
- case BleAction.ACTION_READ:
- mBtGatt.readCharacteristic(action.getCharacteristic());
- break;
- default:
- }
- }
-
- private String getStatus(int status) {
- switch (status) {
- case BluetoothGatt.GATT_FAILURE:
- return "Failure";
- case BluetoothGatt.GATT_SUCCESS:
- return "GATT_SUCCESS";
- case BluetoothGatt.GATT_READ_NOT_PERMITTED:
- return "GATT_READ_NOT_PERMITTED";
- case BluetoothGatt.GATT_WRITE_NOT_PERMITTED:
- return "GATT_WRITE_NOT_PERMITTED";
- case BluetoothGatt.GATT_INSUFFICIENT_AUTHENTICATION:
- return "GATT_INSUFFICIENT_AUTHENTICATION";
- case BluetoothGatt.GATT_REQUEST_NOT_SUPPORTED:
- return "GATT_REQUEST_NOT_SUPPORTED";
- case BluetoothGatt.GATT_INVALID_OFFSET:
- return "GATT_INVALID_OFFSET";
- case BluetoothGatt.GATT_INVALID_ATTRIBUTE_LENGTH:
- return "GATT_INVALID_ATTRIBUTE_LENGTH";
- case BluetoothGatt.GATT_CONNECTION_CONGESTED:
- return "GATT_CONNECTION_CONGESTED";
- default:
- return "unknown";
- }
- }
-
- private ScanCallback mScanCallback = new ScanCallback() {
- @Override
- public void onScanResult(int callbackType, ScanResult result) {
- BluetoothDevice device = result.getDevice();
- if (Log.isLoggable(TAG, Log.DEBUG)) {
- Log.d(TAG, "Scan result found: " + result.getScanRecord().getServiceUuids());
- }
-
- if (!hasServiceUuid(result)) {
- return;
- }
-
- for (ParcelUuid uuid : result.getScanRecord().getServiceUuids()) {
- if (Log.isLoggable(TAG, Log.DEBUG)) {
- Log.d(TAG, "Scan result UUID: " + uuid);
- }
- if (uuid.equals(mServiceUuid)) {
- // This client only supports connecting to one service.
- // Once we find one, stop scanning and open a GATT connection to the device.
- mScanner.stopScan(mScanCallback);
- mBtGatt = device.connectGatt(mContext, false /* autoConnect */, mGattCallback);
- return;
- }
- }
- }
-
- @Override
- public void onBatchScanResults(List<ScanResult> results) {
- for (ScanResult r : results) {
- if (Log.isLoggable(TAG, Log.DEBUG)) {
- Log.d(TAG, "Batch scanResult: " + r.getDevice().getName()
- + " " + r.getDevice().getAddress());
- }
- }
- }
-
- @Override
- public void onScanFailed(int errorCode) {
- Log.w(TAG, "Scan failed: " + errorCode);
- }
- };
-
- private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
- @Override
- public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
- super.onConnectionStateChange(gatt, status, newState);
-
- String state = "";
-
- if (newState == BluetoothProfile.STATE_CONNECTED) {
- state = "Connected";
- mBtGatt.discoverServices();
- for (ClientCallback callback : mCallbacks) {
- callback.onDeviceConnected(gatt.getDevice());
- }
-
- } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
- state = "Disconnected";
- for (ClientCallback callback : mCallbacks) {
- callback.onDeviceDisconnected();
- }
- }
- if (Log.isLoggable(TAG, Log.DEBUG)) {
- Log.d(TAG, " Gatt connection status: " + getStatus(status) + " newState: " + state);
- }
- }
-
- @Override
- public void onServicesDiscovered(BluetoothGatt gatt, int status) {
- super.onServicesDiscovered(gatt, status);
- if (Log.isLoggable(TAG, Log.DEBUG)) {
- Log.d(TAG, "onServicesDiscovered: " + status);
- }
-
- List<BluetoothGattService> services = gatt.getServices();
- if (services == null || services.size() <= 0) {
- return;
- }
-
- // Notify clients of newly discovered services.
- for (BluetoothGattService service : mBtGatt.getServices()) {
- if (Log.isLoggable(TAG, Log.DEBUG)) {
- Log.d(TAG, "Found service: " + service.getUuid() + " notifying clients");
- }
- for (ClientCallback callback : mCallbacks) {
- callback.onServiceDiscovered(service);
- }
- }
- }
-
- @Override
- public void onCharacteristicWrite(BluetoothGatt gatt,
- BluetoothGattCharacteristic characteristic, int status) {
- if (Log.isLoggable(TAG, Log.DEBUG)) {
- Log.d(TAG, "onCharacteristicWrite: " + status);
- }
- processNextAction();
- }
-
- @Override
- public void onCharacteristicRead(BluetoothGatt gatt,
- BluetoothGattCharacteristic characteristic, int status) {
- if (Log.isLoggable(TAG, Log.DEBUG)) {
- Log.d(TAG, "onCharacteristicRead:" + new String(characteristic.getValue()));
- }
- processNextAction();
- }
-
- @Override
- public void onCharacteristicChanged(BluetoothGatt gatt,
- BluetoothGattCharacteristic characteristic) {
- for (ClientCallback callback : mCallbacks) {
- callback.onCharacteristicChanged(gatt, characteristic);
- }
- processNextAction();
- }
- };
-}
diff --git a/TrustAgent/src/com/android/car/trust/comms/SimpleBleServer.java b/TrustAgent/src/com/android/car/trust/comms/SimpleBleServer.java
index da3f7accce..9b3d648c94 100644
--- a/TrustAgent/src/com/android/car/trust/comms/SimpleBleServer.java
+++ b/TrustAgent/src/com/android/car/trust/comms/SimpleBleServer.java
@@ -37,42 +37,96 @@ import android.os.ParcelUuid;
import android.util.Log;
import java.util.HashSet;
+import java.util.Set;
/**
* A generic service to start a BLE
*/
public abstract class SimpleBleServer extends Service {
- /**
- * Listener that is notified when the status of the BLE server changes.
- */
- public interface ConnectionListener {
- /**
- * Called when the GATT server is started and BLE is successfully advertising.
- */
- void onServerStarted();
+ private static final String TAG = "SimpleBleServer";
- /**
- * Called when the BLE advertisement fails to start.
- *
- * @param errorCode Error code (see {@link AdvertiseCallback}#ADVERTISE_FAILED_* constants)
- */
- void onServerStartFailed(int errorCode);
+ private final AdvertiseCallback mAdvertisingCallback = new AdvertiseCallback() {
+ @Override
+ public void onStartSuccess(AdvertiseSettings settingsInEffect) {
+ super.onStartSuccess(settingsInEffect);
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "Successfully started advertising service");
+ }
+ for (ConnectionCallback callback : mConnectionCallbacks) {
+ callback.onServerStarted();
+ }
+ }
- /**
- * Called when a device is connected.
- * @param device
- */
- void onDeviceConnected(BluetoothDevice device);
- }
+ @Override
+ public void onStartFailure(int errorCode) {
+ super.onStartFailure(errorCode);
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "Failed to advertise, errorCode: " + errorCode);
+ }
+ for (ConnectionCallback callback : mConnectionCallbacks) {
+ callback.onServerStartFailed(errorCode);
+ }
+ }
+ };
- private static final String TAG = "SimpleBleServer";
+ private final BluetoothGattServerCallback mGattServerCallback =
+ new BluetoothGattServerCallback() {
+ @Override
+ public void onConnectionStateChange(BluetoothDevice device,
+ final int status, final int newState) {
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "GattServer connection change status: "
+ + newState + " newState: "
+ + newState + " device name: " + device.getName());
+ }
+ if (newState == BluetoothProfile.STATE_CONNECTED) {
+ for (ConnectionCallback callback : mConnectionCallbacks) {
+ callback.onDeviceConnected(device);
+ }
+ }
+ }
+
+ @Override
+ public void onServiceAdded(final int status, BluetoothGattService service) {
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "Service added status: " + status + " uuid: " + service.getUuid());
+ }
+ }
+
+ @Override
+ public void onCharacteristicReadRequest(BluetoothDevice device,
+ int requestId, int offset, final BluetoothGattCharacteristic characteristic) {
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "Read request for characteristic: " + characteristic.getUuid());
+ }
+ mGattServer.sendResponse(device, requestId,
+ BluetoothGatt.GATT_SUCCESS, offset, characteristic.getValue());
+ SimpleBleServer.
+ this.onCharacteristicRead(device, requestId, offset, characteristic);
+ }
+
+ @Override
+ public void onCharacteristicWriteRequest(final BluetoothDevice device, int requestId,
+ BluetoothGattCharacteristic characteristic, boolean preparedWrite, boolean
+ responseNeeded, int offset, byte[] value) {
+ if (Log.isLoggable(TAG, Log.DEBUG)) {
+ Log.d(TAG, "Write request for characteristic: " + characteristic.getUuid());
+ }
+ mGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS,
+ offset, value);
+
+ SimpleBleServer.
+ this.onCharacteristicWrite(device, requestId, characteristic,
+ preparedWrite, responseNeeded, offset, value);
+ }
+ };
+
+ private final Set<ConnectionCallback> mConnectionCallbacks = new HashSet<>();
private BluetoothLeAdvertiser mAdvertiser;
protected BluetoothGattServer mGattServer;
- private HashSet<ConnectionListener> mListeners = new HashSet<>();
-
@Override
public IBinder onBind(Intent intent) {
// Override in child classes.
@@ -116,9 +170,7 @@ public abstract class SimpleBleServer extends Service {
.addServiceUuid(advertiseUuid)
.build();
- mAdvertiser
- = BluetoothAdapter.getDefaultAdapter().getBluetoothLeAdvertiser();
-
+ mAdvertiser = BluetoothAdapter.getDefaultAdapter().getBluetoothLeAdvertiser();
mAdvertiser.startAdvertising(settings, data, mAdvertisingCallback);
}
@@ -144,7 +196,7 @@ public abstract class SimpleBleServer extends Service {
}
}
- mListeners.clear();
+ mConnectionCallbacks.clear();
}
@Override
@@ -153,11 +205,11 @@ public abstract class SimpleBleServer extends Service {
super.onDestroy();
}
- public void addConnectionListener(ConnectionListener listener) {
+ public void registerConnectionCallback(ConnectionCallback callback) {
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Adding connection listener");
}
- mListeners.add(listener);
+ mConnectionCallbacks.add(callback);
}
/**
@@ -174,78 +226,26 @@ public abstract class SimpleBleServer extends Service {
public abstract void onCharacteristicRead(BluetoothDevice device,
int requestId, int offset, final BluetoothGattCharacteristic characteristic);
- private AdvertiseCallback mAdvertisingCallback = new AdvertiseCallback() {
- @Override
- public void onStartSuccess(AdvertiseSettings settingsInEffect) {
- super.onStartSuccess(settingsInEffect);
- if (Log.isLoggable(TAG, Log.DEBUG)) {
- Log.d(TAG, "Successfully started advertising service");
- }
- for (ConnectionListener listener : mListeners) {
- listener.onServerStarted();
- }
- }
-
- @Override
- public void onStartFailure(int errorCode) {
- super.onStartFailure(errorCode);
- if (Log.isLoggable(TAG, Log.DEBUG)) {
- Log.d(TAG, "Failed to advertise, errorCode: " + errorCode);
- }
- for (ConnectionListener listener : mListeners) {
- listener.onServerStartFailed(errorCode);
- }
- }
- };
-
- private BluetoothGattServerCallback mGattServerCallback = new BluetoothGattServerCallback() {
- @Override
- public void onConnectionStateChange(BluetoothDevice device,
- final int status, final int newState) {
- if (Log.isLoggable(TAG, Log.DEBUG)) {
- Log.d(TAG, "GattServer connection change status: "
- + newState + " newState: "
- + newState + " device name: " + device.getName());
- }
- if (newState == BluetoothProfile.STATE_CONNECTED) {
- for (ConnectionListener listener : mListeners) {
- listener.onDeviceConnected(device);
- }
- }
- }
-
- @Override
- public void onServiceAdded(final int status, BluetoothGattService service) {
- if (Log.isLoggable(TAG, Log.DEBUG)) {
- Log.d(TAG, "Service added status: " + status + " uuid: " + service.getUuid());
- }
- }
-
- @Override
- public void onCharacteristicReadRequest(BluetoothDevice device,
- int requestId, int offset, final BluetoothGattCharacteristic characteristic) {
- if (Log.isLoggable(TAG, Log.DEBUG)) {
- Log.d(TAG, "Read request for characteristic: " + characteristic.getUuid());
- }
- mGattServer.sendResponse(device, requestId,
- BluetoothGatt.GATT_SUCCESS, offset, characteristic.getValue());
- SimpleBleServer.
- this.onCharacteristicRead(device, requestId, offset, characteristic);
- }
+ /**
+ * Callback that is notified when the status of the BLE server changes.
+ */
+ public interface ConnectionCallback {
+ /**
+ * Called when the GATT server is started and BLE is successfully advertising.
+ */
+ void onServerStarted();
- @Override
- public void onCharacteristicWriteRequest(final BluetoothDevice device, int requestId,
- BluetoothGattCharacteristic characteristic, boolean preparedWrite, boolean
- responseNeeded, int offset, byte[] value) {
- if (Log.isLoggable(TAG, Log.DEBUG)) {
- Log.d(TAG, "Write request for characteristic: " + characteristic.getUuid());
- }
- mGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS,
- offset, value);
+ /**
+ * Called when the BLE advertisement fails to start.
+ *
+ * @param errorCode Error code (see {@link AdvertiseCallback}#ADVERTISE_FAILED_* constants)
+ */
+ void onServerStartFailed(int errorCode);
- SimpleBleServer.
- this.onCharacteristicWrite(device, requestId, characteristic,
- preparedWrite, responseNeeded, offset, value);
- }
- };
+ /**
+ * Called when a device is connected.
+ * @param device {@link BluetoothDevice} that is connected
+ */
+ void onDeviceConnected(BluetoothDevice device);
+ }
}
diff --git a/TrustAgent/src/com/android/car/trust/Utils.java b/TrustAgent/src/com/android/car/trust/comms/Utils.java
index 3e9181f88d..6742842cd8 100644
--- a/TrustAgent/src/com/android/car/trust/Utils.java
+++ b/TrustAgent/src/com/android/car/trust/comms/Utils.java
@@ -13,14 +13,9 @@
* See the License for the specific language governing permissions and
* limitations under the License
*/
-package com.android.car.trust;
-
-import android.bluetooth.BluetoothGattCharacteristic;
-import android.bluetooth.BluetoothGattService;
-import android.content.Context;
+package com.android.car.trust.comms;
import java.nio.ByteBuffer;
-import java.util.UUID;
public class Utils {
@@ -36,9 +31,4 @@ public class Utils {
buffer.flip();
return buffer.getLong();
}
-
- public static BluetoothGattCharacteristic getCharacteristic(int uuidRes,
- BluetoothGattService service, Context context) {
- return service.getCharacteristic(UUID.fromString(context.getString(uuidRes)));
- }
}