Debian Codegraph @

core/java/com/android/internal/power/MeasuredEnergyStats.java

raw symbols SCIP
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 com.android.internal.power;
18
19
20 import static android.os.BatteryStats.POWER_DATA_UNAVAILABLE;
21
22 import android.annotation.IntDef;
23 import android.annotation.NonNull;
24 import android.annotation.Nullable;
25 import android.os.Parcel;
26 import android.text.TextUtils;
27 import android.util.DebugUtils;
28 import android.util.Slog;
29 import android.view.Display;
30
31 import com.android.internal.annotations.VisibleForTesting;
32 import com.android.internal.os.LongMultiStateCounter;
33
34 import java.io.PrintWriter;
35 import java.lang.annotation.Retention;
36 import java.lang.annotation.RetentionPolicy;
37 import java.util.Arrays;
38
39 /**
40 * Tracks the measured charge consumption of various subsystems according to their
41 * {@link StandardPowerBucket} or custom power bucket (which is tied to
42 * {@link android.hardware.power.stats.EnergyConsumer.ordinal}).
43 *
44 * This class doesn't use a TimeBase, and instead requires manually decisions about when to
45 * accumulate since it is trivial. However, in the future, a TimeBase could be used instead.
46 */
47 @VisibleForTesting
48 public class MeasuredEnergyStats {
49 private static final String TAG = "MeasuredEnergyStats";
50
51 // Note: {@link com.android.internal.os.BatteryStatsImpl#VERSION} MUST be updated if standard
52 // power bucket integers are modified/added/removed.
53 public static final int POWER_BUCKET_UNKNOWN = -1;
54 public static final int POWER_BUCKET_SCREEN_ON = 0;
55 public static final int POWER_BUCKET_SCREEN_DOZE = 1;
56 public static final int POWER_BUCKET_SCREEN_OTHER = 2;
57 public static final int POWER_BUCKET_CPU = 3;
58 public static final int POWER_BUCKET_WIFI = 4;
59 public static final int POWER_BUCKET_BLUETOOTH = 5;
60 public static final int POWER_BUCKET_GNSS = 6;
61 public static final int POWER_BUCKET_MOBILE_RADIO = 7;
62 public static final int NUMBER_STANDARD_POWER_BUCKETS = 8; // Buckets above this are custom.
63
64 @IntDef(prefix = {"POWER_BUCKET_"}, value = {
65 POWER_BUCKET_UNKNOWN,
66 POWER_BUCKET_SCREEN_ON,
67 POWER_BUCKET_SCREEN_DOZE,
68 POWER_BUCKET_SCREEN_OTHER,
69 POWER_BUCKET_CPU,
70 POWER_BUCKET_WIFI,
71 POWER_BUCKET_BLUETOOTH,
72 POWER_BUCKET_GNSS,
73 POWER_BUCKET_MOBILE_RADIO,
74 })
75 @Retention(RetentionPolicy.SOURCE)
76 public @interface StandardPowerBucket {
77 }
78
79 private static final int INVALID_STATE = -1;
80
81 /**
82 * Configuration of measured energy stats: which power rails (buckets) are supported on
83 * this device, what custom power drains are supported etc.
84 */
85 public static class Config {
86 private final boolean[] mSupportedStandardBuckets;
87 @NonNull
88 private final String[] mCustomBucketNames;
89 private final boolean[] mSupportedMultiStateBuckets;
90 @NonNull
91 private final String[] mStateNames;
92
93 public Config(@NonNull boolean[] supportedStandardBuckets,
94 @Nullable String[] customBucketNames,
95 @NonNull int[] supportedMultiStateBuckets,
96 @Nullable String[] stateNames) {
97 mSupportedStandardBuckets = supportedStandardBuckets;
98 mCustomBucketNames = customBucketNames != null ? customBucketNames : new String[0];
99 mSupportedMultiStateBuckets =
100 new boolean[supportedStandardBuckets.length + mCustomBucketNames.length];
101 for (int bucket : supportedMultiStateBuckets) {
102 if (mSupportedStandardBuckets[bucket]) {
103 mSupportedMultiStateBuckets[bucket] = true;
104 }
105 }
106 mStateNames = stateNames != null ? stateNames : new String[] {""};
107 }
108
109 /**
110 * Returns true if the supplied Config is compatible with this one and therefore
111 * data collected with one of them will work with the other.
112 */
113 public boolean isCompatible(Config other) {
114 return Arrays.equals(mSupportedStandardBuckets, other.mSupportedStandardBuckets)
115 && Arrays.equals(mCustomBucketNames, other.mCustomBucketNames)
116 && Arrays.equals(mSupportedMultiStateBuckets,
117 other.mSupportedMultiStateBuckets)
118 && Arrays.equals(mStateNames, other.mStateNames);
119 }
120
121 /**
122 * Writes the Config object into the supplied Parcel.
123 */
124 public static void writeToParcel(@Nullable Config config, Parcel out) {
125 if (config == null) {
126 out.writeBoolean(false);
127 return;
128 }
129
130 out.writeBoolean(true);
131 out.writeInt(config.mSupportedStandardBuckets.length);
132 out.writeBooleanArray(config.mSupportedStandardBuckets);
133 out.writeStringArray(config.mCustomBucketNames);
134 int multiStateBucketCount = 0;
135 for (boolean supported : config.mSupportedMultiStateBuckets) {
136 if (supported) {
137 multiStateBucketCount++;
138 }
139 }
140 final int[] supportedMultiStateBuckets = new int[multiStateBucketCount];
141 int index = 0;
142 for (int bucket = 0; bucket < config.mSupportedMultiStateBuckets.length; bucket++) {
143 if (config.mSupportedMultiStateBuckets[bucket]) {
144 supportedMultiStateBuckets[index++] = bucket;
145 }
146 }
147 out.writeInt(multiStateBucketCount);
148 out.writeIntArray(supportedMultiStateBuckets);
149 out.writeStringArray(config.mStateNames);
150 }
151
152 /**
153 * Reads a Config object from the supplied Parcel.
154 */
155 @Nullable
156 public static Config createFromParcel(Parcel in) {
157 if (!in.readBoolean()) {
158 return null;
159 }
160
161 final int supportedStandardBucketCount = in.readInt();
162 final boolean[] supportedStandardBuckets = new boolean[supportedStandardBucketCount];
163 in.readBooleanArray(supportedStandardBuckets);
164 final String[] customBucketNames = in.readStringArray();
165 final int supportedMultiStateBucketCount = in.readInt();
166 final int[] supportedMultiStateBuckets = new int[supportedMultiStateBucketCount];
167 in.readIntArray(supportedMultiStateBuckets);
168 final String[] stateNames = in.readStringArray();
169 return new Config(supportedStandardBuckets, customBucketNames,
170 supportedMultiStateBuckets, stateNames);
171 }
172
173 /** Get number of possible buckets, including both standard and custom ones. */
174 private int getNumberOfBuckets() {
175 return mSupportedStandardBuckets.length + mCustomBucketNames.length;
176 }
177
178 /**
179 * Returns true if the specified charge bucket is tracked.
180 */
181 public boolean isSupportedBucket(int index) {
182 return mSupportedStandardBuckets[index];
183 }
184
185 @NonNull
186 public String[] getCustomBucketNames() {
187 return mCustomBucketNames;
188 }
189
190 /**
191 * Returns true if the specified charge bucket is tracked on a per-state basis.
192 */
193 public boolean isSupportedMultiStateBucket(int index) {
194 return mSupportedMultiStateBuckets[index];
195 }
196
197 @NonNull
198 public String[] getStateNames() {
199 return mStateNames;
200 }
201
202 /**
203 * If the index is a standard bucket, returns its name; otherwise returns its prefixed
204 * custom bucket number.
205 */
206 private String getBucketName(int index) {
207 if (isValidStandardBucket(index)) {
208 return DebugUtils.valueToString(MeasuredEnergyStats.class, "POWER_BUCKET_", index);
209 }
210 final int customBucket = indexToCustomBucket(index);
211 StringBuilder name = new StringBuilder().append("CUSTOM_").append(customBucket);
212 if (!TextUtils.isEmpty(mCustomBucketNames[customBucket])) {
213 name.append('(').append(mCustomBucketNames[customBucket]).append(')');
214 }
215 return name.toString();
216 }
217 }
218
219 private final Config mConfig;
220
221 /**
222 * Total charge (in microcoulombs) that a power bucket (including both
223 * {@link StandardPowerBucket} and custom buckets) has accumulated since the last reset.
224 * Values MUST be non-zero or POWER_DATA_UNAVAILABLE. Accumulation only occurs
225 * while the necessary conditions are satisfied (e.g. on battery).
226 *
227 * Charge for both {@link StandardPowerBucket}s and custom power buckets are stored in this
228 * array, and may internally both referred to as 'buckets'. This is an implementation detail;
229 * externally, we differentiate between these two data sources.
230 *
231 * Warning: Long array is used for access speed. If the number of supported subsystems
232 * becomes large, consider using an alternate data structure such as a SparseLongArray.
233 */
234 private final long[] mAccumulatedChargeMicroCoulomb;
235
236 private LongMultiStateCounter[] mAccumulatedMultiStateChargeMicroCoulomb;
237 private int mState = INVALID_STATE;
238 private long mStateChangeTimestampMs;
239
240 /**
241 * Creates a MeasuredEnergyStats set to support the provided power buckets.
242 * supportedStandardBuckets must be of size {@link #NUMBER_STANDARD_POWER_BUCKETS}.
243 * numCustomBuckets >= 0 is the number of (non-standard) custom power buckets on the device.
244 */
245 public MeasuredEnergyStats(MeasuredEnergyStats.Config config) {
246 mConfig = config;
247 final int numTotalBuckets = config.getNumberOfBuckets();
248 mAccumulatedChargeMicroCoulomb = new long[numTotalBuckets];
249 // Initialize to all zeros where supported, otherwise POWER_DATA_UNAVAILABLE.
250 // All custom buckets are, by definition, supported, so their values stay at 0.
251 for (int stdBucket = 0; stdBucket < NUMBER_STANDARD_POWER_BUCKETS; stdBucket++) {
252 if (!mConfig.mSupportedStandardBuckets[stdBucket]) {
253 mAccumulatedChargeMicroCoulomb[stdBucket] = POWER_DATA_UNAVAILABLE;
254 }
255 }
256 }
257
258 /**
259 * Reads a MeasuredEnergyStats from the supplied Parcel.
260 */
261 @Nullable
262 public static MeasuredEnergyStats createFromParcel(Config config, Parcel in) {
263 if (!in.readBoolean()) {
264 return null;
265 }
266 return new MeasuredEnergyStats(config, in);
267 }
268
269 /** Construct from parcel. */
270 public MeasuredEnergyStats(MeasuredEnergyStats.Config config, Parcel in) {
271 mConfig = config;
272
273 final int size = in.readInt();
274 mAccumulatedChargeMicroCoulomb = new long[size];
275 in.readLongArray(mAccumulatedChargeMicroCoulomb);
276 if (in.readBoolean()) {
277 mAccumulatedMultiStateChargeMicroCoulomb = new LongMultiStateCounter[size];
278 for (int i = 0; i < size; i++) {
279 if (in.readBoolean()) {
280 mAccumulatedMultiStateChargeMicroCoulomb[i] =
281 LongMultiStateCounter.CREATOR.createFromParcel(in);
282 }
283 }
284 } else {
285 mAccumulatedMultiStateChargeMicroCoulomb = null;
286 }
287 }
288
289 /** Write to parcel */
290 public void writeToParcel(Parcel out) {
291 out.writeInt(mAccumulatedChargeMicroCoulomb.length);
292 out.writeLongArray(mAccumulatedChargeMicroCoulomb);
293 if (mAccumulatedMultiStateChargeMicroCoulomb != null) {
294 out.writeBoolean(true);
295 for (LongMultiStateCounter counter : mAccumulatedMultiStateChargeMicroCoulomb) {
296 if (counter != null) {
297 out.writeBoolean(true);
298 counter.writeToParcel(out, 0);
299 } else {
300 out.writeBoolean(false);
301 }
302 }
303 } else {
304 out.writeBoolean(false);
305 }
306 }
307
308 /**
309 * Read from summary parcel.
310 * Note: Measured subsystem (and therefore bucket) availability may be different from when the
311 * summary parcel was written. Availability has already been correctly set in the constructor.
312 * Note: {@link com.android.internal.os.BatteryStatsImpl#VERSION} must be updated if summary
313 * parceling changes.
314 *
315 * Corresponding write performed by {@link #writeSummaryToParcel(Parcel)}.
316 */
317 private void readSummaryFromParcel(Parcel in) {
318 final int numWrittenEntries = in.readInt();
319 for (int entry = 0; entry < numWrittenEntries; entry++) {
320 final int index = in.readInt();
321 final long chargeUC = in.readLong();
322 LongMultiStateCounter multiStateCounter = null;
323 if (in.readBoolean()) {
324 multiStateCounter = LongMultiStateCounter.CREATOR.createFromParcel(in);
325 if (mConfig == null
326 || multiStateCounter.getStateCount() != mConfig.getStateNames().length) {
327 multiStateCounter = null;
328 }
329 }
330
331 if (index < mAccumulatedChargeMicroCoulomb.length) {
332 setValueIfSupported(index, chargeUC);
333 if (multiStateCounter != null) {
334 if (mAccumulatedMultiStateChargeMicroCoulomb == null) {
335 mAccumulatedMultiStateChargeMicroCoulomb =
336 new LongMultiStateCounter[mAccumulatedChargeMicroCoulomb.length];
337 }
338 mAccumulatedMultiStateChargeMicroCoulomb[index] = multiStateCounter;
339 }
340 }
341 }
342 }
343
344 /**
345 * Write to summary parcel.
346 * Note: Measured subsystem availability may be different when the summary parcel is read.
347 *
348 * Corresponding read performed by {@link #readSummaryFromParcel(Parcel)}.
349 */
350 private void writeSummaryToParcel(Parcel out) {
351 final int posOfNumWrittenEntries = out.dataPosition();
352 out.writeInt(0);
353 int numWrittenEntries = 0;
354 // Write only the supported buckets (with non-zero charge, if applicable).
355 for (int index = 0; index < mAccumulatedChargeMicroCoulomb.length; index++) {
356 final long charge = mAccumulatedChargeMicroCoulomb[index];
357 if (charge <= 0) continue;
358
359 out.writeInt(index);
360 out.writeLong(charge);
361 if (mAccumulatedMultiStateChargeMicroCoulomb != null
362 && mAccumulatedMultiStateChargeMicroCoulomb[index] != null) {
363 out.writeBoolean(true);
364 mAccumulatedMultiStateChargeMicroCoulomb[index].writeToParcel(out, 0);
365 } else {
366 out.writeBoolean(false);
367 }
368 numWrittenEntries++;
369 }
370 final int currPos = out.dataPosition();
371 out.setDataPosition(posOfNumWrittenEntries);
372 out.writeInt(numWrittenEntries);
373 out.setDataPosition(currPos);
374 }
375
376 /** Updates the given standard power bucket with the given charge if accumulate is true. */
377 public void updateStandardBucket(@StandardPowerBucket int bucket, long chargeDeltaUC) {
378 updateStandardBucket(bucket, chargeDeltaUC, 0);
379 }
380
381 /**
382 * Updates the given standard power bucket with the given charge if supported.
383 * @param timestampMs elapsed realtime in milliseconds
384 */
385 public void updateStandardBucket(@StandardPowerBucket int bucket, long chargeDeltaUC,
386 long timestampMs) {
387 checkValidStandardBucket(bucket);
388 updateEntry(bucket, chargeDeltaUC, timestampMs);
389 }
390
391 /** Updates the given custom power bucket with the given charge if accumulate is true. */
392 public void updateCustomBucket(int customBucket, long chargeDeltaUC) {
393 updateCustomBucket(customBucket, chargeDeltaUC, 0);
394 }
395
396 /**
397 * Updates the given custom power bucket with the given charge if supported.
398 * @param timestampMs elapsed realtime in milliseconds
399 */
400 public void updateCustomBucket(int customBucket, long chargeDeltaUC, long timestampMs) {
401 if (!isValidCustomBucket(customBucket)) {
402 Slog.e(TAG, "Attempted to update invalid custom bucket " + customBucket);
403 return;
404 }
405 final int index = customBucketToIndex(customBucket);
406 updateEntry(index, chargeDeltaUC, timestampMs);
407 }
408
409 /** Updates the given bucket with the given charge delta. */
410 private void updateEntry(int index, long chargeDeltaUC, long timestampMs) {
411 if (mAccumulatedChargeMicroCoulomb[index] >= 0L) {
412 mAccumulatedChargeMicroCoulomb[index] += chargeDeltaUC;
413 if (mState != INVALID_STATE && mConfig.isSupportedMultiStateBucket(index)) {
414 if (mAccumulatedMultiStateChargeMicroCoulomb == null) {
415 mAccumulatedMultiStateChargeMicroCoulomb =
416 new LongMultiStateCounter[mAccumulatedChargeMicroCoulomb.length];
417 }
418 LongMultiStateCounter counter =
419 mAccumulatedMultiStateChargeMicroCoulomb[index];
420 if (counter == null) {
421 counter = new LongMultiStateCounter(mConfig.mStateNames.length);
422 mAccumulatedMultiStateChargeMicroCoulomb[index] = counter;
423 counter.setState(mState, mStateChangeTimestampMs);
424 counter.updateValue(0, mStateChangeTimestampMs);
425 }
426 counter.updateValue(mAccumulatedChargeMicroCoulomb[index], timestampMs);
427 }
428 } else {
429 Slog.wtf(TAG, "Attempting to add " + chargeDeltaUC + " to unavailable bucket "
430 + mConfig.getBucketName(index) + " whose value was "
431 + mAccumulatedChargeMicroCoulomb[index]);
432 }
433 }
434
435 /**
436 * Updates the "state" on all multi-state counters used by this MeasuredEnergyStats. Further
437 * accumulated charge updates will assign the deltas to this state, until the state changes.
438 *
439 * If setState is never called on a MeasuredEnergyStats object, then it does not track
440 * per-state usage.
441 */
442 public void setState(int state, long timestampMs) {
443 mState = state;
444 mStateChangeTimestampMs = timestampMs;
445 if (mAccumulatedMultiStateChargeMicroCoulomb == null) {
446 mAccumulatedMultiStateChargeMicroCoulomb =
447 new LongMultiStateCounter[mAccumulatedChargeMicroCoulomb.length];
448 }
449 for (int i = 0; i < mAccumulatedMultiStateChargeMicroCoulomb.length; i++) {
450 LongMultiStateCounter counter = mAccumulatedMultiStateChargeMicroCoulomb[i];
451 if (counter == null && mConfig.isSupportedMultiStateBucket(i)) {
452 counter = new LongMultiStateCounter(mConfig.mStateNames.length);
453 counter.updateValue(0, timestampMs);
454 mAccumulatedMultiStateChargeMicroCoulomb[i] = counter;
455 }
456 if (counter != null) {
457 counter.setState(state, timestampMs);
458 }
459 }
460 }
461
462 /**
463 * Return accumulated charge (in microcouloumb) for a standard power bucket since last reset.
464 * Returns {@link android.os.BatteryStats#POWER_DATA_UNAVAILABLE} if this data is unavailable.
465 * @throws IllegalArgumentException if no such {@link StandardPowerBucket}.
466 */
467 public long getAccumulatedStandardBucketCharge(@StandardPowerBucket int bucket) {
468 checkValidStandardBucket(bucket);
469 return mAccumulatedChargeMicroCoulomb[bucket];
470 }
471
472 /**
473 * Returns the accumulated charge (in microcouloumb) for the standard power bucket and
474 * the specified state since last reset.
475 *
476 * Returns {@link android.os.BatteryStats#POWER_DATA_UNAVAILABLE} if this data is unavailable.
477 */
478 public long getAccumulatedStandardBucketCharge(@StandardPowerBucket int bucket, int state) {
479 if (!mConfig.isSupportedMultiStateBucket(bucket)) {
480 return POWER_DATA_UNAVAILABLE;
481 }
482 if (mAccumulatedMultiStateChargeMicroCoulomb == null) {
483 return 0;
484 }
485 final LongMultiStateCounter counter = mAccumulatedMultiStateChargeMicroCoulomb[bucket];
486 if (counter == null) {
487 return 0;
488 }
489 return counter.getCount(state);
490 }
491
492 /**
493 * Return accumulated charge (in microcoulomb) for the a custom power bucket since last
494 * reset.
495 * Returns {@link android.os.BatteryStats#POWER_DATA_UNAVAILABLE} if this data is unavailable.
496 */
497 @VisibleForTesting
498 public long getAccumulatedCustomBucketCharge(int customBucket) {
499 if (!isValidCustomBucket(customBucket)) {
500 return POWER_DATA_UNAVAILABLE;
501 }
502 return mAccumulatedChargeMicroCoulomb[customBucketToIndex(customBucket)];
503 }
504
505 /**
506 * Return accumulated charge (in microcoulomb) for all custom power buckets since last reset.
507 */
508 public @NonNull long[] getAccumulatedCustomBucketCharges() {
509 final long[] charges = new long[getNumberCustomPowerBuckets()];
510 for (int bucket = 0; bucket < charges.length; bucket++) {
511 charges[bucket] = mAccumulatedChargeMicroCoulomb[customBucketToIndex(bucket)];
512 }
513 return charges;
514 }
515
516 /**
517 * Map {@link android.view.Display} STATE_ to corresponding {@link StandardPowerBucket}.
518 */
519 public static @StandardPowerBucket int getDisplayPowerBucket(int screenState) {
520 if (Display.isOnState(screenState)) {
521 return POWER_BUCKET_SCREEN_ON;
522 }
523 if (Display.isDozeState(screenState)) {
524 return POWER_BUCKET_SCREEN_DOZE;
525 }
526 return POWER_BUCKET_SCREEN_OTHER;
527 }
528
529 /**
530 * Create a MeasuredEnergyStats using the template to determine which buckets are supported,
531 * and populate this new object from the given parcel.
532 *
533 * The parcel must be consistent with the template in terms of the number of
534 * possible (not necessarily supported) standard and custom buckets.
535 *
536 * Corresponding write performed by
537 * {@link #writeSummaryToParcel(MeasuredEnergyStats, Parcel)}.
538 *
539 * @return a new MeasuredEnergyStats object as described.
540 * Returns null if the stats contain no non-0 information (such as if template is null
541 * or if the parcel indicates there is no data to populate).
542 */
543 public static @Nullable MeasuredEnergyStats createAndReadSummaryFromParcel(
544 @Nullable Config config, Parcel in) {
545 final int arraySize = in.readInt();
546 // Check if any MeasuredEnergyStats exists on the parcel
547 if (arraySize == 0) return null;
548
549 if (config == null) {
550 // Nothing supported anymore. Create placeholder object just to consume the parcel data.
551 final MeasuredEnergyStats mes = new MeasuredEnergyStats(
552 new Config(new boolean[arraySize], null, new int[0], new String[]{""}));
553 mes.readSummaryFromParcel(in);
554 return null;
555 }
556
557 if (arraySize != config.getNumberOfBuckets()) {
558 Slog.wtf(TAG, "Size of MeasuredEnergyStats parcel (" + arraySize
559 + ") does not match config (" + config.getNumberOfBuckets() + ").");
560 // Something is horribly wrong. Just consume the parcel and return null.
561 final MeasuredEnergyStats mes = new MeasuredEnergyStats(config);
562 mes.readSummaryFromParcel(in);
563 return null;
564 }
565
566 final MeasuredEnergyStats stats = new MeasuredEnergyStats(config);
567 stats.readSummaryFromParcel(in);
568 if (stats.containsInterestingData()) {
569 return stats;
570 } else {
571 // Don't waste RAM on it (and make sure not to persist it in the next writeSummary)
572 return null;
573 }
574 }
575
576 /** Returns true iff any of the buckets are supported and non-zero. */
577 private boolean containsInterestingData() {
578 for (int index = 0; index < mAccumulatedChargeMicroCoulomb.length; index++) {
579 if (mAccumulatedChargeMicroCoulomb[index] > 0) return true;
580 }
581 return false;
582 }
583
584 /**
585 * Write a MeasuredEnergyStats to a parcel. If the stats is null, just write a 0.
586 *
587 * Corresponding read performed by {@link #createAndReadSummaryFromParcel}.
588 */
589 public static void writeSummaryToParcel(@Nullable MeasuredEnergyStats stats, Parcel dest) {
590 if (stats == null) {
591 dest.writeInt(0);
592 return;
593 }
594 dest.writeInt(stats.mConfig.getNumberOfBuckets());
595 stats.writeSummaryToParcel(dest);
596 }
597
598 /** Reset accumulated charges. */
599 private void reset() {
600 final int numIndices = mConfig.getNumberOfBuckets();
601 for (int index = 0; index < numIndices; index++) {
602 setValueIfSupported(index, 0L);
603 if (mAccumulatedMultiStateChargeMicroCoulomb != null
604 && mAccumulatedMultiStateChargeMicroCoulomb[index] != null) {
605 mAccumulatedMultiStateChargeMicroCoulomb[index].reset();
606 }
607 }
608 }
609
610 /** Reset accumulated charges of the given stats. */
611 public static void resetIfNotNull(@Nullable MeasuredEnergyStats stats) {
612 if (stats != null) stats.reset();
613 }
614
615 /** If the index is AVAILABLE, overwrite its value; otherwise leave it as UNAVAILABLE. */
616 private void setValueIfSupported(int index, long value) {
617 if (mAccumulatedChargeMicroCoulomb[index] != POWER_DATA_UNAVAILABLE) {
618 mAccumulatedChargeMicroCoulomb[index] = value;
619 }
620 }
621
622 /**
623 * Check if measuring the charge consumption of the given bucket is supported by this device.
624 * @throws IllegalArgumentException if not a valid {@link StandardPowerBucket}.
625 */
626 public boolean isStandardBucketSupported(@StandardPowerBucket int bucket) {
627 checkValidStandardBucket(bucket);
628 return isIndexSupported(bucket);
629 }
630
631 private boolean isIndexSupported(int index) {
632 return mAccumulatedChargeMicroCoulomb[index] != POWER_DATA_UNAVAILABLE;
633 }
634
635 /** Dump debug data. */
636 public void dump(PrintWriter pw) {
637 pw.print(" ");
638 for (int index = 0; index < mAccumulatedChargeMicroCoulomb.length; index++) {
639 pw.print(mConfig.getBucketName(index));
640 pw.print(" : ");
641 pw.print(mAccumulatedChargeMicroCoulomb[index]);
642 if (!isIndexSupported(index)) {
643 pw.print(" (unsupported)");
644 }
645 if (mAccumulatedMultiStateChargeMicroCoulomb != null) {
646 final LongMultiStateCounter counter =
647 mAccumulatedMultiStateChargeMicroCoulomb[index];
648 if (counter != null) {
649 pw.print(" [");
650 for (int i = 0; i < mConfig.mStateNames.length; i++) {
651 if (i != 0) {
652 pw.print(" ");
653 }
654 pw.print(mConfig.mStateNames[i]);
655 pw.print(": ");
656 pw.print(counter.getCount(i));
657 }
658 pw.print("]");
659 }
660 }
661 if (index != mAccumulatedChargeMicroCoulomb.length - 1) {
662 pw.print(", ");
663 }
664 }
665 pw.println();
666 }
667
668 /** Get the number of custom power buckets on this device. */
669 public int getNumberCustomPowerBuckets() {
670 return mAccumulatedChargeMicroCoulomb.length - NUMBER_STANDARD_POWER_BUCKETS;
671 }
672
673 private static int customBucketToIndex(int customBucket) {
674 return customBucket + NUMBER_STANDARD_POWER_BUCKETS;
675 }
676
677 private static int indexToCustomBucket(int index) {
678 return index - NUMBER_STANDARD_POWER_BUCKETS;
679 }
680
681 private static void checkValidStandardBucket(@StandardPowerBucket int bucket) {
682 if (!isValidStandardBucket(bucket)) {
683 throw new IllegalArgumentException("Illegal StandardPowerBucket " + bucket);
684 }
685 }
686
687 private static boolean isValidStandardBucket(@StandardPowerBucket int bucket) {
688 return bucket >= 0 && bucket < NUMBER_STANDARD_POWER_BUCKETS;
689 }
690
691 /** Returns whether the given custom bucket is valid (exists) on this device. */
692 @VisibleForTesting
693 public boolean isValidCustomBucket(int customBucket) {
694 return customBucket >= 0
695 && customBucketToIndex(customBucket) < mAccumulatedChargeMicroCoulomb.length;
696 }
697 }