blob: 3a9a59f85be6a6c926c4d148bb7bea640509d598 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 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
17package com.android.server;
18
19import com.android.internal.app.IBatteryStats;
20import com.android.server.am.BatteryStatsService;
21
22import android.app.ActivityManagerNative;
23import android.content.ContentResolver;
24import android.content.Context;
25import android.content.Intent;
26import android.content.pm.PackageManager;
27import android.os.BatteryManager;
28import android.os.Binder;
29import android.os.Debug;
30import android.os.IBinder;
31import android.os.RemoteException;
32import android.os.ServiceManager;
33import android.os.SystemClock;
34import android.os.UEventObserver;
35import android.provider.Checkin;
36import android.provider.Settings;
37import android.util.EventLog;
38import android.util.Log;
39
40import java.io.File;
41import java.io.FileDescriptor;
42import java.io.FileInputStream;
43import java.io.FileOutputStream;
44import java.io.IOException;
45import java.io.PrintWriter;
46
47
48
49/**
50 * <p>BatteryService monitors the charging status, and charge level of the device
51 * battery. When these values change this service broadcasts the new values
52 * to all {@link android.content.BroadcastReceiver IntentReceivers} that are
53 * watching the {@link android.content.Intent#ACTION_BATTERY_CHANGED
54 * BATTERY_CHANGED} action.</p>
55 * <p>The new values are stored in the Intent data and can be retrieved by
56 * calling {@link android.content.Intent#getExtra Intent.getExtra} with the
57 * following keys:</p>
58 * <p>&quot;scale&quot; - int, the maximum value for the charge level</p>
59 * <p>&quot;level&quot; - int, charge level, from 0 through &quot;scale&quot; inclusive</p>
60 * <p>&quot;status&quot; - String, the current charging status.<br />
61 * <p>&quot;health&quot; - String, the current battery health.<br />
62 * <p>&quot;present&quot; - boolean, true if the battery is present<br />
63 * <p>&quot;icon-small&quot; - int, suggested small icon to use for this state</p>
64 * <p>&quot;plugged&quot; - int, 0 if the device is not plugged in; 1 if plugged
65 * into an AC power adapter; 2 if plugged in via USB.</p>
66 * <p>&quot;voltage&quot; - int, current battery voltage in millivolts</p>
67 * <p>&quot;temperature&quot; - int, current battery temperature in tenths of
68 * a degree Centigrade</p>
69 * <p>&quot;technology&quot; - String, the type of battery installed, e.g. "Li-ion"</p>
70 */
71class BatteryService extends Binder {
72 private static final String TAG = BatteryService.class.getSimpleName();
73
74 private static final boolean LOCAL_LOGV = false;
75
76 static final int LOG_BATTERY_LEVEL = 2722;
77 static final int LOG_BATTERY_STATUS = 2723;
78 static final int LOG_BATTERY_DISCHARGE_STATUS = 2730;
79
80 static final int BATTERY_SCALE = 100; // battery capacity is a percentage
81
82 // Used locally for determining when to make a last ditch effort to log
83 // discharge stats before the device dies.
84 private static final int CRITICAL_BATTERY_LEVEL = 4;
85
86 private static final int DUMP_MAX_LENGTH = 24 * 1024;
87 private static final String[] DUMPSYS_ARGS = new String[] { "-c", "-u" };
88 private static final String BATTERY_STATS_SERVICE_NAME = "batteryinfo";
89
90 private static final String DUMPSYS_DATA_PATH = "/data/system/";
91
92 // This should probably be exposed in the API, though it's not critical
93 private static final int BATTERY_PLUGGED_NONE = 0;
94
95 private final Context mContext;
96 private final IBatteryStats mBatteryStats;
97
98 private boolean mAcOnline;
99 private boolean mUsbOnline;
100 private int mBatteryStatus;
101 private int mBatteryHealth;
102 private boolean mBatteryPresent;
103 private int mBatteryLevel;
104 private int mBatteryVoltage;
105 private int mBatteryTemperature;
106 private String mBatteryTechnology;
107 private boolean mBatteryLevelCritical;
108
109 private int mLastBatteryStatus;
110 private int mLastBatteryHealth;
111 private boolean mLastBatteryPresent;
112 private int mLastBatteryLevel;
113 private int mLastBatteryVoltage;
114 private int mLastBatteryTemperature;
115 private boolean mLastBatteryLevelCritical;
116
117 private int mPlugType;
118 private int mLastPlugType = -1; // Extra state so we can detect first run
119
120 private long mDischargeStartTime;
121 private int mDischargeStartLevel;
122
123
124 public BatteryService(Context context) {
125 mContext = context;
126 mBatteryStats = BatteryStatsService.getService();
127
128 mUEventObserver.startObserving("SUBSYSTEM=power_supply");
129
130 // set initial status
131 update();
132 }
133
134 final boolean isPowered() {
135 // assume we are powered if battery state is unknown so the "stay on while plugged in" option will work.
136 return (mAcOnline || mUsbOnline || mBatteryStatus == BatteryManager.BATTERY_STATUS_UNKNOWN);
137 }
138
139 final boolean isPowered(int plugTypeSet) {
140 // assume we are powered if battery state is unknown so
141 // the "stay on while plugged in" option will work.
142 if (mBatteryStatus == BatteryManager.BATTERY_STATUS_UNKNOWN) {
143 return true;
144 }
145 if (plugTypeSet == 0) {
146 return false;
147 }
148 int plugTypeBit = 0;
149 if (mAcOnline) {
150 plugTypeBit |= BatteryManager.BATTERY_PLUGGED_AC;
151 }
152 if (mUsbOnline) {
153 plugTypeBit |= BatteryManager.BATTERY_PLUGGED_USB;
154 }
155 return (plugTypeSet & plugTypeBit) != 0;
156 }
157
158 final int getPlugType() {
159 return mPlugType;
160 }
161
162 private UEventObserver mUEventObserver = new UEventObserver() {
163 @Override
164 public void onUEvent(UEventObserver.UEvent event) {
165 update();
166 }
167 };
168
169 // returns battery level as a percentage
170 final int getBatteryLevel() {
171 return mBatteryLevel;
172 }
173
174 private native void native_update();
175
176 private synchronized final void update() {
177 native_update();
178
179 mBatteryLevelCritical = mBatteryLevel <= CRITICAL_BATTERY_LEVEL;
180 if (mAcOnline) {
181 mPlugType = BatteryManager.BATTERY_PLUGGED_AC;
182 } else if (mUsbOnline) {
183 mPlugType = BatteryManager.BATTERY_PLUGGED_USB;
184 } else {
185 mPlugType = BATTERY_PLUGGED_NONE;
186 }
187 if (mBatteryStatus != mLastBatteryStatus ||
188 mBatteryHealth != mLastBatteryHealth ||
189 mBatteryPresent != mLastBatteryPresent ||
190 mBatteryLevel != mLastBatteryLevel ||
191 mPlugType != mLastPlugType ||
192 mBatteryVoltage != mLastBatteryVoltage ||
193 mBatteryTemperature != mLastBatteryTemperature) {
194
195 if (mPlugType != mLastPlugType) {
196 if (mLastPlugType == BATTERY_PLUGGED_NONE) {
197 // discharging -> charging
198
199 // There's no value in this data unless we've discharged at least once and the
200 // battery level has changed; so don't log until it does.
201 if (mDischargeStartTime != 0 && mDischargeStartLevel != mBatteryLevel) {
202 long duration = SystemClock.elapsedRealtime() - mDischargeStartTime;
203 EventLog.writeEvent(LOG_BATTERY_DISCHARGE_STATUS, duration,
204 mDischargeStartLevel, mBatteryLevel);
205 // make sure we see a discharge event before logging again
206 mDischargeStartTime = 0;
207
208 logOutlier(duration);
209 }
210 } else if (mPlugType == BATTERY_PLUGGED_NONE) {
211 // charging -> discharging or we just powered up
212 mDischargeStartTime = SystemClock.elapsedRealtime();
213 mDischargeStartLevel = mBatteryLevel;
214 }
215 }
216 if (mBatteryStatus != mLastBatteryStatus ||
217 mBatteryHealth != mLastBatteryHealth ||
218 mBatteryPresent != mLastBatteryPresent ||
219 mPlugType != mLastPlugType) {
220 EventLog.writeEvent(LOG_BATTERY_STATUS,
221 mBatteryStatus, mBatteryHealth, mBatteryPresent ? 1 : 0,
222 mPlugType, mBatteryTechnology);
223 }
224 if (mBatteryLevel != mLastBatteryLevel ||
225 mBatteryVoltage != mLastBatteryVoltage ||
226 mBatteryTemperature != mLastBatteryTemperature) {
227 EventLog.writeEvent(LOG_BATTERY_LEVEL,
228 mBatteryLevel, mBatteryVoltage, mBatteryTemperature);
229 }
230 if (mBatteryLevelCritical && !mLastBatteryLevelCritical &&
231 mPlugType == BATTERY_PLUGGED_NONE) {
232 // We want to make sure we log discharge cycle outliers
233 // if the battery is about to die.
234 logOutlier(SystemClock.elapsedRealtime() - mDischargeStartTime);
235 }
236
237 mLastBatteryStatus = mBatteryStatus;
238 mLastBatteryHealth = mBatteryHealth;
239 mLastBatteryPresent = mBatteryPresent;
240 mLastBatteryLevel = mBatteryLevel;
241 mLastPlugType = mPlugType;
242 mLastBatteryVoltage = mBatteryVoltage;
243 mLastBatteryTemperature = mBatteryTemperature;
244 mLastBatteryLevelCritical = mBatteryLevelCritical;
245
246 sendIntent();
247 }
248 }
249
250 private final void sendIntent() {
251 // Pack up the values and broadcast them to everyone
252 Intent intent = new Intent(Intent.ACTION_BATTERY_CHANGED);
253 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
254 try {
255 mBatteryStats.setOnBattery(mPlugType == BATTERY_PLUGGED_NONE);
256 } catch (RemoteException e) {
257 // Should never happen.
258 }
259
260 int icon = getIcon(mBatteryLevel);
261
262 intent.putExtra("status", mBatteryStatus);
263 intent.putExtra("health", mBatteryHealth);
264 intent.putExtra("present", mBatteryPresent);
265 intent.putExtra("level", mBatteryLevel);
266 intent.putExtra("scale", BATTERY_SCALE);
267 intent.putExtra("icon-small", icon);
268 intent.putExtra("plugged", mPlugType);
269 intent.putExtra("voltage", mBatteryVoltage);
270 intent.putExtra("temperature", mBatteryTemperature);
271 intent.putExtra("technology", mBatteryTechnology);
272
273 if (false) {
274 Log.d(TAG, "updateBattery level:" + mBatteryLevel +
275 " scale:" + BATTERY_SCALE + " status:" + mBatteryStatus +
276 " health:" + mBatteryHealth + " present:" + mBatteryPresent +
277 " voltage: " + mBatteryVoltage +
278 " temperature: " + mBatteryTemperature +
279 " technology: " + mBatteryTechnology +
280 " AC powered:" + mAcOnline + " USB powered:" + mUsbOnline +
281 " icon:" + icon );
282 }
283
284 ActivityManagerNative.broadcastStickyIntent(intent, null);
285 }
286
287 private final void logBatteryStats() {
288
289 IBinder batteryInfoService = ServiceManager.getService(BATTERY_STATS_SERVICE_NAME);
290 if (batteryInfoService != null) {
291 byte[] buffer = new byte[DUMP_MAX_LENGTH];
292 File dumpFile = null;
293 FileOutputStream dumpStream = null;
294 try {
295 // dump the service to a file
296 dumpFile = new File(DUMPSYS_DATA_PATH + BATTERY_STATS_SERVICE_NAME + ".dump");
297 dumpStream = new FileOutputStream(dumpFile);
298 batteryInfoService.dump(dumpStream.getFD(), DUMPSYS_ARGS);
299 dumpStream.getFD().sync();
300
301 // read dumped file above into buffer truncated to DUMP_MAX_LENGTH
302 // and insert into events table.
303 int length = (int) Math.min(dumpFile.length(), DUMP_MAX_LENGTH);
304 FileInputStream fileInputStream = new FileInputStream(dumpFile);
305 int nread = fileInputStream.read(buffer, 0, length);
306 if (nread > 0) {
307 Checkin.logEvent(mContext.getContentResolver(),
308 Checkin.Events.Tag.BATTERY_DISCHARGE_INFO,
309 new String(buffer, 0, nread));
310 if (LOCAL_LOGV) Log.v(TAG, "dumped " + nread + "b from " +
311 batteryInfoService + "to log");
312 if (LOCAL_LOGV) Log.v(TAG, "actual dump:" + new String(buffer, 0, nread));
313 }
314 } catch (RemoteException e) {
315 Log.e(TAG, "failed to dump service '" + BATTERY_STATS_SERVICE_NAME +
316 "':" + e);
317 } catch (IOException e) {
318 Log.e(TAG, "failed to write dumpsys file: " + e);
319 } finally {
320 // make sure we clean up
321 if (dumpStream != null) {
322 try {
323 dumpStream.close();
324 } catch (IOException e) {
325 Log.e(TAG, "failed to close dumpsys output stream");
326 }
327 }
328 if (dumpFile != null && !dumpFile.delete()) {
329 Log.e(TAG, "failed to delete temporary dumpsys file: "
330 + dumpFile.getAbsolutePath());
331 }
332 }
333 }
334 }
335
336 private final void logOutlier(long duration) {
337 ContentResolver cr = mContext.getContentResolver();
338 String dischargeThresholdString = Settings.Gservices.getString(cr,
339 Settings.Gservices.BATTERY_DISCHARGE_THRESHOLD);
340 String durationThresholdString = Settings.Gservices.getString(cr,
341 Settings.Gservices.BATTERY_DISCHARGE_DURATION_THRESHOLD);
342
343 if (dischargeThresholdString != null && durationThresholdString != null) {
344 try {
345 long durationThreshold = Long.parseLong(durationThresholdString);
346 int dischargeThreshold = Integer.parseInt(dischargeThresholdString);
347 if (duration <= durationThreshold &&
348 mDischargeStartLevel - mBatteryLevel >= dischargeThreshold) {
349 // If the discharge cycle is bad enough we want to know about it.
350 logBatteryStats();
351 }
352 if (LOCAL_LOGV) Log.v(TAG, "duration threshold: " + durationThreshold +
353 " discharge threshold: " + dischargeThreshold);
354 if (LOCAL_LOGV) Log.v(TAG, "duration: " + duration + " discharge: " +
355 (mDischargeStartLevel - mBatteryLevel));
356 } catch (NumberFormatException e) {
357 Log.e(TAG, "Invalid DischargeThresholds GService string: " +
358 durationThresholdString + " or " + dischargeThresholdString);
359 return;
360 }
361 }
362 }
363
364 private final int getIcon(int level) {
365 if (mBatteryStatus == BatteryManager.BATTERY_STATUS_CHARGING) {
366 return com.android.internal.R.drawable.stat_sys_battery_charge;
367 } else if (mBatteryStatus == BatteryManager.BATTERY_STATUS_DISCHARGING ||
368 mBatteryStatus == BatteryManager.BATTERY_STATUS_NOT_CHARGING ||
369 mBatteryStatus == BatteryManager.BATTERY_STATUS_FULL) {
370 return com.android.internal.R.drawable.stat_sys_battery;
371 } else {
372 return com.android.internal.R.drawable.stat_sys_battery_unknown;
373 }
374 }
375
376 @Override
377 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
378 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
379 != PackageManager.PERMISSION_GRANTED) {
380
381 pw.println("Permission Denial: can't dump Battery service from from pid="
382 + Binder.getCallingPid()
383 + ", uid=" + Binder.getCallingUid());
384 return;
385 }
386
387 synchronized (this) {
388 pw.println("Current Battery Service state:");
389 pw.println(" AC powered: " + mAcOnline);
390 pw.println(" USB powered: " + mUsbOnline);
391 pw.println(" status: " + mBatteryStatus);
392 pw.println(" health: " + mBatteryHealth);
393 pw.println(" present: " + mBatteryPresent);
394 pw.println(" level: " + mBatteryLevel);
395 pw.println(" scale: " + BATTERY_SCALE);
396 pw.println(" voltage:" + mBatteryVoltage);
397 pw.println(" temperature: " + mBatteryTemperature);
398 pw.println(" technology: " + mBatteryTechnology);
399 }
400 }
401}