|
| 1 | +import 'dart:async'; |
| 2 | + |
| 3 | +import 'package:battery_plus_platform_interface/battery_plus_platform_interface.dart'; |
| 4 | +import 'package:meta/meta.dart'; |
| 5 | + |
| 6 | +import 'upower_device.dart'; |
| 7 | + |
| 8 | +// ### TODO: introduce an 'unknown' battery state for workstations? |
| 9 | +// https://github.com/fluttercommunity/plus_plugins/issues/61 |
| 10 | +extension _ToBatteryState on UPowerBatteryState { |
| 11 | + BatteryState toBatteryState() { |
| 12 | + switch (this) { |
| 13 | + case UPowerBatteryState.charging: |
| 14 | + return BatteryState.charging; |
| 15 | + case UPowerBatteryState.discharging: |
| 16 | + return BatteryState.discharging; |
| 17 | + default: |
| 18 | + return BatteryState.full; |
| 19 | + } |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +@visibleForTesting |
| 24 | +typedef UPowerDeviceFactory = UPowerDevice Function(); |
| 25 | + |
| 26 | +/// The Linux implementation of BatteryPlatform. |
| 27 | +class BatteryLinux extends BatteryPlatform { |
| 28 | + /// Returns the current battery level in percent. |
| 29 | + @override |
| 30 | + Future<int> get batteryLevel { |
| 31 | + final device = createDevice(); |
| 32 | + return device |
| 33 | + .getPercentage() |
| 34 | + .then((value) => value.round()) |
| 35 | + .whenComplete(() => device.dispose()); |
| 36 | + } |
| 37 | + |
| 38 | + /// Fires whenever the battery state changes. |
| 39 | + @override |
| 40 | + Stream<BatteryState> get onBatteryStateChanged { |
| 41 | + _stateController ??= StreamController<BatteryState>( |
| 42 | + onListen: _startListenState, |
| 43 | + onCancel: _stopListenState, |
| 44 | + ); |
| 45 | + return _stateController.stream.asBroadcastStream(); |
| 46 | + } |
| 47 | + |
| 48 | + UPowerDevice _stateDevice; |
| 49 | + StreamController<BatteryState> _stateController; |
| 50 | + |
| 51 | + @visibleForTesting |
| 52 | + UPowerDeviceFactory createDevice = () => UPowerDevice.display(); |
| 53 | + |
| 54 | + void _addState(UPowerBatteryState value) { |
| 55 | + _stateController.add(value.toBatteryState()); |
| 56 | + } |
| 57 | + |
| 58 | + void _startListenState() { |
| 59 | + _stateDevice ??= createDevice(); |
| 60 | + _stateDevice.getState().then((value) => _addState(value)); |
| 61 | + _stateDevice.subscribeStateChanged().listen((value) => _addState(value)); |
| 62 | + } |
| 63 | + |
| 64 | + void _stopListenState() { |
| 65 | + _stateDevice?.dispose(); |
| 66 | + _stateDevice = null; |
| 67 | + } |
| 68 | +} |
0 commit comments