1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
|
/*
* Copyright (C) 2016 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.
*/
/*
* Bluetooth Pbap PCE StateMachine
* (Disconnected)
* | ^
* CONNECT | | DISCONNECTED
* V |
* (Connecting) (Disconnecting)
* | ^
* CONNECTED | | DISCONNECT
* V |
* (Connected)
*
* Valid Transitions:
* State + Event -> Transition:
*
* Disconnected + CONNECT -> Connecting
* Connecting + CONNECTED -> Connected
* Connecting + TIMEOUT -> Disconnecting
* Connecting + DISCONNECT -> Disconnecting
* Connected + DISCONNECT -> Disconnecting
* Disconnecting + DISCONNECTED -> (Safe) Disconnected
* Disconnecting + TIMEOUT -> (Force) Disconnected
* Disconnecting + CONNECT : Defer Message
*
*/
package com.android.bluetooth.pbapclient;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothPbapClient;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothUuid;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.HandlerThread;
import android.os.Message;
import android.os.ParcelUuid;
import android.os.Process;
import android.os.UserManager;
import android.util.Log;
import com.android.bluetooth.BluetoothMetricsProto;
import com.android.bluetooth.btservice.MetricsLogger;
import com.android.bluetooth.btservice.ProfileService;
import com.android.internal.util.IState;
import com.android.internal.util.State;
import com.android.internal.util.StateMachine;
import java.util.ArrayList;
import java.util.List;
final class PbapClientStateMachine extends StateMachine {
private static final boolean DBG = Utils.DBG;
private static final String TAG = "PbapClientStateMachine";
// Messages for handling connect/disconnect requests.
private static final int MSG_DISCONNECT = 2;
private static final int MSG_SDP_COMPLETE = 9;
// Messages for handling error conditions.
private static final int MSG_CONNECT_TIMEOUT = 3;
private static final int MSG_DISCONNECT_TIMEOUT = 4;
// Messages for feedback from ConnectionHandler.
static final int MSG_CONNECTION_COMPLETE = 5;
static final int MSG_CONNECTION_FAILED = 6;
static final int MSG_CONNECTION_CLOSED = 7;
static final int MSG_RESUME_DOWNLOAD = 8;
static final int CONNECT_TIMEOUT = 10000;
static final int DISCONNECT_TIMEOUT = 3000;
private final Object mLock;
private State mDisconnected;
private State mConnecting;
private State mConnected;
private State mDisconnecting;
// mCurrentDevice may only be changed in Disconnected State.
private final BluetoothDevice mCurrentDevice;
private PbapClientService mService;
private PbapClientConnectionHandler mConnectionHandler;
private HandlerThread mHandlerThread = null;
private UserManager mUserManager = null;
// mMostRecentState maintains previous state for broadcasting transitions.
private int mMostRecentState = BluetoothProfile.STATE_DISCONNECTED;
PbapClientStateMachine(PbapClientService svc, BluetoothDevice device) {
super(TAG);
mService = svc;
mCurrentDevice = device;
mLock = new Object();
mUserManager = UserManager.get(mService);
mDisconnected = new Disconnected();
mConnecting = new Connecting();
mDisconnecting = new Disconnecting();
mConnected = new Connected();
addState(mDisconnected);
addState(mConnecting);
addState(mDisconnecting);
addState(mConnected);
setInitialState(mConnecting);
}
class Disconnected extends State {
@Override
public void enter() {
if (DBG) Log.d(TAG, "Enter Disconnected: " + getCurrentMessage().what);
onConnectionStateChanged(mCurrentDevice, mMostRecentState,
BluetoothProfile.STATE_DISCONNECTED);
mMostRecentState = BluetoothProfile.STATE_DISCONNECTED;
quit();
}
}
class Connecting extends State {
private SDPBroadcastReceiver mSdpReceiver;
@Override
public void enter() {
if (DBG) {
Log.d(TAG, "Enter Connecting: " + getCurrentMessage().what);
}
onConnectionStateChanged(mCurrentDevice, mMostRecentState,
BluetoothProfile.STATE_CONNECTING);
mSdpReceiver = new SDPBroadcastReceiver();
mSdpReceiver.register();
mCurrentDevice.sdpSearch(BluetoothUuid.PBAP_PSE);
mMostRecentState = BluetoothProfile.STATE_CONNECTING;
// Create a separate handler instance and thread for performing
// connect/download/disconnect operations as they may be time consuming and error prone.
mHandlerThread =
new HandlerThread("PBAP PCE handler", Process.THREAD_PRIORITY_BACKGROUND);
mHandlerThread.start();
mConnectionHandler =
new PbapClientConnectionHandler.Builder().setLooper(mHandlerThread.getLooper())
.setContext(mService)
.setClientSM(PbapClientStateMachine.this)
.setRemoteDevice(mCurrentDevice)
.build();
sendMessageDelayed(MSG_CONNECT_TIMEOUT, CONNECT_TIMEOUT);
}
@Override
public boolean processMessage(Message message) {
if (DBG) {
Log.d(TAG, "Processing MSG " + message.what + " from " + this.getName());
}
switch (message.what) {
case MSG_DISCONNECT:
if (message.obj instanceof BluetoothDevice && message.obj.equals(
mCurrentDevice)) {
removeMessages(MSG_CONNECT_TIMEOUT);
transitionTo(mDisconnecting);
}
break;
case MSG_CONNECTION_COMPLETE:
removeMessages(MSG_CONNECT_TIMEOUT);
transitionTo(mConnected);
break;
case MSG_CONNECTION_FAILED:
case MSG_CONNECT_TIMEOUT:
removeMessages(MSG_CONNECT_TIMEOUT);
transitionTo(mDisconnecting);
break;
case MSG_SDP_COMPLETE:
mConnectionHandler.obtainMessage(PbapClientConnectionHandler.MSG_CONNECT,
message.obj).sendToTarget();
break;
default:
Log.w(TAG, "Received unexpected message while Connecting");
return NOT_HANDLED;
}
return HANDLED;
}
@Override
public void exit() {
mSdpReceiver.unregister();
mSdpReceiver = null;
}
private class SDPBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DBG) {
Log.v(TAG, "onReceive" + action);
}
if (action.equals(BluetoothDevice.ACTION_SDP_RECORD)) {
BluetoothDevice device =
intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (!device.equals(getDevice())) {
Log.w(TAG, "SDP Record fetched for different device - Ignore");
return;
}
ParcelUuid uuid = intent.getParcelableExtra(BluetoothDevice.EXTRA_UUID);
if (DBG) {
Log.v(TAG, "Received UUID: " + uuid.toString());
Log.v(TAG, "expected UUID: " + BluetoothUuid.PBAP_PSE.toString());
}
if (uuid.equals(BluetoothUuid.PBAP_PSE)) {
sendMessage(MSG_SDP_COMPLETE,
intent.getParcelableExtra(BluetoothDevice.EXTRA_SDP_RECORD));
}
}
}
public void register() {
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_SDP_RECORD);
mService.registerReceiver(this, filter);
}
public void unregister() {
mService.unregisterReceiver(this);
}
}
}
class Disconnecting extends State {
@Override
public void enter() {
if (DBG) Log.d(TAG, "Enter Disconnecting: " + getCurrentMessage().what);
onConnectionStateChanged(mCurrentDevice, mMostRecentState,
BluetoothProfile.STATE_DISCONNECTING);
mMostRecentState = BluetoothProfile.STATE_DISCONNECTING;
mConnectionHandler.obtainMessage(PbapClientConnectionHandler.MSG_DISCONNECT)
.sendToTarget();
sendMessageDelayed(MSG_DISCONNECT_TIMEOUT, DISCONNECT_TIMEOUT);
}
@Override
public boolean processMessage(Message message) {
if (DBG) {
Log.d(TAG, "Processing MSG " + message.what + " from " + this.getName());
}
switch (message.what) {
case MSG_CONNECTION_CLOSED:
removeMessages(MSG_DISCONNECT_TIMEOUT);
mHandlerThread.quitSafely();
transitionTo(mDisconnected);
break;
case MSG_DISCONNECT:
deferMessage(message);
break;
case MSG_DISCONNECT_TIMEOUT:
Log.w(TAG, "Disconnect Timeout, Forcing");
mConnectionHandler.abort();
break;
case MSG_RESUME_DOWNLOAD:
// Do nothing.
break;
default:
Log.w(TAG, "Received unexpected message while Disconnecting");
return NOT_HANDLED;
}
return HANDLED;
}
}
class Connected extends State {
@Override
public void enter() {
if (DBG) Log.d(TAG, "Enter Connected: " + getCurrentMessage().what);
onConnectionStateChanged(mCurrentDevice, mMostRecentState,
BluetoothProfile.STATE_CONNECTED);
mMostRecentState = BluetoothProfile.STATE_CONNECTED;
if (mUserManager.isUserUnlocked()) {
mConnectionHandler.obtainMessage(PbapClientConnectionHandler.MSG_DOWNLOAD)
.sendToTarget();
}
}
@Override
public boolean processMessage(Message message) {
if (DBG) {
Log.d(TAG, "Processing MSG " + message.what + " from " + this.getName());
}
switch (message.what) {
case MSG_DISCONNECT:
if ((message.obj instanceof BluetoothDevice)
&& ((BluetoothDevice) message.obj).equals(mCurrentDevice)) {
transitionTo(mDisconnecting);
}
break;
case MSG_RESUME_DOWNLOAD:
mConnectionHandler.obtainMessage(PbapClientConnectionHandler.MSG_DOWNLOAD)
.sendToTarget();
break;
default:
Log.w(TAG, "Received unexpected message while Connected");
return NOT_HANDLED;
}
return HANDLED;
}
}
private void onConnectionStateChanged(BluetoothDevice device, int prevState, int state) {
if (device == null) {
Log.w(TAG, "onConnectionStateChanged with invalid device");
return;
}
if (prevState != state && state == BluetoothProfile.STATE_CONNECTED) {
MetricsLogger.logProfileConnectionEvent(BluetoothMetricsProto.ProfileId.PBAP_CLIENT);
}
Log.d(TAG, "Connection state " + device + ": " + prevState + "->" + state);
Intent intent = new Intent(BluetoothPbapClient.ACTION_CONNECTION_STATE_CHANGED);
intent.putExtra(BluetoothProfile.EXTRA_PREVIOUS_STATE, prevState);
intent.putExtra(BluetoothProfile.EXTRA_STATE, state);
intent.putExtra(BluetoothDevice.EXTRA_DEVICE, device);
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
mService.sendBroadcast(intent, ProfileService.BLUETOOTH_PERM);
}
public void disconnect(BluetoothDevice device) {
if (DBG) Log.d(TAG, "Disconnect Request " + device);
sendMessage(MSG_DISCONNECT, device);
}
public void resumeDownload() {
sendMessage(MSG_RESUME_DOWNLOAD);
}
void doQuit() {
if (mHandlerThread != null) {
mHandlerThread.quitSafely();
}
quitNow();
}
@Override
protected void onQuitting() {
mService.cleanupDevice(mCurrentDevice);
}
public int getConnectionState() {
IState currentState = getCurrentState();
if (currentState instanceof Disconnected) {
return BluetoothProfile.STATE_DISCONNECTED;
} else if (currentState instanceof Connecting) {
return BluetoothProfile.STATE_CONNECTING;
} else if (currentState instanceof Connected) {
return BluetoothProfile.STATE_CONNECTED;
} else if (currentState instanceof Disconnecting) {
return BluetoothProfile.STATE_DISCONNECTING;
}
Log.w(TAG, "Unknown State");
return BluetoothProfile.STATE_DISCONNECTED;
}
public List<BluetoothDevice> getDevicesMatchingConnectionStates(int[] states) {
int clientState;
BluetoothDevice currentDevice;
synchronized (mLock) {
clientState = getConnectionState();
currentDevice = getDevice();
}
List<BluetoothDevice> deviceList = new ArrayList<BluetoothDevice>();
for (int state : states) {
if (clientState == state) {
if (currentDevice != null) {
deviceList.add(currentDevice);
}
}
}
return deviceList;
}
public int getConnectionState(BluetoothDevice device) {
if (device == null) {
return BluetoothProfile.STATE_DISCONNECTED;
}
synchronized (mLock) {
if (device.equals(mCurrentDevice)) {
return getConnectionState();
}
}
return BluetoothProfile.STATE_DISCONNECTED;
}
public BluetoothDevice getDevice() {
/*
* Disconnected is the only state where device can change, and to prevent the race
* condition of reporting a valid device while disconnected fix the report here. Note that
* Synchronization of the state and device is not possible with current state machine
* desingn since the actual Transition happens sometime after the transitionTo method.
*/
if (getCurrentState() instanceof Disconnected) {
return null;
}
return mCurrentDevice;
}
Context getContext() {
return mService;
}
public void dump(StringBuilder sb) {
ProfileService.println(sb, "mCurrentDevice: " + mCurrentDevice.getAddress() + "("
+ mCurrentDevice.getName() + ") " + this.toString());
}
}
|