summaryrefslogtreecommitdiffstats
path: root/device/battery/battery_status_manager_linux.cc
blob: 0b2da63d0f1c1f769ef0c45288a0a6112525ea94 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "device/battery/battery_status_manager_linux.h"

#include "base/macros.h"
#include "base/metrics/histogram.h"
#include "base/threading/thread.h"
#include "base/values.h"
#include "dbus/bus.h"
#include "dbus/message.h"
#include "dbus/object_path.h"
#include "dbus/object_proxy.h"
#include "dbus/property.h"
#include "dbus/values_util.h"
#include "device/battery/battery_status_manager.h"

namespace device {

namespace {

const char kUPowerServiceName[] = "org.freedesktop.UPower";
const char kUPowerDeviceName[] = "org.freedesktop.UPower.Device";
const char kUPowerPath[] = "/org/freedesktop/UPower";
const char kUPowerDeviceSignalChanged[] = "Changed";
const char kUPowerEnumerateDevices[] = "EnumerateDevices";
const char kBatteryNotifierThreadName[] = "BatteryStatusNotifier";

// UPowerDeviceType reflects the possible UPower.Device.Type values,
// see upower.freedesktop.org/docs/Device.html#Device:Type.
enum UPowerDeviceType {
  UPOWER_DEVICE_TYPE_UNKNOWN = 0,
  UPOWER_DEVICE_TYPE_LINE_POWER = 1,
  UPOWER_DEVICE_TYPE_BATTERY = 2,
  UPOWER_DEVICE_TYPE_UPS = 3,
  UPOWER_DEVICE_TYPE_MONITOR = 4,
  UPOWER_DEVICE_TYPE_MOUSE = 5,
  UPOWER_DEVICE_TYPE_KEYBOARD = 6,
  UPOWER_DEVICE_TYPE_PDA = 7,
  UPOWER_DEVICE_TYPE_PHONE = 8,
};

typedef std::vector<dbus::ObjectPath> PathsVector;

double GetPropertyAsDouble(const base::DictionaryValue& dictionary,
                           const std::string& property_name,
                           double default_value) {
  double value = default_value;
  return dictionary.GetDouble(property_name, &value) ? value : default_value;
}

bool GetPropertyAsBoolean(const base::DictionaryValue& dictionary,
                          const std::string& property_name,
                          bool default_value) {
  bool value = default_value;
  return dictionary.GetBoolean(property_name, &value) ? value : default_value;
}

scoped_ptr<base::DictionaryValue> GetPropertiesAsDictionary(
    dbus::ObjectProxy* proxy) {
  dbus::MethodCall method_call(dbus::kPropertiesInterface,
                               dbus::kPropertiesGetAll);
  dbus::MessageWriter builder(&method_call);
  builder.AppendString(kUPowerDeviceName);

  scoped_ptr<dbus::Response> response(
      proxy->CallMethodAndBlock(&method_call,
                                dbus::ObjectProxy::TIMEOUT_USE_DEFAULT));
  if (response) {
    dbus::MessageReader reader(response.get());
    scoped_ptr<base::Value> value(dbus::PopDataAsValue(&reader));
    base::DictionaryValue* dictionary_value = NULL;
    if (value && value->GetAsDictionary(&dictionary_value)) {
      ignore_result(value.release());
      return scoped_ptr<base::DictionaryValue>(dictionary_value);
    }
  }
  return scoped_ptr<base::DictionaryValue>();
}

scoped_ptr<PathsVector> GetPowerSourcesPaths(dbus::ObjectProxy* proxy) {
  scoped_ptr<PathsVector> paths(new PathsVector());
  if (!proxy)
    return paths.Pass();

  dbus::MethodCall method_call(kUPowerServiceName, kUPowerEnumerateDevices);
  scoped_ptr<dbus::Response> response(
      proxy->CallMethodAndBlock(&method_call,
                                dbus::ObjectProxy::TIMEOUT_USE_DEFAULT));

  if (response) {
    dbus::MessageReader reader(response.get());
    reader.PopArrayOfObjectPaths(paths.get());
  }
  return paths.Pass();;
}

void UpdateNumberBatteriesHistogram(int count) {
  UMA_HISTOGRAM_CUSTOM_COUNTS(
      "BatteryStatus.NumberBatteriesLinux", count, 1, 5, 6);
}

// Class that represents a dedicated thread which communicates with DBus to
// obtain battery information and receives battery change notifications.
class BatteryStatusNotificationThread : public base::Thread {
 public:
  BatteryStatusNotificationThread(
      const BatteryStatusService::BatteryUpdateCallback& callback)
      : base::Thread(kBatteryNotifierThreadName),
        callback_(callback),
        battery_proxy_(NULL) {}

  ~BatteryStatusNotificationThread() override {
    // Make sure to shutdown the dbus connection if it is still open in the very
    // end. It needs to happen on the BatteryStatusNotificationThread.
    message_loop()->PostTask(
        FROM_HERE,
        base::Bind(&BatteryStatusNotificationThread::ShutdownDBusConnection,
                   base::Unretained(this)));

    // Drain the message queue of the BatteryStatusNotificationThread and stop.
    Stop();
  }

  void StartListening() {
    DCHECK(OnWatcherThread());

    if (system_bus_.get())
      return;

    InitDBus();
    dbus::ObjectProxy* power_proxy =
        system_bus_->GetObjectProxy(kUPowerServiceName,
                                    dbus::ObjectPath(kUPowerPath));
    scoped_ptr<PathsVector> device_paths = GetPowerSourcesPaths(power_proxy);
    int num_batteries = 0;

    for (size_t i = 0; i < device_paths->size(); ++i) {
      const dbus::ObjectPath& device_path = device_paths->at(i);
      dbus::ObjectProxy* device_proxy = system_bus_->GetObjectProxy(
          kUPowerServiceName, device_path);
      scoped_ptr<base::DictionaryValue> dictionary =
          GetPropertiesAsDictionary(device_proxy);

      if (!dictionary)
        continue;

      bool is_present = GetPropertyAsBoolean(*dictionary, "IsPresent", false);
      uint32 type = static_cast<uint32>(
          GetPropertyAsDouble(*dictionary, "Type", UPOWER_DEVICE_TYPE_UNKNOWN));

      if (!is_present || type != UPOWER_DEVICE_TYPE_BATTERY) {
        system_bus_->RemoveObjectProxy(kUPowerServiceName,
                                       device_path,
                                       base::Bind(&base::DoNothing));
        continue;
      }

      if (battery_proxy_) {
        // TODO(timvolodine): add support for multiple batteries. Currently we
        // only collect information from the first battery we encounter
        // (crbug.com/400780).
        LOG(WARNING) << "multiple batteries found, "
                     << "using status data of the first battery only.";
      } else {
        battery_proxy_ = device_proxy;
      }
      num_batteries++;
    }

    UpdateNumberBatteriesHistogram(num_batteries);

    if (!battery_proxy_) {
      callback_.Run(BatteryStatus());
      return;
    }

    battery_proxy_->ConnectToSignal(
        kUPowerDeviceName,
        kUPowerDeviceSignalChanged,
        base::Bind(&BatteryStatusNotificationThread::BatteryChanged,
                   base::Unretained(this)),
        base::Bind(&BatteryStatusNotificationThread::OnSignalConnected,
                   base::Unretained(this)));
  }

  void StopListening() {
    DCHECK(OnWatcherThread());
    ShutdownDBusConnection();
  }

 private:
  bool OnWatcherThread() {
    return task_runner()->BelongsToCurrentThread();
  }

  void InitDBus() {
    DCHECK(OnWatcherThread());

    dbus::Bus::Options options;
    options.bus_type = dbus::Bus::SYSTEM;
    options.connection_type = dbus::Bus::PRIVATE;
    system_bus_ = new dbus::Bus(options);
  }

  void ShutdownDBusConnection() {
    DCHECK(OnWatcherThread());

    if (!system_bus_.get())
      return;

    // Shutdown DBus connection later because there may be pending tasks on
    // this thread.
    message_loop()->PostTask(FROM_HERE,
                             base::Bind(&dbus::Bus::ShutdownAndBlock,
                                        system_bus_));
    system_bus_ = NULL;
    battery_proxy_ = NULL;
  }

  void OnSignalConnected(const std::string& interface_name,
                         const std::string& signal_name,
                         bool success) {
    DCHECK(OnWatcherThread());

    if (interface_name != kUPowerDeviceName ||
        signal_name != kUPowerDeviceSignalChanged) {
      return;
    }

    if (!system_bus_.get())
      return;

    if (success) {
      BatteryChanged(NULL);
    } else {
      // Failed to register for "Changed" signal, execute callback with the
      // default values.
      callback_.Run(BatteryStatus());
    }
  }

  void BatteryChanged(dbus::Signal* signal /* unsused */) {
    DCHECK(OnWatcherThread());

    if (!system_bus_.get())
      return;

    scoped_ptr<base::DictionaryValue> dictionary =
        GetPropertiesAsDictionary(battery_proxy_);
    if (dictionary)
      callback_.Run(ComputeWebBatteryStatus(*dictionary));
    else
      callback_.Run(BatteryStatus());
  }

  BatteryStatusService::BatteryUpdateCallback callback_;
  scoped_refptr<dbus::Bus> system_bus_;
  dbus::ObjectProxy* battery_proxy_;  // owned by the bus

  DISALLOW_COPY_AND_ASSIGN(BatteryStatusNotificationThread);
};

// Creates a notification thread and delegates Start/Stop calls to it.
class BatteryStatusManagerLinux : public BatteryStatusManager {
 public:
  explicit BatteryStatusManagerLinux(
      const BatteryStatusService::BatteryUpdateCallback& callback)
      : callback_(callback) {}

  ~BatteryStatusManagerLinux() override {}

 private:
  // BatteryStatusManager:
  bool StartListeningBatteryChange() override {
    if (!StartNotifierThreadIfNecessary())
      return false;

    notifier_thread_->message_loop()->PostTask(
        FROM_HERE,
        base::Bind(&BatteryStatusNotificationThread::StartListening,
                   base::Unretained(notifier_thread_.get())));
    return true;
  }

  void StopListeningBatteryChange() override {
    if (!notifier_thread_)
      return;

    notifier_thread_->message_loop()->PostTask(
        FROM_HERE,
        base::Bind(&BatteryStatusNotificationThread::StopListening,
                   base::Unretained(notifier_thread_.get())));
  }

  // Starts the notifier thread if not already started and returns true on
  // success.
  bool StartNotifierThreadIfNecessary() {
    if (notifier_thread_)
      return true;

    base::Thread::Options thread_options(base::MessageLoop::TYPE_IO, 0);
    notifier_thread_.reset(new BatteryStatusNotificationThread(callback_));
    if (!notifier_thread_->StartWithOptions(thread_options)) {
      notifier_thread_.reset();
      LOG(ERROR) << "Could not start the " << kBatteryNotifierThreadName
                 << " thread";
      return false;
    }
    return true;
  }

  BatteryStatusService::BatteryUpdateCallback callback_;
  scoped_ptr<BatteryStatusNotificationThread> notifier_thread_;

  DISALLOW_COPY_AND_ASSIGN(BatteryStatusManagerLinux);
};

}  // namespace

BatteryStatus ComputeWebBatteryStatus(const base::DictionaryValue& dictionary) {
  BatteryStatus status;
  if (!dictionary.HasKey("State"))
    return status;

  uint32 state = static_cast<uint32>(
      GetPropertyAsDouble(dictionary, "State", UPOWER_DEVICE_STATE_UNKNOWN));
  status.charging = state != UPOWER_DEVICE_STATE_DISCHARGING &&
                    state != UPOWER_DEVICE_STATE_EMPTY;
  double percentage = GetPropertyAsDouble(dictionary, "Percentage", 100);
  // Convert percentage to a value between 0 and 1 with 2 digits of precision.
  // This is to bring it in line with other platforms like Mac and Android where
  // we report level with 1% granularity. It also serves the purpose of reducing
  // the possibility of fingerprinting and triggers less level change events on
  // the blink side.
  // TODO(timvolodine): consider moving this rounding to the blink side.
  status.level = round(percentage) / 100.f;

  switch (state) {
    case UPOWER_DEVICE_STATE_CHARGING : {
      double time_to_full = GetPropertyAsDouble(dictionary, "TimeToFull", 0);
      status.charging_time =
          (time_to_full > 0) ? time_to_full
                             : std::numeric_limits<double>::infinity();
      break;
    }
    case UPOWER_DEVICE_STATE_DISCHARGING : {
      double time_to_empty = GetPropertyAsDouble(dictionary, "TimeToEmpty", 0);
      // Set dischargingTime if it's available. Otherwise leave the default
      // value which is +infinity.
      if (time_to_empty > 0)
        status.discharging_time = time_to_empty;
      status.charging_time = std::numeric_limits<double>::infinity();
      break;
    }
    case UPOWER_DEVICE_STATE_FULL : {
      break;
    }
    default: {
      status.charging_time = std::numeric_limits<double>::infinity();
    }
  }
  return status;
}

// static
scoped_ptr<BatteryStatusManager> BatteryStatusManager::Create(
    const BatteryStatusService::BatteryUpdateCallback& callback) {
  return scoped_ptr<BatteryStatusManager>(
      new BatteryStatusManagerLinux(callback));
}

}  // namespace device