diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 03b03944..fbdd914c 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -298,6 +298,22 @@ class MeshCoreConnector extends ChangeNotifier { Stopwatch? _airtimeBumpStopwatch; int _prevTotalAirSecs = 0; int? _batteryMillivolts; + // Thresholds (percent) that trigger a low-battery notification once per + // crossing, re-arming 5 points above the threshold after recharge. + static const List _lowBatteryThresholds = [25, 10]; + final Set _batteryAlertedThresholds = {}; + // Consecutive readings that newly crossed a threshold. Alerts need + // [_lowBatteryConfirmReadings] in a row so a single TX-load voltage sag + // doesn't notify. + int _lowBatteryReadingStreak = 0; + // Device key the posted low-battery notifications were scoped to, kept so + // they can still be cancelled after the session's identity is cleared. + String? _lowBatteryAlertDeviceKey; + static const int _lowBatteryConfirmReadings = 2; + // Readings below this are treated as "no battery sensor" (boards without + // one report 0 mV). Any single Li cell, including LiFePO4 (2600 mV empty), + // is protection-cut well above 2 V, so lower values are not real readings. + static const int _minPlausibleBatteryMillivolts = 2000; double? _selfLatitude; double? _selfLongitude; final List _directRepeaters = List.empty(growable: true); @@ -6471,6 +6487,7 @@ class MeshCoreConnector extends ChangeNotifier { _batteryMillivolts = reader.readUInt16LE(); _storageUsedKb = reader.readUInt32LE(); _storageTotalKb = reader.readUInt32LE(); + _checkLowBatteryThresholds(); final volts = (_batteryMillivolts! / 1000.0).toStringAsFixed(2); _appDebugLogService?.info( 'Pulled battery: $volts V ($_batteryMillivolts mV)', @@ -6485,6 +6502,64 @@ class MeshCoreConnector extends ChangeNotifier { } } + void _checkLowBatteryThresholds() { + final millivolts = _batteryMillivolts; + if (millivolts == null || millivolts < _minPlausibleBatteryMillivolts) { + return; + } + // Until the device identity (and so its saved chemistry) is known, the + // percentage falls back to NMC and can read low for e.g. LiFePO4 packs. + // Skip evaluation; the next battery poll re-checks once identity is set. + if (batteryDeviceKey == null || _appSettingsService == null) return; + final percent = batteryPercent; + if (percent == null) return; + + // Only the lowest newly crossed threshold notifies; higher ones crossed + // in the same reading are marked as alerted silently. + final newlyCrossed = []; + for (final threshold in _lowBatteryThresholds) { + if (percent <= threshold && + !_batteryAlertedThresholds.contains(threshold)) { + newlyCrossed.add(threshold); + } else if (percent > threshold + 5 && + _batteryAlertedThresholds.contains(threshold)) { + // Re-arm once the battery recovers 5 points above the threshold, + // so a recharge + discharge cycle alerts again without flapping. + _batteryAlertedThresholds.remove(threshold); + final alertDeviceKey = _lowBatteryAlertDeviceKey; + if (alertDeviceKey != null) { + unawaited( + _notificationService.clearLowBatteryNotifications(alertDeviceKey, [ + threshold, + ]), + ); + } + } + } + if (newlyCrossed.isEmpty) { + _lowBatteryReadingStreak = 0; + return; + } + // Debounce: wait for consecutive low readings before alerting. + if (++_lowBatteryReadingStreak < _lowBatteryConfirmReadings) return; + _lowBatteryReadingStreak = 0; + _batteryAlertedThresholds.addAll(newlyCrossed); + final deviceKey = batteryDeviceKey!; + _lowBatteryAlertDeviceKey = deviceKey; + final lowestNewlyCrossed = newlyCrossed.reduce((a, b) => a < b ? a : b); + if (!(_appSettingsService?.settings.notificationsEnabled ?? false)) { + return; + } + unawaited( + _notificationService.showLowBatteryNotification( + deviceKey: deviceKey, + deviceName: deviceDisplayName, + batteryPercent: percent, + threshold: lowestNewlyCrossed, + ), + ); + } + void _checkManualAddContacts() async { // If manual add contacts is enabled, set auto add config and other params. // and disable it after @@ -8568,6 +8643,18 @@ class MeshCoreConnector extends ChangeNotifier { _hasReceivedDeviceInfo = false; _batteryMillivolts = null; _batteryRequested = false; + final alertDeviceKey = _lowBatteryAlertDeviceKey; + if (alertDeviceKey != null && _batteryAlertedThresholds.isNotEmpty) { + unawaited( + _notificationService.clearLowBatteryNotifications( + alertDeviceKey, + _batteryAlertedThresholds.toList(), + ), + ); + } + _batteryAlertedThresholds.clear(); + _lowBatteryAlertDeviceKey = null; + _lowBatteryReadingStreak = 0; _pathHashByteWidth = 1; _maxContacts = _defaultMaxContacts; _maxChannels = _defaultMaxChannels; diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index f62a038b..8e949cab 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -2678,6 +2678,22 @@ "contacts_contactAdvertCopied": "Advert copied to Clipboard.", "contacts_contactAdvertCopyFailed": "Copying advert to Clipboard failed.", "notification_activityTitle": "MeshCore Activity", + "notification_lowBatteryTitle": "Low battery", + "@notification_lowBatteryTitle": { + "description": "Title of the low battery notification" + }, + "notification_lowBatteryBody": "{deviceName} battery is at {percent}%", + "@notification_lowBatteryBody": { + "description": "Body of the low battery notification; deviceName is the connected radio's node name", + "placeholders": { + "deviceName": { + "type": "String" + }, + "percent": { + "type": "int" + } + } + }, "notification_messagesCount": "{count} {count, plural, =1{message} other{messages}}", "@notification_messagesCount": { "placeholders": { diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index b5e7efc5..58630f96 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -8108,6 +8108,18 @@ abstract class AppLocalizations { /// **'MeshCore Activity'** String get notification_activityTitle; + /// Title of the low battery notification + /// + /// In en, this message translates to: + /// **'Low battery'** + String get notification_lowBatteryTitle; + + /// Body of the low battery notification; deviceName is the connected radio's node name + /// + /// In en, this message translates to: + /// **'{deviceName} battery is at {percent}%'** + String notification_lowBatteryBody(String deviceName, int percent); + /// No description provided for @notification_messagesCount. /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index b9f79a6f..d8bec52f 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -4727,6 +4727,14 @@ class AppLocalizationsBg extends AppLocalizations { @override String get notification_activityTitle => 'Активност на MeshCore'; + @override + String get notification_lowBatteryTitle => 'Low battery'; + + @override + String notification_lowBatteryBody(String deviceName, int percent) { + return '$deviceName battery is at $percent%'; + } + @override String notification_messagesCount(int count) { String _temp0 = intl.Intl.pluralLogic( diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index d7893ccf..a03829e6 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -4738,6 +4738,14 @@ class AppLocalizationsDe extends AppLocalizations { @override String get notification_activityTitle => 'MeshCore Aktivität'; + @override + String get notification_lowBatteryTitle => 'Low battery'; + + @override + String notification_lowBatteryBody(String deviceName, int percent) { + return '$deviceName battery is at $percent%'; + } + @override String notification_messagesCount(int count) { String _temp0 = intl.Intl.pluralLogic( diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 0265ac8b..8a4cea69 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -4662,6 +4662,14 @@ class AppLocalizationsEn extends AppLocalizations { @override String get notification_activityTitle => 'MeshCore Activity'; + @override + String get notification_lowBatteryTitle => 'Low battery'; + + @override + String notification_lowBatteryBody(String deviceName, int percent) { + return '$deviceName battery is at $percent%'; + } + @override String notification_messagesCount(int count) { String _temp0 = intl.Intl.pluralLogic( diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 75c2ab0e..dc0b28be 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -4729,6 +4729,14 @@ class AppLocalizationsEs extends AppLocalizations { @override String get notification_activityTitle => 'Actividad de MeshCore'; + @override + String get notification_lowBatteryTitle => 'Low battery'; + + @override + String notification_lowBatteryBody(String deviceName, int percent) { + return '$deviceName battery is at $percent%'; + } + @override String notification_messagesCount(int count) { String _temp0 = intl.Intl.pluralLogic( diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 85de8bbb..f55984f5 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -4748,6 +4748,14 @@ class AppLocalizationsFr extends AppLocalizations { @override String get notification_activityTitle => 'Activité MeshCore'; + @override + String get notification_lowBatteryTitle => 'Low battery'; + + @override + String notification_lowBatteryBody(String deviceName, int percent) { + return '$deviceName battery is at $percent%'; + } + @override String notification_messagesCount(int count) { String _temp0 = intl.Intl.pluralLogic( diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index ef4b3d9b..e35c1981 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -4726,6 +4726,14 @@ class AppLocalizationsHu extends AppLocalizations { @override String get notification_activityTitle => 'MeshCore tevékenység'; + @override + String get notification_lowBatteryTitle => 'Low battery'; + + @override + String notification_lowBatteryBody(String deviceName, int percent) { + return '$deviceName battery is at $percent%'; + } + @override String notification_messagesCount(int count) { String _temp0 = intl.Intl.pluralLogic( diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 50bb49d9..c4a97a49 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -4735,6 +4735,14 @@ class AppLocalizationsIt extends AppLocalizations { @override String get notification_activityTitle => 'Attività MeshCore'; + @override + String get notification_lowBatteryTitle => 'Low battery'; + + @override + String notification_lowBatteryBody(String deviceName, int percent) { + return '$deviceName battery is at $percent%'; + } + @override String notification_messagesCount(int count) { String _temp0 = intl.Intl.pluralLogic( diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 2aabf56e..8066f4ec 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -4498,6 +4498,14 @@ class AppLocalizationsJa extends AppLocalizations { @override String get notification_activityTitle => 'メッシュコアの活動'; + @override + String get notification_lowBatteryTitle => 'Low battery'; + + @override + String notification_lowBatteryBody(String deviceName, int percent) { + return '$deviceName battery is at $percent%'; + } + @override String notification_messagesCount(int count) { String _temp0 = intl.Intl.pluralLogic( diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 98a81ac1..db66d010 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -4509,6 +4509,14 @@ class AppLocalizationsKo extends AppLocalizations { @override String get notification_activityTitle => '메쉬코어 활동'; + @override + String get notification_lowBatteryTitle => 'Low battery'; + + @override + String notification_lowBatteryBody(String deviceName, int percent) { + return '$deviceName battery is at $percent%'; + } + @override String notification_messagesCount(int count) { String _temp0 = intl.Intl.pluralLogic( diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index 082f2a18..470c6646 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -4704,6 +4704,14 @@ class AppLocalizationsNl extends AppLocalizations { @override String get notification_activityTitle => 'MeshCore Activiteit'; + @override + String get notification_lowBatteryTitle => 'Low battery'; + + @override + String notification_lowBatteryBody(String deviceName, int percent) { + return '$deviceName battery is at $percent%'; + } + @override String notification_messagesCount(int count) { String _temp0 = intl.Intl.pluralLogic( diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index 3db02722..96f15d50 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -4755,6 +4755,14 @@ class AppLocalizationsPl extends AppLocalizations { @override String get notification_activityTitle => 'Aktywność MeshCore'; + @override + String get notification_lowBatteryTitle => 'Low battery'; + + @override + String notification_lowBatteryBody(String deviceName, int percent) { + return '$deviceName battery is at $percent%'; + } + @override String notification_messagesCount(int count) { String _temp0 = intl.Intl.pluralLogic( diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 9b89ff31..9358590b 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -4731,6 +4731,14 @@ class AppLocalizationsPt extends AppLocalizations { @override String get notification_activityTitle => 'Atividade MeshCore'; + @override + String get notification_lowBatteryTitle => 'Low battery'; + + @override + String notification_lowBatteryBody(String deviceName, int percent) { + return '$deviceName battery is at $percent%'; + } + @override String notification_messagesCount(int count) { String _temp0 = intl.Intl.pluralLogic( diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index a1686804..f808604f 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -4739,6 +4739,14 @@ class AppLocalizationsRu extends AppLocalizations { @override String get notification_activityTitle => 'Активность MeshCore'; + @override + String get notification_lowBatteryTitle => 'Low battery'; + + @override + String notification_lowBatteryBody(String deviceName, int percent) { + return '$deviceName battery is at $percent%'; + } + @override String notification_messagesCount(int count) { String _temp0 = intl.Intl.pluralLogic( diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 9cd7cc6d..12977b44 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -4712,6 +4712,14 @@ class AppLocalizationsSk extends AppLocalizations { @override String get notification_activityTitle => 'Aktivita MeshCore'; + @override + String get notification_lowBatteryTitle => 'Low battery'; + + @override + String notification_lowBatteryBody(String deviceName, int percent) { + return '$deviceName battery is at $percent%'; + } + @override String notification_messagesCount(int count) { String _temp0 = intl.Intl.pluralLogic( diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 8602eb0d..9b629d4a 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -4710,6 +4710,14 @@ class AppLocalizationsSl extends AppLocalizations { @override String get notification_activityTitle => 'Aktivnost MeshCore'; + @override + String get notification_lowBatteryTitle => 'Low battery'; + + @override + String notification_lowBatteryBody(String deviceName, int percent) { + return '$deviceName battery is at $percent%'; + } + @override String notification_messagesCount(int count) { String _temp0 = intl.Intl.pluralLogic( diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index 1d87483d..129ddf72 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -4686,6 +4686,14 @@ class AppLocalizationsSv extends AppLocalizations { @override String get notification_activityTitle => 'MeshCore Aktivitet'; + @override + String get notification_lowBatteryTitle => 'Low battery'; + + @override + String notification_lowBatteryBody(String deviceName, int percent) { + return '$deviceName battery is at $percent%'; + } + @override String notification_messagesCount(int count) { String _temp0 = intl.Intl.pluralLogic( diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index ebd6d5eb..1d425252 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -4738,6 +4738,14 @@ class AppLocalizationsUk extends AppLocalizations { @override String get notification_activityTitle => 'Активність MeshCore'; + @override + String get notification_lowBatteryTitle => 'Low battery'; + + @override + String notification_lowBatteryBody(String deviceName, int percent) { + return '$deviceName battery is at $percent%'; + } + @override String notification_messagesCount(int count) { String _temp0 = intl.Intl.pluralLogic( diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 703a27fe..fa67ef7d 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -4406,6 +4406,14 @@ class AppLocalizationsZh extends AppLocalizations { @override String get notification_activityTitle => 'MeshCore 活动'; + @override + String get notification_lowBatteryTitle => 'Low battery'; + + @override + String notification_lowBatteryBody(String deviceName, int percent) { + return '$deviceName battery is at $percent%'; + } + @override String notification_messagesCount(int count) { return '$count 条消息'; diff --git a/lib/services/notification_service.dart b/lib/services/notification_service.dart index 66963a39..334240c6 100644 --- a/lib/services/notification_service.dart +++ b/lib/services/notification_service.dart @@ -598,6 +598,54 @@ class NotificationService { } } + /// Posts a low-battery alert for the connected device. + /// + /// Uses a per-device, per-threshold notification id so each alert level + /// updates its own notification instead of stacking, and alerts for + /// different radios don't overwrite each other. Bypasses the rate-limit + /// queue, which only handles message and advert notifications. + Future showLowBatteryNotification({ + required String deviceKey, + required String deviceName, + required int batteryPercent, + required int threshold, + }) async { + if (!await _ensureCanNotify()) return; + + const androidDetails = AndroidNotificationDetails( + 'low_battery', + 'Low Battery', + channelDescription: 'Low battery alerts for the connected device', + importance: Importance.high, + priority: Priority.high, + icon: '@mipmap/ic_launcher', + ); + + const darwinDetails = DarwinNotificationDetails( + presentAlert: true, + presentBadge: false, + presentSound: true, + ); + + const notificationDetails = NotificationDetails( + android: androidDetails, + iOS: darwinDetails, + macOS: darwinDetails, + ); + + try { + await _notifications.show( + id: _lowBatteryNotificationId(deviceKey, threshold), + title: _l10n.notification_lowBatteryTitle, + body: _l10n.notification_lowBatteryBody(deviceName, batteryPercent), + notificationDetails: notificationDetails, + payload: 'low_battery', + ); + } catch (e) { + debugPrint('Failed to show low battery notification: $e'); + } + } + /// Returns a privacy-safe identifier for debug logging. /// - advert: shows device name (body contains contactName) /// - message: shows "from: sender" (avoids logging message content) @@ -654,6 +702,26 @@ class NotificationService { await _updateBadge(totalUnreadCount); } + static int _lowBatteryNotificationId(String deviceKey, int threshold) => + 'low_battery:$deviceKey:$threshold'.hashCode; + + /// Cancel a device's low-battery notifications for the given thresholds. + Future clearLowBatteryNotifications( + String deviceKey, + Iterable thresholds, + ) async { + if (!await _ensureInitialized()) return; + for (final threshold in thresholds) { + try { + await _notifications.cancel( + id: _lowBatteryNotificationId(deviceKey, threshold), + ); + } catch (e) { + debugPrint('Failed to clear low battery notification: $e'); + } + } + } + /// Cancel advert notifications for the given contact public key hexes. Future clearAdvertNotifications(List contactIds) async { if (!await _ensureInitialized()) return; diff --git a/untranslated.json b/untranslated.json index 9e26dfee..440e93f0 100644 --- a/untranslated.json +++ b/untranslated.json @@ -1 +1,86 @@ -{} \ No newline at end of file +{ + "bg": [ + "notification_lowBatteryTitle", + "notification_lowBatteryBody" + ], + + "de": [ + "notification_lowBatteryTitle", + "notification_lowBatteryBody" + ], + + "es": [ + "notification_lowBatteryTitle", + "notification_lowBatteryBody" + ], + + "fr": [ + "notification_lowBatteryTitle", + "notification_lowBatteryBody" + ], + + "hu": [ + "notification_lowBatteryTitle", + "notification_lowBatteryBody" + ], + + "it": [ + "notification_lowBatteryTitle", + "notification_lowBatteryBody" + ], + + "ja": [ + "notification_lowBatteryTitle", + "notification_lowBatteryBody" + ], + + "ko": [ + "notification_lowBatteryTitle", + "notification_lowBatteryBody" + ], + + "nl": [ + "notification_lowBatteryTitle", + "notification_lowBatteryBody" + ], + + "pl": [ + "notification_lowBatteryTitle", + "notification_lowBatteryBody" + ], + + "pt": [ + "notification_lowBatteryTitle", + "notification_lowBatteryBody" + ], + + "ru": [ + "notification_lowBatteryTitle", + "notification_lowBatteryBody" + ], + + "sk": [ + "notification_lowBatteryTitle", + "notification_lowBatteryBody" + ], + + "sl": [ + "notification_lowBatteryTitle", + "notification_lowBatteryBody" + ], + + "sv": [ + "notification_lowBatteryTitle", + "notification_lowBatteryBody" + ], + + "uk": [ + "notification_lowBatteryTitle", + "notification_lowBatteryBody" + ], + + "zh": [ + "notification_lowBatteryTitle", + "notification_lowBatteryBody" + ] +}