1 /* 2 * Copyright (C) 2018 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.tradefed.device; 18 19 import com.android.ddmlib.AdbCommandRejectedException; 20 import com.android.ddmlib.IDevice; 21 import com.android.ddmlib.MultiLineReceiver; 22 import com.android.ddmlib.ShellCommandUnresponsiveException; 23 import com.android.ddmlib.TimeoutException; 24 import com.android.tradefed.log.LogUtil.CLog; 25 26 import java.io.IOException; 27 import java.util.regex.Matcher; 28 import java.util.regex.Pattern; 29 30 public class BatteryTemperature implements IBatteryTemperature { 31 32 /** Parse the output of "adb shell dumpsys battery" to collect the temperature. */ 33 class DumpsysBatteryTemperatureReceiver extends MultiLineReceiver { 34 /* 35 * The temperature is printed as numeric value in tenths of a degree, i.e. 36 * 512 indicates 51.2°C. 37 */ 38 private static final int DUMPSYS_BATTERY_TEMP_SCALE = 10; 39 40 /* The temperature is listed on a single line, like "temperature: 512" */ 41 private static final String BATTERY_REGEX = "temperature: ([0-9]+)"; 42 43 private int mDeviceBatteryTemp = 0; 44 getDeviceBatteryTemp()45 public int getDeviceBatteryTemp() { 46 return mDeviceBatteryTemp; 47 } 48 49 @Override isCancelled()50 public boolean isCancelled() { 51 return false; 52 } 53 54 @Override processNewLines(String[] lines)55 public void processNewLines(String[] lines) { 56 for (String line : lines) { 57 Pattern p = Pattern.compile(BATTERY_REGEX); 58 Matcher m = p.matcher(line); 59 if (m.find()) { 60 String tempString = m.group(1); 61 try { 62 mDeviceBatteryTemp = Integer.parseInt(tempString); 63 mDeviceBatteryTemp /= DUMPSYS_BATTERY_TEMP_SCALE; 64 } catch (NumberFormatException e) { 65 CLog.w("Failed to parse battery temperature: %s", line); 66 } 67 } 68 } 69 } 70 } 71 72 @Override getBatteryTemperature(IDevice device)73 public Integer getBatteryTemperature(IDevice device) { 74 DumpsysBatteryTemperatureReceiver receiver = new DumpsysBatteryTemperatureReceiver(); 75 76 try { 77 device.executeShellCommand("dumpsys battery", receiver); 78 } catch (TimeoutException 79 | AdbCommandRejectedException 80 | ShellCommandUnresponsiveException 81 | IOException e) { 82 return 0; 83 } 84 85 return receiver.getDeviceBatteryTemp(); 86 } 87 } 88