1 /*
2  * Copyright (C) 2017 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package android.platform.test.longevity.listener;
17 
18 import android.content.Context;
19 import android.content.Intent;
20 import android.content.IntentFilter;
21 import android.host.test.longevity.listener.RunTerminator;
22 import android.util.Log;
23 
24 import androidx.annotation.VisibleForTesting;
25 
26 import org.junit.runner.Description;
27 import org.junit.runner.notification.RunNotifier;
28 
29 import java.util.Map;
30 
31 /**
32  * A {@link RunTerminator} for terminating early on test end due to low battery.
33  */
34 public final class BatteryTerminator extends RunTerminator {
35     @VisibleForTesting
36     static final String OPTION = "min-battery";
37     private static final double DEFAULT = 0.05; // 5% battery
38 
39     private final Context mContext;
40     private final double mMinBattery;
41 
BatteryTerminator(RunNotifier notifier, Map<String, String> args, Context context)42     public BatteryTerminator(RunNotifier notifier, Map<String, String> args, Context context) {
43         super(notifier);
44         mMinBattery = args.containsKey(OPTION) ? Double.parseDouble(args.get(OPTION)) : DEFAULT;
45         mContext = context;
46     }
47 
48     /**
49      * Returns the battery level of the current device, in percent format (0.05 = 5%).
50      */
getBatteryLevel()51     private double getBatteryLevel() {
52         Intent batteryIntent =
53             mContext.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
54         int level = batteryIntent.getIntExtra("level", -1);
55         int scale = batteryIntent.getIntExtra("scale", -1);
56         if (level < 0 || scale <= 0) {
57             throw new RuntimeException("Failed to get proper battery levels.");
58         }
59         return (double) level / (double) scale;
60     }
61 
62     @Override
testFinished(Description description)63     public void testFinished(Description description) {
64         if (getBatteryLevel() < mMinBattery) {
65             kill(String.format("battery fell below %.2f%%", mMinBattery * 100.0f));
66         }
67     }
68 
69     /**
70      * Prints messages to logcat.
71      */
72     @Override
print(String reason)73     protected void print(String reason) {
74         Log.e(getClass().getSimpleName(), reason);
75     }
76 }
77