Properly implement low battery notification service (#577)
* Properly implement low battery notification service * Apply suggestions from code review --------- Co-authored-by: Jas Singh <jaskiratpal.singh@outlook.com>
This commit is contained in:
@@ -3,7 +3,18 @@ import icons from '../icons/icons';
|
||||
import { Notify } from '../utils';
|
||||
|
||||
export function warnOnLowBattery(): void {
|
||||
batteryService.connect('notify::percent', () => {
|
||||
let sentLowNotification = false;
|
||||
let sentHalfLowNotification = false;
|
||||
|
||||
batteryService.connect('notify::charging', () => {
|
||||
// Reset it when the battery is put to charge
|
||||
if (batteryService.charging) {
|
||||
sentLowNotification = false;
|
||||
sentHalfLowNotification = false;
|
||||
}
|
||||
});
|
||||
|
||||
batteryService.connect('notify::percentage', () => {
|
||||
const { lowBatteryThreshold, lowBatteryNotification, lowBatteryNotificationText, lowBatteryNotificationTitle } =
|
||||
options.menus.power;
|
||||
|
||||
@@ -11,14 +22,26 @@ export function warnOnLowBattery(): void {
|
||||
return;
|
||||
}
|
||||
|
||||
// batteryService.percentage will be a double in between 0 and 1, so we multiply it by 100 to convert it to the percentage
|
||||
const batteryPercentage = Math.floor(batteryService.percentage * 100);
|
||||
const lowThreshold = lowBatteryThreshold.get();
|
||||
|
||||
if (batteryService.percentage === lowThreshold || batteryService.percentage === lowThreshold / 2) {
|
||||
// To avoid double notifications, we check each of the thresholds and set the correct `sentNotification`, but then
|
||||
// combine them into one notification only
|
||||
let sendNotification = false;
|
||||
if (!sentLowNotification && batteryPercentage < lowThreshold) {
|
||||
sentLowNotification = true;
|
||||
sendNotification = true;
|
||||
}
|
||||
if (!sentHalfLowNotification && batteryPercentage < lowThreshold / 2) {
|
||||
sentHalfLowNotification = true;
|
||||
sendNotification = true;
|
||||
}
|
||||
|
||||
if (sendNotification) {
|
||||
Notify({
|
||||
summary: lowBatteryNotificationTitle
|
||||
.get()
|
||||
.replace('/$POWER_LEVEL/g', batteryService.percentage.toString()),
|
||||
body: lowBatteryNotificationText.get().replace('/$POWER_LEVEL/g', batteryService.percentage.toString()),
|
||||
summary: lowBatteryNotificationTitle.get().replace('$POWER_LEVEL', batteryPercentage.toString()),
|
||||
body: lowBatteryNotificationText.get().replace('$POWER_LEVEL', batteryPercentage.toString()),
|
||||
iconName: icons.ui.warning,
|
||||
urgency: 'critical',
|
||||
timeout: 7000,
|
||||
|
||||
Reference in New Issue
Block a user