1 // Copyright 2014 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef BLINK_MODULES_BATTERY_BATTERY_STATUS_H_ 6 #define BLINK_MODULES_BATTERY_BATTERY_STATUS_H_ 7 8 #include "third_party/blink/renderer/modules/modules_export.h" 9 #include "third_party/blink/renderer/platform/wtf/allocator/allocator.h" 10 #include "third_party/blink/renderer/platform/wtf/assertions.h" 11 12 #include <cmath> 13 #include <limits> 14 15 namespace blink { 16 17 // Simple struct to hold the battery status. This class is copyable. 18 class MODULES_EXPORT BatteryStatus final { 19 DISALLOW_NEW(); 20 21 public: BatteryStatus()22 BatteryStatus() 23 : charging_(true), 24 charging_time_(0), 25 discharging_time_(std::numeric_limits<double>::infinity()), 26 level_(1) {} BatteryStatus(bool charging,double charging_time,double discharging_time,double level)27 BatteryStatus(bool charging, 28 double charging_time, 29 double discharging_time, 30 double level) 31 : charging_(charging), 32 charging_time_(charging_time), 33 discharging_time_(discharging_time), 34 level_(EnsureTwoSignificantDigits(level)) {} 35 BatteryStatus(const BatteryStatus&) = default; 36 BatteryStatus& operator=(const BatteryStatus&) = default; 37 Charging()38 bool Charging() const { return charging_; } charging_time()39 double charging_time() const { return charging_time_; } discharging_time()40 double discharging_time() const { return discharging_time_; } Level()41 double Level() const { return level_; } 42 43 private: EnsureTwoSignificantDigits(double level)44 double EnsureTwoSignificantDigits(double level) { 45 // Convert battery level value which should be in [0, 1] to a value in 46 // [0, 1] with 2 digits of precision. This is to provide a consistent 47 // experience across platforms (e.g. on Mac and Android the battery changes 48 // are generally reported with 1% granularity). It also serves the purpose 49 // of reducing the possibility of fingerprinting and triggers less level 50 // change events on platforms where the granularity is high. 51 DCHECK(level >= 0 && level <= 1); 52 return std::round(level * 100) / 100.f; 53 } 54 55 bool charging_; 56 double charging_time_; 57 double discharging_time_; 58 double level_; 59 }; 60 61 } // namespace blink 62 63 #endif // BLINK_MODULES_BATTERY_BATTERY_STATUS_H_ 64