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

ash / system / power / power_sounds_controller.cc [blame]

// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ash/system/power/power_sounds_controller.h"

#include "ash/constants/ash_features.h"
#include "ash/constants/ash_pref_names.h"
#include "ash/shell.h"
#include "ash/system/power/battery_saver_controller.h"
#include "ash/system/power/power_status.h"
#include "base/check.h"
#include "base/check_is_test.h"
#include "base/metrics/histogram_functions.h"
#include "base/time/time.h"
#include "chromeos/ash/components/audio/sounds.h"
#include "chromeos/ash/components/audio/system_sounds_delegate.h"
#include "chromeos/dbus/power/power_manager_client.h"
#include "components/prefs/pref_registry_simple.h"
#include "ui/message_center/message_center.h"

namespace ash {

namespace {

constexpr ExternalPower kAcPower =
    power_manager::PowerSupplyProperties_ExternalPower_AC;
constexpr ExternalPower kUsbPower =
    power_manager::PowerSupplyProperties_ExternalPower_USB;

// Percentage-based thresholds for remaining battery charge to play sounds when
// plugging in a charger cable.
constexpr int kMidPercentageForCharging = 16;
constexpr int kNormalPercentageForCharging = 80;

// Percentage-based threshold for remaining battery level when using a low-power
// charger.
constexpr int kCriticalWarningPercentage = 5;
constexpr int kLowPowerWarningPercentage = 10;

// Time-based threshold for remaining time when disconnected with the line
// power (any type of charger).
constexpr base::TimeDelta kCriticalWarningMinutes = base::Minutes(5);
constexpr base::TimeDelta kLowPowerWarningMinutes = base::Minutes(15);

// Gets the sound for plugging in an AC charger at different battery levels.
Sound GetSoundKeyForBatteryLevel(int level) {
  if (level >= kNormalPercentageForCharging)
    return Sound::kChargeHighBattery;

  const int threshold =
      IsBatterySaverAllowed()
          ? features::kBatterySaverActivationChargePercent.Get() + 1
          : kMidPercentageForCharging;

  return level >= threshold ? Sound::kChargeMediumBattery
                            : Sound::kChargeLowBattery;
}

}  // namespace

// static
const char PowerSoundsController::kPluggedInBatteryLevelHistogramName[] =
    "Ash.PowerSoundsController.PluggedInBatteryLevel";

// static
const char PowerSoundsController::kUnpluggedBatteryLevelHistogramName[] =
    "Ash.PowerSoundsController.UnpluggedBatteryLevel";

PowerSoundsController::PowerSoundsController() {
  chromeos::PowerManagerClient* client = chromeos::PowerManagerClient::Get();
  DCHECK(client);
  client->AddObserver(this);

  // Get the initial lid state.
  client->GetSwitchStates(
      base::BindOnce(&PowerSoundsController::OnReceiveSwitchStates,
                     weak_factory_.GetWeakPtr()));

  PowerStatus* power_status = PowerStatus::Get();
  power_status->AddObserver(this);

  battery_level_ = power_status->GetRoundedBatteryPercent();
  is_ac_charger_connected_ = power_status->IsMainsChargerConnected();

  local_state_ = Shell::Get()->local_state();

  // `local_state_` could be null in tests.
  if (local_state_) {
    low_battery_sound_enabled_.Init(prefs::kLowBatterySoundEnabled,
                                    local_state_);
    charging_sounds_enabled_.Init(prefs::kChargingSoundsEnabled, local_state_);
  }
}

PowerSoundsController::~PowerSoundsController() {
  PowerStatus::Get()->RemoveObserver(this);
  chromeos::PowerManagerClient::Get()->RemoveObserver(this);
}

void PowerSoundsController::RegisterLocalStatePrefs(
    PrefRegistrySimple* registry) {
  registry->RegisterBooleanPref(prefs::kChargingSoundsEnabled,
                                /*default_value=*/false);
  registry->RegisterBooleanPref(prefs::kLowBatterySoundEnabled,
                                /*default_value=*/false);
}

void PowerSoundsController::OnPowerStatusChanged() {
  if (!local_state_) {
    CHECK_IS_TEST();
    return;
  }

  const PowerStatus& status = *PowerStatus::Get();
  SetPowerStatus(status.GetRoundedBatteryPercent(),
                 status.IsBatteryTimeBeingCalculated(), status.external_power(),
                 status.GetBatteryTimeToEmpty());
}

void PowerSoundsController::LidEventReceived(
    chromeos::PowerManagerClient::LidState state,
    base::TimeTicks timestamp) {
  lid_state_ = state;
}

void PowerSoundsController::OnReceiveSwitchStates(
    std::optional<chromeos::PowerManagerClient::SwitchStates> switch_states) {
  if (switch_states.has_value()) {
    lid_state_ = switch_states->lid_state;
  }
}

bool PowerSoundsController::CanPlaySounds() const {
  // Do not play any sound if the device is in DND mode, or if the lid is not
  // open.
  return !message_center::MessageCenter::Get()->IsQuietMode() &&
         lid_state_ == chromeos::PowerManagerClient::LidState::OPEN;
}

void PowerSoundsController::SetPowerStatus(
    int battery_level,
    bool is_calculating_battery_time,
    ExternalPower external_power,
    std::optional<base::TimeDelta> remaining_time) {
  battery_level_ = battery_level;

  const bool old_ac_charger_connected = is_ac_charger_connected_;
  is_ac_charger_connected_ = external_power == kAcPower;

  // Records the battery level only for the device plugged in or Unplugged.
  if (old_ac_charger_connected != is_ac_charger_connected_) {
    base::UmaHistogramPercentage(is_ac_charger_connected_
                                     ? kPluggedInBatteryLevelHistogramName
                                     : kUnpluggedBatteryLevelHistogramName,
                                 battery_level_);
  }

  MaybePlaySoundsForCharging(old_ac_charger_connected);

  if (UpdateBatteryState(is_calculating_battery_time, external_power,
                         remaining_time) &&
      ShouldPlayLowBatterySound()) {
    Shell::Get()->system_sounds_delegate()->Play(Sound::kNoChargeLowBattery);
  }
}

void PowerSoundsController::MaybePlaySoundsForCharging(
    bool old_ac_charger_connected) {
  // Don't play the charging sound if the toggle button is disabled by user in
  // the Settings UI.
  if (!charging_sounds_enabled_.GetValue() || !CanPlaySounds()) {
    return;
  }

  // Returns when it isn't a plug in event.
  bool is_plugging_in = !old_ac_charger_connected && is_ac_charger_connected_;
  if (!is_plugging_in)
    return;

  Shell::Get()->system_sounds_delegate()->Play(
      GetSoundKeyForBatteryLevel(battery_level_));
}

bool PowerSoundsController::ShouldPlayLowBatterySound() const {
  if (!low_battery_sound_enabled_.GetValue() || !CanPlaySounds()) {
    return false;
  }

  return current_state_ == BatteryState::kCriticalPower ||
         current_state_ == BatteryState::kLowPower;
}

bool PowerSoundsController::UpdateBatteryState(
    bool is_calculating_battery_time,
    ExternalPower external_power,
    std::optional<base::TimeDelta> remaining_time) {
  const auto new_state = CalculateBatteryState(is_calculating_battery_time,
                                               external_power, remaining_time);
  if (new_state == current_state_) {
    return false;
  }

  current_state_ = new_state;
  return true;
}

PowerSoundsController::BatteryState
PowerSoundsController::CalculateBatteryState(
    bool is_calculating_battery_time,
    ExternalPower external_power,
    std::optional<base::TimeDelta> remaining_time) const {
  const bool is_battery_saver_allowed = IsBatterySaverAllowed();

  if ((is_calculating_battery_time && !is_battery_saver_allowed) ||
      is_ac_charger_connected_) {
    return BatteryState::kNone;
  }

  // The battery state calculation should follow the same logic used by the
  // power notification (Please see
  // `PowerNotificationController::UpdateNotificationState()`). Hence, when a
  // low-power charger (i.e. a USB charger) is connected, or we are using
  // battery saver notifications, we calculate the state based on the remaining
  // `battery_level_` percentage. GetBatteryStateFromBatteryLevel()
  // automatically reflects this differentiation in its logic. Otherwise, when
  // the device is disconnected, we calculate it based on the remaining time
  // until the battery is empty.
  if (is_battery_saver_allowed || external_power == kUsbPower) {
    return GetBatteryStateFromBatteryLevel();
  }
  return GetBatteryStateFromRemainingTime(remaining_time);
}

PowerSoundsController::BatteryState
PowerSoundsController::GetBatteryStateFromBatteryLevel() const {
  if (battery_level_ <= kCriticalWarningPercentage) {
    return BatteryState::kCriticalPower;
  }

  const int low_power_warning_percentage =
      IsBatterySaverAllowed()
          ? features::kBatterySaverActivationChargePercent.Get()
          : kLowPowerWarningPercentage;

  if (battery_level_ <= low_power_warning_percentage) {
    return BatteryState::kLowPower;
  }

  return BatteryState::kNone;
}

PowerSoundsController::BatteryState
PowerSoundsController::GetBatteryStateFromRemainingTime(
    std::optional<base::TimeDelta> remaining_time) const {
  if (!remaining_time) {
    return BatteryState::kNone;
  }

  if (*remaining_time <= kCriticalWarningMinutes) {
    return BatteryState::kCriticalPower;
  }

  if (*remaining_time <= kLowPowerWarningMinutes) {
    return BatteryState::kLowPower;
  }

  return BatteryState::kNone;
}

}  // namespace ash