From 006e9543f05e0c70faaf125b99ae90cde47192f9 Mon Sep 17 00:00:00 2001 From: davfsa Date: Sat, 21 Dec 2024 21:11:42 +0100 Subject: [PATCH] Properly implement low battery notification service (#577) * Properly implement low battery notification service * Apply suggestions from code review --------- Co-authored-by: Jas Singh --- src/lib/behaviors/batteryWarning.ts | 35 ++++++++++++++++++++++++----- 1 file changed, 29 insertions(+), 6 deletions(-) diff --git a/src/lib/behaviors/batteryWarning.ts b/src/lib/behaviors/batteryWarning.ts index 5392d3d..419157d 100644 --- a/src/lib/behaviors/batteryWarning.ts +++ b/src/lib/behaviors/batteryWarning.ts @@ -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,