diff --git a/README.md b/README.md index 92d60fe4..1ca9ba29 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,7 @@ See the [user documentation](documentation/README.md), [connection guide](docume - **Contact Groups**: Create custom groups to organize your mesh network contacts - **Message Reactions**: React to messages with emoji responses - **Message Replies**: Thread conversations with inline reply functionality -- **Android Auto & Watches**: Hear messages and reply by voice in Android Auto, or reply from the notification shade and Wear OS/Galaxy watches ([guide](documentation/notifications.md#android-auto)) +- **Android Auto & Watches**: Reply from the notification shade and Wear OS/Galaxy watches, or hear messages and reply by voice in Android Auto (optional build flag) ([guide](documentation/notifications.md#android-auto)) - **Channel Muting**: Mute a channel from its chat screen, the channel list, or its notification ### Mesh Network @@ -103,7 +103,7 @@ See the [user documentation](documentation/README.md), [connection guide](docume | Map & Location | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | Device Management | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | Repeater Hub | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | -| Notification replies | ✅
(incl. Android Auto, watches) | ❌ | ❌ | ❌ | ❌ | ❌ | +| Notification replies | ✅
(incl. watches; Android Auto optional) | ❌ | ❌ | ❌ | ❌ | ❌ | The matrix describes implemented functionality, not a guarantee that every feature has been tested on every device. Web device connections use Web Serial and require Chrome and a secure origin. Image inference and translation require native runtimes and are unavailable on web. Android APKs currently include only `arm64-v8a`; the minimum Android API follows the Flutter SDK used to build. @@ -228,7 +228,7 @@ Messages are transmitted as binary frames using a custom protocol optimized for - **Theme**: System default, light, or dark mode - **Language**: Use one of 18 languages (English, Chinese, French, Spanish, Portuguese, German, Dutch, Polish, Swedish, Italian, Slovak, Slovenian, Bulgarian, Russian, Ukrainian, Hungarian, Japanese, Korean) -- **Notifications**: Configurable for messages, channels, and node advertisements; per-channel muting; reply, mark-as-read, and mute actions on Android notifications and watches (reply and mark-as-read in Android Auto) +- **Notifications**: Configurable for messages, channels, and node advertisements; per-channel muting; reply, mark-as-read, and mute actions on Android notifications and watches (reply and mark-as-read in Android Auto when built with `--android-project-arg=androidAuto=true`) - **Battery Chemistry**: Support for NMC, LiFePO4, LiPo, and LiPo HV battery types - **Message Retry**: Automatic retry with configurable path clearing diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 8aa73ce6..24b5883c 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -98,6 +98,24 @@ android { // } } +// Android Auto (notification read-aloud and voice reply) is opt-in, because +// declaring it puts the app through Play's separate Android Auto review. +// Enable it with `flutter build apk --android-project-arg=androidAuto=true` +// or `./gradlew -PandroidAuto=true ...`. +val androidAutoEnabled = (findProperty("androidAuto") as String?)?.toBoolean() == true + +if (androidAutoEnabled) { + android.sourceSets.getByName("main").res.srcDir("src/androidAuto/res") +} + +androidComponents { + onVariants { variant -> + if (androidAutoEnabled) { + variant.sources.manifests.addStaticManifestFile("src/androidAuto/AndroidManifest.xml") + } + } +} + flutter { source = "../.." } diff --git a/android/app/src/androidAuto/AndroidManifest.xml b/android/app/src/androidAuto/AndroidManifest.xml new file mode 100644 index 00000000..4c5db2aa --- /dev/null +++ b/android/app/src/androidAuto/AndroidManifest.xml @@ -0,0 +1,9 @@ + + + + + + + diff --git a/android/app/src/main/res/xml/automotive_app_desc.xml b/android/app/src/androidAuto/res/xml/automotive_app_desc.xml similarity index 100% rename from android/app/src/main/res/xml/automotive_app_desc.xml rename to android/app/src/androidAuto/res/xml/automotive_app_desc.xml diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 3bb75c69..27d9692a 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -34,10 +34,6 @@ - - ` URI to clipboard | | Share Contact Zero-Hop | All types | Broadcasts the contact's advertisement one hop | -| Delete Contact | All types | Confirmation dialog → removes from device and clears messages | +| Delete Contact | All types | Confirmation dialog → removes from device and clears messages. If auto-add is on for that type, the radio adds it back the next time it advertises; the dialog warns about this | ## App Bar Menus diff --git a/documentation/map-and-location.md b/documentation/map-and-location.md index 3cfa7a6f..634235ef 100644 --- a/documentation/map-and-location.md +++ b/documentation/map-and-location.md @@ -103,10 +103,18 @@ Shows node count and pin count. Tappable to expand a legend of all marker types. ## Path Trace Map ### How to Access -- From the main map's radar icon +- From the main map's menu → **Path Trace** (build your own route, see below) - From a contact's long-press menu → "Path Trace / Ping" - From a message's path view → radar icon +### Building a Custom Trace on the Map +1. Open the map menu and choose **Path Trace**. A panel appears at the top of the map. +2. Tap nodes on the map in the order the trace should travel. **Remove Last** and **Clear** edit the list. +3. Choose **Round trip** (the trace comes back along the same hops) or **As entered** (the hops are used exactly as listed, so add the return hops yourself). +4. Tap **Run path trace**. Nothing is sent until you press this button. + +Returning from the result keeps your hops, mode and the last result (**View last result** reopens it without sending again). **Close** or the back button hides the panel without discarding the hops; reopening **Path Trace** during the same session resumes where you left off. The hops are dropped when you connect to a different radio. + ### What the User Sees A map with a polyline showing the route from your node through repeater hops to the target: - **Green circles**: Hops with known GPS coordinates diff --git a/documentation/notifications.md b/documentation/notifications.md index 0f08a095..535570c3 100644 --- a/documentation/notifications.md +++ b/documentation/notifications.md @@ -42,7 +42,7 @@ Message notifications can be answered without opening the app, from the notifica - **Reply** sends through the connected radio exactly like the chat screen: same length limits, SMAZ and Cyr2Lat handling, and retries. Your reply is then added to the notification. - **Replies over the message limit** are split at word boundaries into up to 3 messages. Longer replies are not sent; a "Reply not sent" notification asks you to open the app. - **Mark as read** clears the unread count on the phone only. MeshCore has no read receipts, so nothing is sent over the mesh. -- **Mute channel** (phone and watch) mutes that channel, the same as the bell icon in the channel chat. +- **Mute channel** (phone and watch) sets that channel to **Muted**, the same as choosing Muted from the bell icon in the channel chat. - If the radio is disconnected, the conversation is no longer on the radio, the radio reports a send error, or the app isn't running, a "Reply not sent" notification explains why. The reply is not queued. If a split reply fails partway, earlier parts may already have been sent. - Replies are sent as typed; composer translation is not applied. @@ -52,6 +52,14 @@ iOS notifications do not have reply actions yet. MeshCore Open works in Android Auto as a notification-based messaging app. There is no MeshCore screen in the car; Android Auto provides the interface. +Android Auto support is off by default and is compiled in only when the build passes the `androidAuto` Gradle property: + +```bash +flutter build apk --release --android-project-arg=androidAuto=true +``` + +The flag merges `android/app/src/androidAuto/` (the `com.google.android.gms.car.application` manifest entry and `automotive_app_desc.xml`) into the app. Without it, Android Auto does not list the app. Notification replies from the shade and watches work either way. + - New direct and channel messages appear on the car display and can be read aloud. - Reply by voice or with a suggested reply; replies follow the rules above (splitting, failure notifications, no translation). - Android Auto shows **Reply** and **Mark as read**. **Mute channel** is marked as a mute action, but Android Auto only documents reply and mark-as-read for messaging apps, so mute may not appear in the car; use the phone, a watch, or the bell icon. @@ -99,15 +107,24 @@ Access via **App Settings → Notifications**: | Channel Message Notifications | On | Channel alerts (greyed out if master is off) | | Advertisement Notifications | On | New node alerts (greyed out if master is off) | -### Per-Channel Muting +### Per-Channel Notification Modes -Mute or unmute a channel from any of these places. Muted channels do not generate OS notifications. +Each channel supports three notification modes: -- The bell icon in the channel chat app bar -- Long-press a channel in the channels list → "Mute channel" / "Unmute channel" -- **Mute channel** on a channel notification (Android) +| Mode | Icon | Behavior | +|---|---|---| +| **All messages** | 🔔 | Receive notifications for every message | +| **Mentions only** | 🔔! | Only notify when a message mentions your name (see below) | +| **Muted** | 🔕 | No notifications | -There is no per-contact muting. +Set the mode from: + +- The notifications icon in the channel chat app bar (tap to open the mode picker) +- Long-press a channel in the channels list → **Notification settings** → select mode + +The Android **Mute channel** notification action sets the channel to **Muted**; it cannot choose another mode. + +A message mentions you if it contains `@[yourname]` or `@yourname`, case-insensitively. The plain `@yourname` form must stand alone as a word, so `@bobby` does not mention `bob` and `x@bob.com` is not a mention; names with spaces must be written in full. Detection (`MeshCoreConnector.textMentionsName`) runs on the original text, before any automatic translation. ## Rate Limiting diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 57ef9fc1..f535ed25 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -38,7 +38,8 @@ import '../services/image_codec_service.dart'; import '../services/received_image_store.dart'; import '../services/message_retry_service.dart'; import '../services/path_history_service.dart'; -import '../services/app_settings_service.dart'; +import '../services/app_settings_service.dart' + show AppSettingsService, ChannelNotificationMode; import '../services/background_service.dart'; import '../services/timeout_prediction_service.dart'; import '../services/translation_service.dart'; @@ -298,6 +299,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); @@ -667,6 +684,16 @@ class MeshCoreConnector extends ChangeNotifier { bool? get autoAddSensors => _autoAddSensors; bool? get autoAddOverwriteOldest => _overwriteOldest; + /// Whether the radio stores adverts of [type] by itself, so a removed + /// contact of that type returns the next time it advertises. + bool autoAddsContactType(int type) => switch (type) { + advTypeChat => _autoAddUsers, + advTypeRepeater => _autoAddRepeaters, + advTypeRoom => _autoAddRoomServers, + advTypeSensor => _autoAddSensors, + _ => false, + }; + /// autoadd_max_hops from GET_AUTOADD_CONFIG (0 = no limit), null when the /// firmware did not report it (pre-v1.13). int? get autoAddMaxHops => _autoAddMaxHops; @@ -681,6 +708,9 @@ class MeshCoreConnector extends ChangeNotifier { /// from ver code 8. bool get supportsNodeDiscover => (_firmwareVerCode ?? 0) >= 8; + /// CMD_SET_PATH_HASH_MODE exists from ver code 10 (v1.14.0). + bool get supportsPathHashMode => (_firmwareVerCode ?? 0) >= 10; + /// CMD_GET/SET_DEFAULT_FLOOD_SCOPE exist from ver code 11 (v1.15.0). bool get supportsDefaultFloodScope => (_firmwareVerCode ?? 0) >= 11; @@ -1246,8 +1276,9 @@ class MeshCoreConnector extends ChangeNotifier { /// (notification shade, watch, or Android Auto). Future handleNotificationReply(NotificationReply reply) async { if (reply.action == NotificationReplyAction.mute) { - await _appSettingsService?.muteChannel( + await _appSettingsService?.setChannelNotificationMode( _channelDisplayName(reply.channelIndex!), + ChannelNotificationMode.muted, ); await _notificationService.clearChannelNotification( reply.channelIndex!, @@ -4359,7 +4390,7 @@ class MeshCoreConnector extends ChangeNotifier { _pathOpLock = completer.future; await prev; try { - if (!isConnected) return; + if (!isConnected || !_isKnownContact(contact)) return; final width = pathHashWidth ?? @@ -4402,6 +4433,13 @@ class MeshCoreConnector extends ChangeNotifier { } } + /// Whether [contact] is still in the radio's contact list. The firmware's + /// CMD_ADD_UPDATE_CONTACT adds unknown keys, so path/flag writes for a + /// removed contact (e.g. a repeater screen still open after its old key was + /// deleted) would re-create it on the radio. + bool _isKnownContact(Contact contact) => + _contacts.any((c) => c.publicKeyHex == contact.publicKeyHex); + /// The advert timestamp the firmware holds for [contact] (Contact.lastSeen /// is parsed from that field); the stored copy is freshest. DateTime _deviceLastAdvert(Contact contact) { @@ -4418,7 +4456,7 @@ class MeshCoreConnector extends ChangeNotifier { bool? teleLoc, bool? teleEnv, }) async { - if (!isConnected) return; + if (!isConnected || !_isKnownContact(contact)) return; final latestContact = await _fetchContactSnapshotFromDevice(contact.publicKey) ?? contact; int updatedFlags = isFavorite != null @@ -5037,13 +5075,26 @@ class MeshCoreConnector extends ChangeNotifier { }) async { if (!isConnected) return; + // Only drop the contact locally once the radio confirms; otherwise the + // next contact sync restores it. ERR means the radio does not have it. + try { + await sendFrame( + buildRemoveContactFrame(contact.publicKey), + waitForGenericAck: true, + ); + } on FirmwareCommandException catch (e) { + _appDebugLogService?.warn( + 'Radio has no contact ${contact.publicKeyHex.substring(0, 8)} ' + '(error ${e.errCode}); removing it locally', + tag: 'Connector', + ); + } + _handleDiscovery( contact, contact.rawPacket ?? Uint8List(0), noNotify: true, ); - - await sendFrame(buildRemoveContactFrame(contact.publicKey)); _contactsStorageFull = false; _contacts.removeWhere((c) => c.publicKeyHex == contact.publicKeyHex); _knownContactKeys.remove(contact.publicKeyHex); @@ -6473,6 +6524,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)', @@ -6487,6 +6539,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 @@ -7355,7 +7465,12 @@ class MeshCoreConnector extends ChangeNotifier { } final label = channelName ?? _channelDisplayName(channelIndex); - if (_appSettingsService!.isChannelMuted(label)) return; + final notificationMode = _appSettingsService!.getChannelNotificationMode( + label, + ); + + // Check if channel is muted + if (notificationMode == ChannelNotificationMode.muted) return; // Reuse translation result only if completed and non-empty; else use original text final resolvedText = @@ -7364,6 +7479,14 @@ class MeshCoreConnector extends ChangeNotifier { translationResult.translatedText.trim().isNotEmpty) ? translationResult.translatedText.trim() : message.text.trim(); + + // Mentions are matched on the untranslated text. + if (notificationMode == ChannelNotificationMode.mentionsOnly) { + if (!textMentionsName(message.originalText ?? message.text, _selfName)) { + return; + } + } + unawaited(() async { await _notificationService.showChannelMessageNotification( channelName: label, @@ -7376,6 +7499,22 @@ class MeshCoreConnector extends ChangeNotifier { }()); } + /// Whether [text] mentions [name], case-insensitively, as either + /// `@[name]` (the reply/mention prefix the app sends) or a plain `@name`. + /// The plain form needs a word boundary on both sides, so `@bobby` does + /// not mention `bob` and `x@bob.com` is not a mention. Names containing + /// spaces must be written out in full. + @visibleForTesting + static bool textMentionsName(String text, String? name) { + if (name == null || name.isEmpty) return false; + final escaped = RegExp.escape(name); + return RegExp( + '@\\[$escaped\\]|(? 'Exception: Command failed with error code $errCode'; +} + /// A command waiting for its reply from the companion firmware. class PendingCommandReply { final int commandCode; @@ -203,9 +213,7 @@ class PendingCommandReplies { if (_queue.isEmpty) return null; final pending = _queue.removeAt(0); if (pending.isTombstone) return null; - pending.completer?.completeError( - Exception('Command failed with error code $errCode'), - ); + pending.completer?.completeError(FirmwareCommandException(errCode)); return pending; } diff --git a/lib/helpers/marker_message.dart b/lib/helpers/marker_message.dart new file mode 100644 index 00000000..52f251c6 --- /dev/null +++ b/lib/helpers/marker_message.dart @@ -0,0 +1,30 @@ +import 'package:latlong2/latlong.dart'; + +class MarkerPayload { + final LatLng position; + final String label; + final String flags; + + MarkerPayload({ + required this.position, + required this.label, + required this.flags, + }); +} + +/// Parse a shared marker text message of the form +/// `m:,|