summaryrefslogtreecommitdiff
path: root/library/main/src/com/android/car/setupwizardlib/util/CarDrivingStateMonitor.java
blob: 0cb667b5a9402cee2d850d99c4ed7f9094d3bb31 (plain)
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
/*
 * Copyright (C) 2018 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.setupwizardlib.util;

import android.car.Car;
import android.car.CarNotConnectedException;
import android.car.VehicleAreaType;
import android.car.VehiclePropertyIds;
import android.car.drivingstate.CarUxRestrictions;
import android.car.drivingstate.CarUxRestrictionsManager;
import android.car.hardware.CarPropertyValue;
import android.car.hardware.property.CarPropertyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;

/**
 * Monitor that listens for changes in the driving state so that it can trigger an exit of the
 * setup wizard when {@link CarUxRestrictions.UX_RESTRICTIONS_NO_SETUP}
 * is active.
 */
public class CarDrivingStateMonitor implements
        CarUxRestrictionsManager.OnUxRestrictionsChangedListener {

    public static final String EXIT_BROADCAST_ACTION =
            "com.android.car.setupwizardlib.driving_exit";

    public static final String INTENT_EXTRA_REASON = "reason";
    public static final String REASON_GEAR_REVERSAL = "gear_reversal";

    private static final String TAG = "CarDrivingStateMonitor";
    private static final long DISCONNECT_DELAY_MS = 700;

    private static final int GEAR_REVERSE = 2;

    private Car mCar;
    private CarUxRestrictionsManager mRestrictionsManager;
    private CarPropertyManager mCarPropertyManager;
    // Need to track the number of times the monitor is started so a single stopMonitor call does
    // not override them all.
    private int mMonitorStartedCount;
    // Flag that allows the monitor to be started for a ux restrictions check but not kept running.
    // This is particularly useful when a DrivingExit is triggered by an app external to the base
    // setup wizard package and we need to verify that it is a valid driving exit.
    private boolean mStopMonitorAfterUxCheck;
    private final Context mContext;
    @VisibleForTesting
    final Handler mHandler = new Handler(Looper.getMainLooper());
    @VisibleForTesting
    final Runnable mDisconnectRunnable = this::disconnectCarMonitor;

    private final CarPropertyManager.CarPropertyEventCallback mGearChangeCallback =
            new CarPropertyManager.CarPropertyEventCallback() {
        @SuppressWarnings("rawtypes")
        @Override
        public void onChangeEvent(CarPropertyValue value) {
            switch (value.getPropertyId()) {
                case VehiclePropertyIds.GEAR_SELECTION:
                    if ((Integer) value.getValue() == GEAR_REVERSE) {
                        Log.v(TAG, "Gear has reversed, exiting SetupWizard.");
                        broadcastGearReversal();
                    }
                    break;
            }
        }

        @Override
        public void onErrorEvent(int propertyId, int zone) {}
    };

    private CarDrivingStateMonitor(Context context) {
        mContext = context.getApplicationContext();
    }

    /**
     * Returns the singleton instance of CarDrivingStateMonitor.
     */
    public static CarDrivingStateMonitor get(Context context) {
        return CarHelperRegistry.getOrCreateWithAppContext(
                context.getApplicationContext(),
                CarDrivingStateMonitor.class,
                CarDrivingStateMonitor::new);
    }

    /**
     * Starts the monitor listening to driving state changes.
     */
    public synchronized void startMonitor() {
        mMonitorStartedCount++;
        if (mMonitorStartedCount == 0) {
            Log.w(TAG, "MonitorStartedCount was negative");
            return;
        }
        mHandler.removeCallbacks(mDisconnectRunnable);
        Log.i(TAG, String.format(
                "Starting monitor, MonitorStartedCount = %d", mMonitorStartedCount));
        if (mCar != null) {
            if (mCar.isConnected()) {
                try {
                    onUxRestrictionsChanged(mRestrictionsManager.getCurrentCarUxRestrictions());
                } catch (CarNotConnectedException e) {
                    Log.e(TAG, "Car not connected", e);
                }
            } else {
                try {
                    mCar.connect();
                } catch (IllegalStateException e) {
                    // Connection failure - already connected or connecting.
                    Log.e(TAG, "Failure connecting to Car object.", e);
                }
            }
            return;
        }
        mCar = Car.createCar(mContext, new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                try {
                    registerPropertyManager();
                    registerRestrictionsManager();

                } catch (CarNotConnectedException e) {
                    Log.e(TAG, "Car not connected", e);
                }
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                try {
                    if (mRestrictionsManager != null) {
                        mRestrictionsManager.unregisterListener();
                        mRestrictionsManager = null;
                    }
                } catch (CarNotConnectedException e) {
                    Log.e(TAG, "Car not connected", e);
                }
            }
        });
        try {
            mCar.connect();
        } catch (IllegalStateException e) {
            // Connection failure - already connected or connecting.
            Log.e(TAG, "Failure connecting to Car object.", e);
        }
    }

    /**
     * Stops the monitor from listening for driving state changes. This will only occur after a
     * set delay so that calling stop/start in quick succession doesn't actually need to reconnect
     * to the service repeatedly. This monitor also maintains parity between started and stopped so
     * 2 started calls requires two stop calls to stop.
     */
    public synchronized void stopMonitor() {
        if (isVerboseLoggable()) {
            Log.v(TAG, "stopMonitor");
        }
        mHandler.removeCallbacks(mDisconnectRunnable);
        mMonitorStartedCount--;
        if (mMonitorStartedCount == 0) {
            if (isVerboseLoggable()) {
                Log.v(TAG, "Scheduling driving monitor timeout");
            }
            mHandler.postDelayed(mDisconnectRunnable, DISCONNECT_DELAY_MS);
        }
        if (mMonitorStartedCount < 0) {
            mMonitorStartedCount = 0;
        }
    }

    private void disconnectCarMonitor() {
        if (mMonitorStartedCount > 0) {
            if (isVerboseLoggable()) {
                Log.v(TAG, "MonitorStartedCount > 0, do nothing");
            }
            return;
        }
        Log.i(TAG, "Disconnecting Car Monitor");
        try {
            if (mRestrictionsManager != null) {
                mRestrictionsManager.unregisterListener();
                mRestrictionsManager = null;
            }
            if (mCarPropertyManager != null) {
                mCarPropertyManager.unregisterCallback(mGearChangeCallback);
                mCarPropertyManager = null;
            }
        } catch (CarNotConnectedException e) {
            Log.e(TAG, "Car not connected for unregistering listener", e);
        }

        if (mCar == null || !mCar.isConnected()) {
            return;
        }

        try {
            mCar.disconnect();
        } catch (IllegalStateException e) {
            // Connection failure - already disconnected or disconnecting.
            Log.e(TAG, "Failure disconnecting from Car object", e);
        }
    }

    /**
     * Returns {@code true} if the current driving state restricts setup from being completed.
     */
    public boolean checkIsSetupRestricted() {
        if (mMonitorStartedCount <= 0 && (mCar == null || !mCar.isConnected())) {
            if (isVerboseLoggable()) {
                Log.v(TAG, "Starting monitor to perform restriction check, returning false for "
                        + "restrictions in the meantime");
            }
            mStopMonitorAfterUxCheck = true;
            startMonitor();
            return false;
        }
        if (mRestrictionsManager == null) {
            if (isVerboseLoggable()) {
                Log.v(TAG, "Restrictions manager null in checkIsSetupRestricted, returning false");
            }
            return false;
        }
        try {
            return checkIsSetupRestricted(mRestrictionsManager.getCurrentCarUxRestrictions());
        } catch (CarNotConnectedException e) {
            Log.e(TAG, "CarNotConnected in checkIsSetupRestricted, returning false", e);
        }
        return false;
    }

    private boolean checkIsSetupRestricted(@Nullable CarUxRestrictions restrictionInfo) {
        return restrictionInfo != null && (restrictionInfo.getActiveRestrictions()
                & CarUxRestrictions.UX_RESTRICTIONS_NO_SETUP) != 0;
    }

    @Override
    public void onUxRestrictionsChanged(CarUxRestrictions restrictionInfo) {
        // Check if setup restriction is active.
        if (isVerboseLoggable()) {
            Log.v(TAG, "onUxRestrictionsChanged");
        }

        // Get the current CarUxRestrictions rather than trusting the ones passed in.
        // This prevents in part interference from other applications triggering a setup wizard
        // exit unnecessarily, though the broadcast is also checked on the receiver side.
        if (mRestrictionsManager != null) {
            try {
                restrictionInfo = mRestrictionsManager.getCurrentCarUxRestrictions();
            } catch (CarNotConnectedException e) {
                Log.e(TAG, "Car not connected in onUxRestrictionsChanged, doing nothing.", e);
            }
        }

        if (checkIsSetupRestricted(restrictionInfo)) {
            if (isVerboseLoggable()) {
                Log.v(TAG, "Triggering driving exit broadcast");
            }
            Intent broadcastIntent = new Intent();
            broadcastIntent.setAction(EXIT_BROADCAST_ACTION);
            mContext.sendBroadcast(broadcastIntent);
        }
    }

    private boolean isVerboseLoggable() {
        return Log.isLoggable(TAG, Log.VERBOSE);
    }

    /**
     * Resets the car driving state monitor. This is only for use in testing.
     */
    @VisibleForTesting
    public static void reset(Context context) {
        CarHelperRegistry.getRegistry(context).putHelper(
                CarDrivingStateMonitor.class, new CarDrivingStateMonitor(context));
    }

    private void registerRestrictionsManager() {
        mRestrictionsManager = (CarUxRestrictionsManager)
                mCar.getCarManager(Car.CAR_UX_RESTRICTION_SERVICE);
        if (mRestrictionsManager == null) {
            Log.e(TAG, "Unable to get CarUxRestrictionsManager");
            return;
        }
        onUxRestrictionsChanged(mRestrictionsManager.getCurrentCarUxRestrictions());
        mRestrictionsManager.registerListener(CarDrivingStateMonitor.this);
        if (mStopMonitorAfterUxCheck) {
            mStopMonitorAfterUxCheck = false;
            stopMonitor();
        }
    }

    private void registerPropertyManager() {
        mCarPropertyManager = (CarPropertyManager) mCar.getCarManager(Car.PROPERTY_SERVICE);
        if (mCarPropertyManager == null) {
            Log.e(TAG, "Unable to get CarPropertyManager");
            return;
        }
        mCarPropertyManager.registerCallback(
                mGearChangeCallback, VehiclePropertyIds.GEAR_SELECTION,
                CarPropertyManager.SENSOR_RATE_ONCHANGE);
        CarPropertyValue<Integer> gearSelection =
                mCarPropertyManager.getProperty(Integer.class, VehiclePropertyIds.GEAR_SELECTION,
                    VehicleAreaType.VEHICLE_AREA_TYPE_GLOBAL);
        if (gearSelection != null
                && gearSelection.getStatus() == CarPropertyValue.STATUS_AVAILABLE) {
            if (gearSelection.getValue() == GEAR_REVERSE) {
                Log.v(TAG, "SetupWizard started when gear is in reverse, exiting.");
                broadcastGearReversal();
            }
        } else {
            Log.e(TAG, "GEAR_SELECTION is not available.");
        }
    }

    private void broadcastGearReversal() {
        Intent intent = new Intent();
        intent.setAction(EXIT_BROADCAST_ACTION);
        intent.putExtra(INTENT_EXTRA_REASON, REASON_GEAR_REVERSAL);
        mContext.sendBroadcast(intent);
    }

}