1 /*
2  * Copyright (C) 2020 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 
17 package android.os;
18 
19 import android.annotation.IntDef;
20 import android.annotation.NonNull;
21 import android.util.IntArray;
22 
23 import java.lang.annotation.Retention;
24 import java.lang.annotation.RetentionPolicy;
25 
26 /**
27  * Query parameters for the {@link BatteryStatsManager#getBatteryUsageStats()} call.
28  *
29  * @hide
30  */
31 public final class BatteryUsageStatsQuery implements Parcelable {
32 
33     @NonNull
34     public static final BatteryUsageStatsQuery DEFAULT =
35             new BatteryUsageStatsQuery.Builder().build();
36 
37     /**
38      * Flags for the {@link BatteryStatsManager#getBatteryUsageStats()} method.
39      * @hide
40      */
41     @IntDef(flag = true, prefix = { "FLAG_BATTERY_USAGE_STATS_" }, value = {
42             FLAG_BATTERY_USAGE_STATS_POWER_PROFILE_MODEL,
43             FLAG_BATTERY_USAGE_STATS_INCLUDE_HISTORY,
44             FLAG_BATTERY_USAGE_STATS_INCLUDE_PROCESS_STATE_DATA,
45             FLAG_BATTERY_USAGE_STATS_INCLUDE_VIRTUAL_UIDS,
46     })
47     @Retention(RetentionPolicy.SOURCE)
48     public @interface BatteryUsageStatsFlags {}
49 
50     /**
51      * Indicates that power estimations should be based on the usage time and
52      * average power constants provided in the PowerProfile, even if on-device power monitoring
53      * is available.
54      *
55      * @hide
56      */
57     public static final int FLAG_BATTERY_USAGE_STATS_POWER_PROFILE_MODEL = 0x0001;
58 
59     /**
60      * Indicates that battery history should be included in the BatteryUsageStats.
61      * @hide
62      */
63     public static final int FLAG_BATTERY_USAGE_STATS_INCLUDE_HISTORY = 0x0002;
64 
65     /**
66      * Indicates that identifiers of power models used for computations of power
67      * consumption should be included in the BatteryUsageStats.
68      */
69     public static final int FLAG_BATTERY_USAGE_STATS_INCLUDE_POWER_MODELS = 0x0004;
70 
71     public static final int FLAG_BATTERY_USAGE_STATS_INCLUDE_PROCESS_STATE_DATA = 0x0008;
72 
73     public static final int FLAG_BATTERY_USAGE_STATS_INCLUDE_VIRTUAL_UIDS = 0x0010;
74 
75     private static final long DEFAULT_MAX_STATS_AGE_MS = 5 * 60 * 1000;
76 
77     private final int mFlags;
78     @NonNull
79     private final int[] mUserIds;
80     private final long mMaxStatsAgeMs;
81     private final long mFromTimestamp;
82     private final long mToTimestamp;
83     private final double mMinConsumedPowerThreshold;
84     private final @BatteryConsumer.PowerComponent int[] mPowerComponents;
85 
BatteryUsageStatsQuery(@onNull Builder builder)86     private BatteryUsageStatsQuery(@NonNull Builder builder) {
87         mFlags = builder.mFlags;
88         mUserIds = builder.mUserIds != null ? builder.mUserIds.toArray()
89                 : new int[]{UserHandle.USER_ALL};
90         mMaxStatsAgeMs = builder.mMaxStatsAgeMs;
91         mMinConsumedPowerThreshold = builder.mMinConsumedPowerThreshold;
92         mFromTimestamp = builder.mFromTimestamp;
93         mToTimestamp = builder.mToTimestamp;
94         mPowerComponents = builder.mPowerComponents;
95     }
96 
97     @BatteryUsageStatsFlags
getFlags()98     public int getFlags() {
99         return mFlags;
100     }
101 
102     /**
103      * Returns an array of users for which the attribution is requested.  It may
104      * contain {@link UserHandle#USER_ALL} to indicate that the attribution
105      * should be performed for all users. Battery consumed by users <b>not</b> included
106      * in this array will be returned in the aggregated form as {@link UserBatteryConsumer}'s.
107      */
108     @NonNull
getUserIds()109     public int[] getUserIds() {
110         return mUserIds;
111     }
112 
113     /**
114      * Returns true if the power calculations must be based on the PowerProfile constants,
115      * even if measured energy data is available.
116      */
shouldForceUsePowerProfileModel()117     public boolean shouldForceUsePowerProfileModel() {
118         return (mFlags & FLAG_BATTERY_USAGE_STATS_POWER_PROFILE_MODEL) != 0;
119     }
120 
isProcessStateDataNeeded()121     public boolean isProcessStateDataNeeded() {
122         return (mFlags & FLAG_BATTERY_USAGE_STATS_INCLUDE_PROCESS_STATE_DATA) != 0;
123     }
124 
125     /**
126      * Returns the power components that should be estimated or null if all power components
127      * are being requested.
128      */
getPowerComponents()129     public int[] getPowerComponents() {
130         return mPowerComponents;
131     }
132 
133     /**
134      * Returns the client's tolerance for stale battery stats. The data is allowed to be up to
135      * this many milliseconds out-of-date.
136      */
getMaxStatsAge()137     public long getMaxStatsAge() {
138         return mMaxStatsAgeMs;
139     }
140 
141     /**
142      * Returns the minimal power component consumed power threshold. The small power consuming
143      * components will be reported as zero.
144      */
getMinConsumedPowerThreshold()145     public double getMinConsumedPowerThreshold() {
146         return mMinConsumedPowerThreshold;
147     }
148 
149     /**
150      * Returns the exclusive lower bound of the stored snapshot timestamps that should be included
151      * in the aggregation.  Ignored if {@link #getToTimestamp()} is zero.
152      */
getFromTimestamp()153     public long getFromTimestamp() {
154         return mFromTimestamp;
155     }
156 
157     /**
158      * Returns the inclusive upper bound of the stored snapshot timestamps that should
159      * be included in the aggregation.  The default is to include only the current stats
160      * accumulated since the latest battery reset.
161      */
getToTimestamp()162     public long getToTimestamp() {
163         return mToTimestamp;
164     }
165 
BatteryUsageStatsQuery(Parcel in)166     private BatteryUsageStatsQuery(Parcel in) {
167         mFlags = in.readInt();
168         mUserIds = new int[in.readInt()];
169         in.readIntArray(mUserIds);
170         mMaxStatsAgeMs = in.readLong();
171         mMinConsumedPowerThreshold = in.readDouble();
172         mFromTimestamp = in.readLong();
173         mToTimestamp = in.readLong();
174         mPowerComponents = in.createIntArray();
175     }
176 
177     @Override
writeToParcel(Parcel dest, int flags)178     public void writeToParcel(Parcel dest, int flags) {
179         dest.writeInt(mFlags);
180         dest.writeInt(mUserIds.length);
181         dest.writeIntArray(mUserIds);
182         dest.writeLong(mMaxStatsAgeMs);
183         dest.writeDouble(mMinConsumedPowerThreshold);
184         dest.writeLong(mFromTimestamp);
185         dest.writeLong(mToTimestamp);
186         dest.writeIntArray(mPowerComponents);
187     }
188 
189     @Override
describeContents()190     public int describeContents() {
191         return 0;
192     }
193 
194     @NonNull
195     public static final Creator<BatteryUsageStatsQuery> CREATOR =
196             new Creator<BatteryUsageStatsQuery>() {
197                 @Override
198                 public BatteryUsageStatsQuery createFromParcel(Parcel in) {
199                     return new BatteryUsageStatsQuery(in);
200                 }
201 
202                 @Override
203                 public BatteryUsageStatsQuery[] newArray(int size) {
204                     return new BatteryUsageStatsQuery[size];
205                 }
206             };
207 
208     /**
209      * Builder for BatteryUsageStatsQuery.
210      */
211     public static final class Builder {
212         private int mFlags;
213         private IntArray mUserIds;
214         private long mMaxStatsAgeMs = DEFAULT_MAX_STATS_AGE_MS;
215         private long mFromTimestamp;
216         private long mToTimestamp;
217         private double mMinConsumedPowerThreshold = 0;
218         private @BatteryConsumer.PowerComponent int[] mPowerComponents;
219 
220         /**
221          * Builds a read-only BatteryUsageStatsQuery object.
222          */
build()223         public BatteryUsageStatsQuery build() {
224             return new BatteryUsageStatsQuery(this);
225         }
226 
227         /**
228          * Add a user whose battery stats should be included in the battery usage stats.
229          * {@link UserHandle#USER_ALL} will be used by default if no users are added explicitly.
230          */
addUser(@onNull UserHandle userHandle)231         public Builder addUser(@NonNull UserHandle userHandle) {
232             if (mUserIds == null) {
233                 mUserIds = new IntArray(1);
234             }
235             mUserIds.add(userHandle.getIdentifier());
236             return this;
237         }
238 
239         /**
240          * Requests that battery history be included in the BatteryUsageStats.
241          */
includeBatteryHistory()242         public Builder includeBatteryHistory() {
243             mFlags |= BatteryUsageStatsQuery.FLAG_BATTERY_USAGE_STATS_INCLUDE_HISTORY;
244             return this;
245         }
246 
247         /**
248          * Requests that per-process state data be included in the BatteryUsageStats, if
249          * available. Check {@link BatteryUsageStats#isProcessStateDataIncluded()} on the result
250          * to see if the data is available.
251          */
includeProcessStateData()252         public Builder includeProcessStateData() {
253             mFlags |= BatteryUsageStatsQuery.FLAG_BATTERY_USAGE_STATS_INCLUDE_PROCESS_STATE_DATA;
254             return this;
255         }
256 
257         /**
258          * Requests to return modeled battery usage stats only, even if on-device
259          * power monitoring data is available.
260          *
261          * Should only be used for testing and debugging.
262          */
powerProfileModeledOnly()263         public Builder powerProfileModeledOnly() {
264             mFlags |= BatteryUsageStatsQuery.FLAG_BATTERY_USAGE_STATS_POWER_PROFILE_MODEL;
265             return this;
266         }
267 
268         /**
269          * Requests to return identifiers of models that were used for estimation
270          * of power consumption.
271          *
272          * Should only be used for testing and debugging.
273          */
includePowerModels()274         public Builder includePowerModels() {
275             mFlags |= BatteryUsageStatsQuery.FLAG_BATTERY_USAGE_STATS_INCLUDE_POWER_MODELS;
276             return this;
277         }
278 
279         /**
280          * Requests to return only statistics for the specified power components.  The default
281          * is all power components.
282          */
includePowerComponents( @atteryConsumer.PowerComponent int[] powerComponents)283         public Builder includePowerComponents(
284                 @BatteryConsumer.PowerComponent int[] powerComponents) {
285             mPowerComponents = powerComponents;
286             return this;
287         }
288 
289         /**
290          * Requests to return attribution data for virtual UIDs such as
291          * {@link Process#SDK_SANDBOX_VIRTUAL_UID}.
292          */
includeVirtualUids()293         public Builder includeVirtualUids() {
294             mFlags |= BatteryUsageStatsQuery.FLAG_BATTERY_USAGE_STATS_INCLUDE_VIRTUAL_UIDS;
295             return this;
296         }
297 
298         /**
299          * Requests to aggregate stored snapshots between the two supplied timestamps
300          * @param fromTimestamp Exclusive starting timestamp, as per System.currentTimeMillis()
301          * @param toTimestamp Inclusive ending timestamp, as per System.currentTimeMillis()
302          */
aggregateSnapshots(long fromTimestamp, long toTimestamp)303         public Builder aggregateSnapshots(long fromTimestamp, long toTimestamp) {
304             mFromTimestamp = fromTimestamp;
305             mToTimestamp = toTimestamp;
306             return this;
307         }
308 
309         /**
310          * Set the client's tolerance for stale battery stats. The data may be up to
311          * this many milliseconds out-of-date.
312          */
setMaxStatsAgeMs(long maxStatsAgeMs)313         public Builder setMaxStatsAgeMs(long maxStatsAgeMs) {
314             mMaxStatsAgeMs = maxStatsAgeMs;
315             return this;
316         }
317 
318         /**
319          * Set the minimal power component consumed power threshold. The small power consuming
320          * components will be reported as zero.
321          */
setMinConsumedPowerThreshold(double minConsumedPowerThreshold)322         public Builder setMinConsumedPowerThreshold(double minConsumedPowerThreshold) {
323             mMinConsumedPowerThreshold = minConsumedPowerThreshold;
324             return this;
325         }
326     }
327 }
328