peripheral_battery_listener.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. // Copyright 2020 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. #ifndef ASH_SYSTEM_POWER_PERIPHERAL_BATTERY_LISTENER_H_
  5. #define ASH_SYSTEM_POWER_PERIPHERAL_BATTERY_LISTENER_H_
  6. #include <cstdint>
  7. #include <map>
  8. #include "ash/ash_export.h"
  9. #include "base/compiler_specific.h"
  10. #include "base/containers/flat_map.h"
  11. #include "base/gtest_prod_util.h"
  12. #include "base/memory/weak_ptr.h"
  13. #include "base/observer_list.h"
  14. #include "base/time/time.h"
  15. #include "base/timer/timer.h"
  16. #include "chromeos/dbus/power/power_manager_client.h"
  17. #include "device/bluetooth/bluetooth_adapter.h"
  18. #include "device/bluetooth/bluetooth_device.h"
  19. #include "third_party/abseil-cpp/absl/types/optional.h"
  20. #include "ui/events/devices/input_device_event_observer.h"
  21. #include "ui/events/devices/stylus_state.h"
  22. namespace ash {
  23. class BluetoothDevice;
  24. class PeripheralBatteryListenerTest;
  25. // This class listens for peripheral device battery status across
  26. // several sources, allowing simpler unified observation.
  27. class ASH_EXPORT PeripheralBatteryListener
  28. : public chromeos::PowerManagerClient::Observer,
  29. public device::BluetoothAdapter::Observer,
  30. public ui::InputDeviceEventObserver {
  31. public:
  32. struct BatteryInfo {
  33. enum class PeripheralType {
  34. kOther = 0,
  35. kStylusViaScreen = 1,
  36. kStylusViaCharger = 2
  37. };
  38. enum class ChargeStatus {
  39. // Indicates that either peripheral is not a charger, or the
  40. // charge device is not attached; level may be invalid (including 0)
  41. // when this is reported for a charger, and likely should be ignored.
  42. kUnknown = 0,
  43. // Common state for peripherals in use.
  44. kDischarging = 1,
  45. // When a chargable device is attached and actively charging.
  46. kCharging = 2,
  47. // When a chargable device is attached and definitely has full charge.
  48. // The device is not charging, but is powered.
  49. kFull = 3,
  50. // When a chargable device is attached and not charging; this can also
  51. // be due to a full charge, or other unspecified reasons for not charging.
  52. kNotCharging = 4,
  53. // Error is reported when charger is unable to function, and user should
  54. // take corrective action; for a wireless
  55. // charger this could be foreign object debris that is preventing
  56. // power transfer. When errors are reported no information is available
  57. // on whether a charge is also occurring or a chargable device is
  58. // attached.
  59. kError = 5
  60. };
  61. BatteryInfo();
  62. BatteryInfo(const std::string& key,
  63. const std::u16string& name,
  64. absl::optional<uint8_t> level,
  65. bool battery_report_eligible,
  66. base::TimeTicks last_update_timestamp,
  67. PeripheralType type,
  68. ChargeStatus charge_status,
  69. const std::string& bluetooth_address);
  70. ~BatteryInfo();
  71. BatteryInfo(const BatteryInfo& info);
  72. // ID key, unique to all current batteries, will not change
  73. // during existence of this battery. If battery is removed, the
  74. // same name may be re-used when a battery is added again.
  75. std::string key;
  76. // Human readable name for the device. It is changeable.
  77. std::u16string name;
  78. // Battery level within range [0, 100], or unset. This is changeable as
  79. // the peripheral charge level changes.
  80. // TODO(kenalba): explain when we might have an unset state.
  81. absl::optional<uint8_t> level;
  82. // True unless peripheral is known to have unreliable battery reporting.
  83. // It is changeable.
  84. // TODO(kenalba): specify how a nullopt level and !battery_report_eligible
  85. // interact.
  86. bool battery_report_eligible = true;
  87. // Time of last known update of the battery state; this is changeable,
  88. // and may be updated even if no other fields are; it gives the time of the
  89. // last known confirmed reading.
  90. base::TimeTicks last_update_timestamp;
  91. // If set, time of last known active update to the battery, indicating
  92. // a peripheral notified the system of status, distinct from a periodic
  93. // poll or poll on powerd restart. Unset (nullopt) if there has never been
  94. // an active update.
  95. absl::optional<base::TimeTicks> last_active_update_timestamp =
  96. absl::nullopt;
  97. // Describes whether battery has been used for stylus-related elements,
  98. // or anything else. Note that stylus information received through the
  99. // touch-screen and the stylus charger (if present) are reported separately,
  100. // though their capacity may refer to the same battery.
  101. PeripheralType type = PeripheralType::kOther;
  102. ChargeStatus charge_status = ChargeStatus::kUnknown;
  103. // Peripheral's Bluetooth address. Empty for non-Bluetooth devices.
  104. std::string bluetooth_address;
  105. };
  106. // Interface for observing changes from the peripheral battery listener.
  107. class Observer : public base::CheckedObserver {
  108. public:
  109. ~Observer() override {}
  110. // All callback methods are given the current BatteryInfo state: do not take
  111. // or keep the address of the battery info, you will only be able to get the
  112. // current state when another callback is invoked, using the key for
  113. // identity.
  114. // Invoked when a new battery is detected; OnUpdatedBatteryLevel will always
  115. // be invoked (with same key) after an OnAddingBattery invocation. All
  116. // battery fields will match in the following OnUpdatedBatteryLevel
  117. // invocation.
  118. virtual void OnAddingBattery(const BatteryInfo& battery) = 0;
  119. // Invoked just before deletion of a battery record; there will be no
  120. // further updates to this battery key, unless and until OnAddingBattery is
  121. // invoked for the same key.
  122. virtual void OnRemovingBattery(const BatteryInfo& battery) = 0;
  123. // Invoked when the battery level changes for a battery. The level, as
  124. // optional, may not be set indicating an unknown level. An update may be
  125. // issued without any change to name or level, as updates are issued when we
  126. // specifically know we have received up-to-date information from the
  127. // stylus, even if there is no change of state from the last information.
  128. // Such no-change updates are not expected to occur faster than 30 second
  129. // intervals.
  130. virtual void OnUpdatedBatteryLevel(const BatteryInfo& battery) = 0;
  131. };
  132. // This class registers/unregisters itself as an observer in ctor/dtor.
  133. PeripheralBatteryListener();
  134. PeripheralBatteryListener(const PeripheralBatteryListener&) = delete;
  135. PeripheralBatteryListener& operator=(const PeripheralBatteryListener&) =
  136. delete;
  137. ~PeripheralBatteryListener() override;
  138. // Adds and removes an observer.
  139. void AddObserver(Observer* observer);
  140. void RemoveObserver(Observer* observer);
  141. bool HasObserver(const Observer* observer) const;
  142. // chromeos::PowerManagerClient::Observer:
  143. void PeripheralBatteryStatusReceived(
  144. const std::string& path,
  145. const std::string& name,
  146. int level,
  147. power_manager::PeripheralBatteryStatus_ChargeStatus status,
  148. const std::string& serial_number,
  149. bool active_update) override;
  150. // device::BluetoothAdapter::Observer:
  151. void DeviceBatteryChanged(device::BluetoothAdapter* adapter,
  152. device::BluetoothDevice* device,
  153. device::BluetoothDevice::BatteryType type) override;
  154. void DeviceConnectedStateChanged(device::BluetoothAdapter* adapter,
  155. device::BluetoothDevice* device,
  156. bool is_now_connected) override;
  157. void DeviceRemoved(device::BluetoothAdapter* adapter,
  158. device::BluetoothDevice* device) override;
  159. // ui::InputDeviceEventObserver:
  160. void OnDeviceListsComplete() override;
  161. private:
  162. friend class PeripheralBatteryNotifierListenerTest;
  163. FRIEND_TEST_ALL_PREFIXES(PeripheralBatteryNotifierListenerTest, Basic);
  164. FRIEND_TEST_ALL_PREFIXES(PeripheralBatteryNotifierListenerTest,
  165. InvalidBatteryInfo);
  166. FRIEND_TEST_ALL_PREFIXES(PeripheralBatteryNotifierListenerTest,
  167. ExtractBluetoothAddress);
  168. FRIEND_TEST_ALL_PREFIXES(PeripheralBatteryNotifierListenerTest, DeviceRemove);
  169. friend class PeripheralBatteryNotifierTest;
  170. friend class PeripheralBatteryListenerTest;
  171. FRIEND_TEST_ALL_PREFIXES(PeripheralBatteryListenerTest, Basic);
  172. FRIEND_TEST_ALL_PREFIXES(PeripheralBatteryListenerTest, DeviceRemove);
  173. FRIEND_TEST_ALL_PREFIXES(PeripheralBatteryListenerTest,
  174. ObserverationLifetimeObeyed);
  175. FRIEND_TEST_ALL_PREFIXES(PeripheralBatteryListenerTest,
  176. PartialObserverationLifetimeObeyed);
  177. FRIEND_TEST_ALL_PREFIXES(PeripheralBatteryListenerTest,
  178. PartialObserverationLifetimeCatchUp);
  179. FRIEND_TEST_ALL_PREFIXES(PeripheralBatteryListenerTest,
  180. MultipleObserverationLifetimeObeyed);
  181. friend class PeripheralBatteryListenerIncompleteDevicesTest;
  182. FRIEND_TEST_ALL_PREFIXES(PeripheralBatteryListenerIncompleteDevicesTest,
  183. GarageCharging);
  184. FRIEND_TEST_ALL_PREFIXES(PeripheralBatteryListenerIncompleteDevicesTest,
  185. GarageChargesFully);
  186. FRIEND_TEST_ALL_PREFIXES(PeripheralBatteryListenerIncompleteDevicesTest,
  187. GarageChargesFullyFromFiftyPercent);
  188. FRIEND_TEST_ALL_PREFIXES(PeripheralBatteryListenerIncompleteDevicesTest,
  189. GarageChargingResumed);
  190. FRIEND_TEST_ALL_PREFIXES(PeripheralBatteryListenerIncompleteDevicesTest,
  191. GarageChargingInterrupted);
  192. // Report whether we are producing a 'battery peripheral' based on
  193. // stylus dock/garage switch
  194. bool HasSyntheticStylusGarargePeripheral();
  195. void UpdateSyntheticStylusGarargePeripheral();
  196. void GetSwitchStateCallback(ui::StylusState state);
  197. // Compute the estimated charge level for the docked stylus based on
  198. // prior knowledge of stylus charge levels. Returns nullopt if there
  199. // was no prior information.
  200. absl::optional<uint8_t> DerateLastChargeLevel();
  201. // Periodic callback used when docked stylus is charging; it will
  202. // be provided with the time that charging started, and the derated
  203. // charge level at that time.
  204. void GarageTimerAction(base::TimeTicks charge_start_time,
  205. absl::optional<uint8_t> start_level);
  206. void NotifyAddingBattery(const BatteryInfo& battery);
  207. void NotifyRemovingBattery(const BatteryInfo& battery);
  208. void NotifyUpdatedBatteryLevel(const BatteryInfo& battery);
  209. void InitializeOnBluetoothReady(
  210. scoped_refptr<device::BluetoothAdapter> adapter);
  211. // Removes the Bluetooth battery with address |bluetooth_address|, and posts
  212. // the removal. Called when a bluetooth device has been changed or removed.
  213. void RemoveBluetoothBattery(const std::string& bluetooth_address);
  214. // Updates the battery information of the peripheral, posting the update.
  215. void UpdateBattery(const BatteryInfo& battery_info, bool active_update);
  216. // Record of existing battery information. For Bluetooth Devices, the key is
  217. // kBluetoothDeviceIdPrefix + the device's address. For HID devices, the key
  218. // is the device path. If a device uses HID over Bluetooth, it is indexed as a
  219. // Bluetooth device.
  220. base::flat_map<std::string, BatteryInfo> batteries_;
  221. // PeripheralBatteryListener is an observer of |bluetooth_adapter_| for
  222. // bluetooth device change/remove events.
  223. scoped_refptr<device::BluetoothAdapter> bluetooth_adapter_;
  224. // PeripheralBatteryListener is an observer of InputDeviceEventObserver for
  225. // stylus garage insertion/removal messages.
  226. void OnStylusStateChanged(ui::StylusState state) override;
  227. bool synthetic_stylus_garage_peripheral_ = false;
  228. absl::optional<ui::StylusState> current_stylus_state_;
  229. base::RepeatingTimer garage_charge_timer_;
  230. base::ObserverList<Observer> observers_;
  231. base::WeakPtrFactory<PeripheralBatteryListener> weak_factory_{this};
  232. };
  233. } // namespace ash
  234. #endif // ASH_SYSTEM_POWER_PERIPHERAL_BATTERY_LISTENER_H_