summaryrefslogtreecommitdiffstats
path: root/base/system_monitor.cc
blob: 1d44e3c8d4622b797d931687953e5395166810d3 (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
// Copyright (c) 2008 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 "base/system_monitor.h"
#include "base/logging.h"
#include "base/message_loop.h"

namespace base {

// The amount of time (in ms) to wait before running the initial
// battery check.
static int kDelayedBatteryCheckMs = 10 * 1000;

SystemMonitor::SystemMonitor()
    : battery_in_use_(false),
      suspended_(false) {
  observer_list_ = new ObserverListThreadSafe<PowerObserver>();
}

void SystemMonitor::ProcessPowerMessage(PowerEvent event_id) {
  // Suppress duplicate notifications.  Some platforms may 
  // send multiple notifications of the same event.
  switch (event_id) {
    case POWER_STATE_EVENT:
      {
        bool on_battery = IsBatteryPower();
        if (on_battery != battery_in_use_) {
          battery_in_use_ = on_battery;
          NotifyPowerStateChange();
        }
      }
      break;
    case RESUME_EVENT:
      if (suspended_) {
        suspended_ = false;
        NotifyResume();
      }
      break;
    case SUSPEND_EVENT:
      if (!suspended_) {
        suspended_ = true;
        NotifySuspend();
      }
      break;
  }
}

void SystemMonitor::AddObserver(PowerObserver* obs) {
  observer_list_->AddObserver(obs);
}

void SystemMonitor::RemoveObserver(PowerObserver* obs) {
  observer_list_->RemoveObserver(obs);
}

void SystemMonitor::NotifyPowerStateChange() {
  LOG(INFO) << L"PowerStateChange: " 
           << (BatteryPower() ? L"On" : L"Off") << L" battery";
  observer_list_->Notify(&PowerObserver::OnPowerStateChange, this);
}

void SystemMonitor::NotifySuspend() {
  LOG(INFO) << L"Power Suspending";
  observer_list_->Notify(&PowerObserver::OnSuspend, this);
}

void SystemMonitor::NotifyResume() {
  LOG(INFO) << L"Power Resuming";
  observer_list_->Notify(&PowerObserver::OnResume, this);
}

void SystemMonitor::Start() {
  DCHECK(MessageLoop::current());  // Can't call start too early.
  SystemMonitor* monitor = Get();
  monitor->delayed_battery_check_.Start(
      TimeDelta::FromMilliseconds(kDelayedBatteryCheckMs), monitor,
      &SystemMonitor::BatteryCheck);
}

void SystemMonitor::BatteryCheck() {
  ProcessPowerMessage(SystemMonitor::POWER_STATE_EVENT);
}

} // namespace base