Compare commits

..

7 Commits

Author SHA1 Message Date
Janez T
a24e699e22 fix: Refresh MeshCore lock #31
ref: dz0ny/meshcore-sar#31
2026-03-22 09:49:16 +01:00
Janez T
7486837ad0 fix: Compact recipient selector #0 2026-03-22 09:37:53 +01:00
Janez T
059125c714 fix: Restore telemetry refresh behavior
ref:
2026-03-22 09:19:33 +01:00
Janez T
9279ff2158 chore: Bump iOS build number #123 2026-03-21 20:45:09 +01:00
Janez T
dc297b0b9f fix: Tighten device settings layout 2026-03-21 20:44:29 +01:00
Janez T
2d24481aba feat: Add MET history isolation 2026-03-21 19:22:43 +01:00
Janez T
20a1df94eb fix: Support MeshCore message links #123 2026-03-21 18:36:56 +01:00
43 changed files with 6430 additions and 1279 deletions

View File

@@ -489,7 +489,7 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CURRENT_PROJECT_VERSION = 122;
CURRENT_PROJECT_VERSION = 124;
DEVELOPMENT_TEAM = JND55328G8;
ENABLE_BITCODE = NO;
INFOPLIST_FILE = Runner/Info.plist;
@@ -511,7 +511,7 @@
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 122;
CURRENT_PROJECT_VERSION = 124;
DEVELOPMENT_TEAM = JND55328G8;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
@@ -530,7 +530,7 @@
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 122;
CURRENT_PROJECT_VERSION = 124;
DEVELOPMENT_TEAM = JND55328G8;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
@@ -547,7 +547,7 @@
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 122;
CURRENT_PROJECT_VERSION = 124;
DEVELOPMENT_TEAM = JND55328G8;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
@@ -679,7 +679,7 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CURRENT_PROJECT_VERSION = 122;
CURRENT_PROJECT_VERSION = 124;
DEVELOPMENT_TEAM = JND55328G8;
ENABLE_BITCODE = NO;
INFOPLIST_FILE = Runner/Info.plist;
@@ -702,7 +702,7 @@
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CURRENT_PROJECT_VERSION = 122;
CURRENT_PROJECT_VERSION = 124;
DEVELOPMENT_TEAM = JND55328G8;
ENABLE_BITCODE = NO;
INFOPLIST_FILE = Runner/Info.plist;

View File

@@ -43,7 +43,7 @@
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>122</string>
<string>124</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>ITSAppUsesNonExemptEncryption</key>

View File

@@ -5,22 +5,22 @@
<testcase classname="fastlane.lanes" name="0: default_platform" time="0.000217">
<testcase classname="fastlane.lanes" name="0: default_platform" time="0.00024">
</testcase>
<testcase classname="fastlane.lanes" name="1: increment_build_number" time="0.503497">
<testcase classname="fastlane.lanes" name="1: increment_build_number" time="1.144858">
</testcase>
<testcase classname="fastlane.lanes" name="2: build_app" time="103.12875">
<testcase classname="fastlane.lanes" name="2: build_app" time="98.142592">
</testcase>
<testcase classname="fastlane.lanes" name="3: upload_to_app_store" time="58490.472877">
<testcase classname="fastlane.lanes" name="3: upload_to_app_store" time="157.12775">
</testcase>

View File

@@ -372,6 +372,8 @@ class _MeshCoreSarAppState extends State<MeshCoreSarApp> {
mapProvider: mapProvider,
drawingProvider: context.read<DrawingProvider>(),
channelsProvider: context.read<ChannelsProvider>(),
voiceProvider: context.read<VoiceProvider>(),
imageProvider: context.read<ip.ImageProvider>(),
appProvider: appProvider,
),
),

View File

@@ -71,6 +71,7 @@ class DeviceInfo {
final bool? autoAddRoomServers;
final bool? autoAddSensors;
final bool? autoAddOverwriteOldest;
final int? autoAddMaxHops;
final int? radioFreq;
final int? radioBw;
final int? radioSf;
@@ -95,6 +96,7 @@ class DeviceInfo {
// Repeat mode (firmware v9+)
final bool? clientRepeat;
final int? pathHashMode;
final bool? supportsSpectrumScan;
final int? spectrumScanMinKhz;
final int? spectrumScanMaxKhz;
@@ -123,6 +125,7 @@ class DeviceInfo {
this.autoAddRoomServers,
this.autoAddSensors,
this.autoAddOverwriteOldest,
this.autoAddMaxHops,
this.radioFreq,
this.radioBw,
this.radioSf,
@@ -139,6 +142,7 @@ class DeviceInfo {
this.manufacturerModel,
this.semanticVersion,
this.clientRepeat,
this.pathHashMode,
this.supportsSpectrumScan,
this.spectrumScanMinKhz,
this.spectrumScanMaxKhz,
@@ -254,6 +258,7 @@ class DeviceInfo {
bool? autoAddRoomServers,
bool? autoAddSensors,
bool? autoAddOverwriteOldest,
int? autoAddMaxHops,
int? radioFreq,
int? radioBw,
int? radioSf,
@@ -270,6 +275,7 @@ class DeviceInfo {
String? manufacturerModel,
String? semanticVersion,
bool? clientRepeat,
int? pathHashMode,
bool? supportsSpectrumScan,
int? spectrumScanMinKhz,
int? spectrumScanMaxKhz,
@@ -299,6 +305,7 @@ class DeviceInfo {
autoAddSensors: autoAddSensors ?? this.autoAddSensors,
autoAddOverwriteOldest:
autoAddOverwriteOldest ?? this.autoAddOverwriteOldest,
autoAddMaxHops: autoAddMaxHops ?? this.autoAddMaxHops,
radioFreq: radioFreq ?? this.radioFreq,
radioBw: radioBw ?? this.radioBw,
radioSf: radioSf ?? this.radioSf,
@@ -315,6 +322,7 @@ class DeviceInfo {
manufacturerModel: manufacturerModel ?? this.manufacturerModel,
semanticVersion: semanticVersion ?? this.semanticVersion,
clientRepeat: clientRepeat ?? this.clientRepeat,
pathHashMode: pathHashMode ?? this.pathHashMode,
supportsSpectrumScan: supportsSpectrumScan ?? this.supportsSpectrumScan,
spectrumScanMinKhz: spectrumScanMinKhz ?? this.spectrumScanMinKhz,
spectrumScanMaxKhz: spectrumScanMaxKhz ?? this.spectrumScanMaxKhz,

View File

@@ -2553,12 +2553,10 @@ class AppProvider with ChangeNotifier {
try {
_isReconnectSyncInProgress = true;
_hasCompletedConnectionBootstrap = false;
// Initialize contacts provider with device public key to exclude self
// If already initialized (from early load), this will just filter out self-contact
// This must happen before getContacts to ensure proper filtering
await contactsProvider.initialize(
await contactsProvider.prepareForDeviceContactSync(
devicePublicKey: connectionProvider.deviceInfo.publicKey,
);
channelsProvider.prepareForDeviceSync();
// Note: Device clock is automatically synced during connection in MeshCoreBleService
// No need to sync it again here
@@ -2634,10 +2632,14 @@ class AppProvider with ChangeNotifier {
'🔄 [AppProvider] Device reconnected - syncing contacts and missed messages',
);
await contactsProvider.initialize(
await contactsProvider.prepareForDeviceContactSync(
devicePublicKey: connectionProvider.deviceInfo.publicKey,
);
channelsProvider.prepareForDeviceSync();
await connectionProvider.getContacts();
await connectionProvider.syncChannels(
maxChannels: connectionProvider.deviceInfo.maxChannels,
);
final messageCount = await connectionProvider.syncAllMessages(
force: true,
@@ -3642,6 +3644,7 @@ class AppProvider with ChangeNotifier {
await connectionProvider.getContacts();
// Sync all channels so refresh reflects the full device state.
channelsProvider.prepareForDeviceSync();
await connectionProvider.syncChannels(
maxChannels: connectionProvider.deviceInfo.maxChannels,
);

View File

@@ -7,7 +7,8 @@ class ChannelsProvider with ChangeNotifier {
int _selectedChannelIndex = 0; // Default to public channel
/// Get all channels
List<Channel> get channels => _channels.values.toList()..sort((a, b) => a.index.compareTo(b.index));
List<Channel> get channels =>
_channels.values.toList()..sort((a, b) => a.index.compareTo(b.index));
/// Get a specific channel by index
Channel? getChannel(int index) => _channels[index];
@@ -54,12 +55,12 @@ class ChannelsProvider with ChangeNotifier {
void removeChannel(int index) {
if (_channels.containsKey(index)) {
_channels.remove(index);
// If the deleted channel was selected, switch to public channel
if (_selectedChannelIndex == index) {
_selectedChannelIndex = 0;
}
notifyListeners();
}
}
@@ -96,6 +97,13 @@ class ChannelsProvider with ChangeNotifier {
notifyListeners();
}
/// Clear runtime channel state before a live device sync begins.
void prepareForDeviceSync() {
_channels.clear();
_selectedChannelIndex = 0;
notifyListeners();
}
/// Check if channels have been loaded
bool get hasChannels => _channels.isNotEmpty;

View File

@@ -547,6 +547,7 @@ class ConnectionProvider with ChangeNotifier {
manufacturerModel: deviceInfo['manufacturerModel'] as String?,
semanticVersion: deviceInfo['semanticVersion'] as String?,
clientRepeat: deviceInfo['clientRepeat'] as bool?,
pathHashMode: deviceInfo['pathHashMode'] as int?,
supportsSpectrumScan: deviceInfo['supportsSpectrumScan'] as bool?,
spectrumScanMinKhz: deviceInfo['spectrumScanMinKhz'] as int?,
spectrumScanMaxKhz: deviceInfo['spectrumScanMaxKhz'] as int?,
@@ -563,6 +564,9 @@ class ConnectionProvider with ChangeNotifier {
publicKey: selfInfo['publicKey'] as Uint8List?,
advLat: selfInfo['advLat'] as int?,
advLon: selfInfo['advLon'] as int?,
multiAcks: selfInfo['multiAcks'] as int?,
advertLocPolicy: selfInfo['advertLocPolicy'] as int?,
telemetryModes: selfInfo['telemetryModes'] as int?,
manualAddContacts: selfInfo['manualAddContacts'] as bool?,
radioFreq: selfInfo['radioFreq'] as int?,
radioBw: selfInfo['radioBw'] as int?,
@@ -605,6 +609,7 @@ class ConnectionProvider with ChangeNotifier {
autoAddRoomServers: config['autoAddRoomServers'] as bool?,
autoAddSensors: config['autoAddSensors'] as bool?,
autoAddOverwriteOldest: config['autoAddOverwriteOldest'] as bool?,
autoAddMaxHops: config['autoAddMaxHops'] as int?,
);
notifyListeners();
};
@@ -1853,11 +1858,13 @@ class ConnectionProvider with ChangeNotifier {
return pendingPing;
}
final future = _runSmartPing(
contactPublicKey: contactPublicKey,
hasPath: hasPath,
onRetryWithFlooding: onRetryWithFlooding,
);
final future = _isSelfPublicKey(contactPublicKey)
? _runSelfTelemetryPing(contactPublicKey)
: _runSmartPing(
contactPublicKey: contactPublicKey,
hasPath: hasPath,
onRetryWithFlooding: onRetryWithFlooding,
);
_pendingSmartPings[pingKey] = future;
notifyListeners();
@@ -1944,10 +1951,53 @@ class ConnectionProvider with ChangeNotifier {
}
}
Future<PingResult> _runSelfTelemetryPing(Uint8List devicePublicKey) async {
if (!_activeService.isConnected) {
_error = 'Not connected to device';
notifyListeners();
return PingResult(success: false, usedFlooding: false, timedOut: true);
}
try {
final pingFuture = _pingTracker.trackPing(
publicKey: devicePublicKey,
wasDirectAttempt: true,
);
// Firmware treats a 4-byte telemetry request as "self telemetry".
await _activeService.requestTelemetry(Uint8List(0), zeroHop: true);
final gotResponse = await pingFuture;
return PingResult(
success: gotResponse,
usedFlooding: false,
timedOut: !gotResponse,
);
} catch (e) {
_error = 'Failed to request self telemetry: $e';
notifyListeners();
return PingResult(success: false, usedFlooding: false, timedOut: true);
}
}
String _publicKeyToHex(Uint8List publicKey) {
return publicKey.map((b) => b.toRadixString(16).padLeft(2, '0')).join('');
}
bool _isSelfPublicKey(Uint8List publicKey) {
final selfKey = _deviceInfo.publicKey;
if (selfKey == null || selfKey.length != publicKey.length) {
return false;
}
for (var i = 0; i < publicKey.length; i++) {
if (selfKey[i] != publicKey[i]) {
return false;
}
}
return true;
}
/// Send binary request to contact (modern replacement for requestTelemetry)
///
/// Supports multiple request types:
@@ -2292,6 +2342,7 @@ class ConnectionProvider with ChangeNotifier {
autoAddRoomServers: config['autoAddRoomServers'] as bool?,
autoAddSensors: config['autoAddSensors'] as bool?,
autoAddOverwriteOldest: config['autoAddOverwriteOldest'] as bool?,
autoAddMaxHops: config['autoAddMaxHops'] as int?,
);
notifyListeners();
} catch (e) {
@@ -2303,6 +2354,7 @@ class ConnectionProvider with ChangeNotifier {
autoAddRoomServers: null,
autoAddSensors: null,
autoAddOverwriteOldest: null,
autoAddMaxHops: null,
);
notifyListeners();
return;
@@ -2322,6 +2374,7 @@ class ConnectionProvider with ChangeNotifier {
required bool autoAddRoomServers,
required bool autoAddSensors,
required bool overwriteOldest,
int maxHops = 0,
}) async {
if (!_activeService.isConnected) {
_error = 'Not connected to device';
@@ -2336,6 +2389,7 @@ class ConnectionProvider with ChangeNotifier {
autoAddRoomServers: autoAddRoomServers,
autoAddSensors: autoAddSensors,
overwriteOldest: overwriteOldest,
maxHops: maxHops,
);
_deviceInfo = _deviceInfo.copyWith(
autoAddUsers: autoAddUsers,
@@ -2343,6 +2397,7 @@ class ConnectionProvider with ChangeNotifier {
autoAddRoomServers: autoAddRoomServers,
autoAddSensors: autoAddSensors,
autoAddOverwriteOldest: overwriteOldest,
autoAddMaxHops: maxHops,
);
notifyListeners();
} catch (e) {
@@ -2351,6 +2406,23 @@ class ConnectionProvider with ChangeNotifier {
}
}
Future<void> setPathHashMode(int mode) async {
if (!_activeService.isConnected) {
_error = 'Not connected to device';
notifyListeners();
return;
}
try {
await _activeService.setPathHashMode(mode);
_deviceInfo = _deviceInfo.copyWith(pathHashMode: mode);
notifyListeners();
} catch (e) {
_error = 'Failed to set path hash mode: $e';
notifyListeners();
}
}
/// Export a contact as a meshcore:// share URL.
/// Pass null to export self.
Future<String?> exportContactUrl(Uint8List? publicKey) async {
@@ -2440,14 +2512,8 @@ class ConnectionProvider with ChangeNotifier {
Future<void> requestSelfTelemetry() async {
if (!_activeService.isConnected) return;
try {
// Request own telemetry by sending telemetry req with zero-length key
final deviceKey = _deviceInfo.publicKey;
if (deviceKey != null) {
await _activeService.requestTelemetry(
Uint8List.fromList(deviceKey),
zeroHop: true,
);
}
// Firmware expects a 4-byte CMD_SEND_TELEMETRY_REQ frame for "self".
await _activeService.requestTelemetry(Uint8List(0), zeroHop: true);
} catch (e) {
debugPrint('⚠️ [Provider] requestSelfTelemetry failed: $e');
}

View File

@@ -7,6 +7,7 @@ import '../models/contact_group.dart';
import '../models/message_contact_location.dart';
import '../services/cayenne_lpp_parser.dart';
import '../services/contact_storage_service.dart';
import '../services/profiles_feature_service.dart';
import '../utils/fast_gps_packet.dart';
import '../utils/rssi_location_estimator.dart';
import '../utils/key_comparison.dart';
@@ -126,11 +127,13 @@ class _RetainedRoute {
class ContactsProvider with ChangeNotifier {
static const double _firstHopFallbackOffsetMeters = 100.0;
static const String autoGroupIdPrefix = 'auto_group_';
static const String _rawTelemetryHexKey = '__raw_lpp_hex';
final Map<String, Contact> _contacts = {};
final List<SavedContactGroup> _savedContactGroups = <SavedContactGroup>[];
final Map<String, PendingAdvert> _pendingAdverts = {};
final Map<String, LatLng> _estimatedLocations = {};
final Map<String, List<RssiObservation>> _rssiObservations = {};
final Map<String, Contact> _retainedContactsForSync = {};
final ContactStorageService _storageService = ContactStorageService();
bool _isInitialized = false;
bool _isPersisting = false;
@@ -138,9 +141,12 @@ class ContactsProvider with ChangeNotifier {
bool _isPersistingPendingAdverts = false;
bool _persistPendingAdvertsRequested = false;
String? _storageNamespace;
String? _selfPublicKeyHex;
ContactTelemetry? _selfTelemetry;
// Add default public channel on initialization
ContactsProvider() {
ContactsProvider()
: _storageNamespace = ProfileStorageScope.effectiveNamespace {
_ensurePublicChannelExists();
}
@@ -160,6 +166,7 @@ class ContactsProvider with ChangeNotifier {
Uint8List? devicePublicKey,
}) async {
_storageNamespace = namespace;
_setSelfDevicePublicKey(devicePublicKey);
await _loadFromStorage(force: true, devicePublicKey: devicePublicKey);
}
@@ -251,6 +258,7 @@ class ContactsProvider with ChangeNotifier {
/// Initialize and load persisted contacts
/// [devicePublicKey] - device's own public key to exclude from loaded contacts
Future<void> initialize({Uint8List? devicePublicKey}) async {
_setSelfDevicePublicKey(devicePublicKey);
if (_isInitialized) {
// If already initialized (from early load), just filter out self-contact
if (devicePublicKey != null) {
@@ -265,6 +273,42 @@ class ContactsProvider with ChangeNotifier {
}
}
/// Clear runtime contact state before a live device contact sync begins.
///
/// This intentionally does not touch persisted storage. It keeps any saved
/// contact groups for the active profile, but removes stale in-memory device
/// contacts and discovery state so a newly connected device starts from an
/// empty list while sync is in progress.
Future<void> prepareForDeviceContactSync({Uint8List? devicePublicKey}) async {
_setSelfDevicePublicKey(devicePublicKey);
if (!_isInitialized) {
final storedGroups = await _storageService.loadContactGroups(
namespace: _storageNamespace,
);
_savedContactGroups
..clear()
..addAll(storedGroups);
_isInitialized = true;
}
debugPrint(
'🧹 [ContactsProvider] Clearing runtime contacts before device sync',
);
_retainedContactsForSync
..clear()
..addEntries(
_contactsForStorage().map(
(contact) => MapEntry(contact.publicKeyHex, contact),
),
);
_contacts.clear();
_pendingAdverts.clear();
_estimatedLocations.clear();
_rssiObservations.clear();
_ensurePublicChannelExists();
notifyListeners();
}
/// Remove self-contact from loaded contacts (called after BLE connection established)
void _removeSelfContact(Uint8List devicePublicKey) {
final selfKeyHex = devicePublicKey
@@ -345,6 +389,7 @@ class ContactsProvider with ChangeNotifier {
}
List<Contact> get contacts => _contacts.values.toList();
ContactTelemetry? get selfTelemetry => _selfTelemetry;
List<Contact> get favouriteContacts =>
_contacts.values.where((c) => c.isFavourite).toList();
List<SavedContactGroup> get savedContactGroups =>
@@ -535,9 +580,11 @@ class ContactsProvider with ChangeNotifier {
// Replace existing observation from the same repeater, or add new
final repeaterKey =
'${observation.repeaterLocation.latitude},${observation.repeaterLocation.longitude}';
observations.removeWhere((o) =>
'${o.repeaterLocation.latitude},${o.repeaterLocation.longitude}' ==
repeaterKey);
observations.removeWhere(
(o) =>
'${o.repeaterLocation.latitude},${o.repeaterLocation.longitude}' ==
repeaterKey,
);
observations.add(observation);
// Keep at most 8 observations (most recent per repeater)
@@ -637,7 +684,9 @@ class ContactsProvider with ChangeNotifier {
}
// Check if this is a new contact
final existingContact = _contacts[contact.publicKeyHex];
final existingContact =
_contacts[contact.publicKeyHex] ??
_retainedContactsForSync[contact.publicKeyHex];
final isNewContact = existingContact == null;
debugPrint(
' isNew: $isNewContact, total contacts before: ${_contacts.length}',
@@ -649,6 +698,7 @@ class ContactsProvider with ChangeNotifier {
);
_contacts[contact.publicKeyHex] = updatedContact;
_retainedContactsForSync.remove(contact.publicKeyHex);
// Keep repeaters and sensors in pending adverts so they remain visible
// in the discovery list (with a checkmark). Remove others.
if (contact.type != ContactType.repeater &&
@@ -678,11 +728,14 @@ class ContactsProvider with ChangeNotifier {
excluded++;
continue;
}
final existingContact = _contacts[contact.publicKeyHex];
final existingContact =
_contacts[contact.publicKeyHex] ??
_retainedContactsForSync[contact.publicKeyHex];
_contacts[contact.publicKeyHex] = _mergeIncomingContact(
incomingContact: contact,
existingContact: existingContact,
);
_retainedContactsForSync.remove(contact.publicKeyHex);
if (contact.type != ContactType.repeater &&
contact.type != ContactType.sensor) {
_pendingAdverts.remove(contact.publicKeyHex);
@@ -954,17 +1007,29 @@ class ContactsProvider with ChangeNotifier {
// Find contact by public key prefix
final contact = _findContactByPrefix(publicKeyPrefix);
if (contact == null) {
final isSelfTelemetry =
contact == null && _matchesSelfPrefix(publicKeyPrefix);
if (contact == null && !isSelfTelemetry) {
debugPrint(' ❌ Contact not found for this prefix');
return;
}
debugPrint(' ✅ Found contact: ${contact.advName}');
debugPrint(' Old telemetry timestamp: ${contact.telemetry?.timestamp}');
if (isSelfTelemetry) {
debugPrint(' ✅ Matched self telemetry response');
debugPrint(
' Old self telemetry timestamp: ${_selfTelemetry?.timestamp}',
);
} else {
debugPrint(' ✅ Found contact: ${contact!.advName}');
debugPrint(' Old telemetry timestamp: ${contact.telemetry?.timestamp}');
}
try {
// Parse Cayenne LPP data
var telemetry = CayenneLppParser.parse(lppData);
var telemetry = _withRawTelemetryHex(
CayenneLppParser.parse(lppData),
lppData,
);
debugPrint(' ✅ Parsed new telemetry');
debugPrint(' New telemetry timestamp: ${telemetry.timestamp}');
@@ -983,7 +1048,9 @@ class ContactsProvider with ChangeNotifier {
);
}
final previousTelemetry = contact.telemetry;
final previousTelemetry = isSelfTelemetry
? _selfTelemetry
: contact!.telemetry;
final mergedTelemetry = _mergeTelemetryForContact(
existingTelemetry: previousTelemetry,
@@ -1006,29 +1073,38 @@ class ContactsProvider with ChangeNotifier {
timestamp: mergedTelemetry.timestamp,
humidity: mergedTelemetry.humidity,
pressure: mergedTelemetry.pressure,
extraSensorData: telemetry.extraSensorData,
extraSensorData: mergedTelemetry.extraSensorData,
);
}
if (isSelfTelemetry) {
_selfTelemetry = telemetry;
notifyListeners();
debugPrint(' ✅ Updated self telemetry');
return;
}
final resolvedContact = contact!;
// Update contact with new telemetry AND last seen time
// lastAdvert is Unix timestamp in seconds
final currentTimestamp = (DateTime.now().millisecondsSinceEpoch / 1000)
.round();
debugPrint(' Old lastAdvert: ${contact.lastAdvert}');
debugPrint(' Old lastAdvert: ${resolvedContact.lastAdvert}');
debugPrint(' New lastAdvert: $currentTimestamp');
final persistedGps = _getValidGpsOrNull(telemetry.gpsLocation);
final updatedContact = contact.copyWith(
final updatedContact = resolvedContact.copyWith(
telemetry: telemetry,
lastAdvert: currentTimestamp, // Update last seen time
advLat: persistedGps != null
? _coordinateToAdvertMicrodegrees(persistedGps.latitude)
: contact.advLat,
: resolvedContact.advLat,
advLon: persistedGps != null
? _coordinateToAdvertMicrodegrees(persistedGps.longitude)
: contact.advLon,
: resolvedContact.advLon,
);
_contacts[contact.publicKeyHex] = updatedContact;
_contacts[resolvedContact.publicKeyHex] = updatedContact;
debugPrint(' ✅ Updated contact in map (with new lastAdvert)');
_persistContacts();
@@ -1146,6 +1222,28 @@ class ContactsProvider with ChangeNotifier {
);
}
ContactTelemetry _withRawTelemetryHex(
ContactTelemetry telemetry,
Uint8List lppData,
) {
final extraSensorData = <String, dynamic>{...?telemetry.extraSensorData};
extraSensorData[_rawTelemetryHexKey] = _bytesToHex(lppData);
return ContactTelemetry(
gpsLocation: telemetry.gpsLocation,
batteryPercentage: telemetry.batteryPercentage,
batteryMilliVolts: telemetry.batteryMilliVolts,
temperature: telemetry.temperature,
timestamp: telemetry.timestamp,
humidity: telemetry.humidity,
pressure: telemetry.pressure,
extraSensorData: extraSensorData,
);
}
String _bytesToHex(Uint8List bytes) {
return bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join(' ');
}
Map<String, dynamic> _mergeExtraSensorData(
Map<String, dynamic>? existingExtraSensorData,
Map<String, dynamic>? incomingExtraSensorData,
@@ -1235,6 +1333,36 @@ class ContactsProvider with ChangeNotifier {
return _contacts[keyHex];
}
void _setSelfDevicePublicKey(Uint8List? devicePublicKey) {
final nextKeyHex = _publicKeyHexOrNull(devicePublicKey);
if (_selfPublicKeyHex != nextKeyHex) {
_selfTelemetry = null;
}
_selfPublicKeyHex = nextKeyHex;
}
String? _publicKeyHexOrNull(Uint8List? publicKey) {
if (publicKey == null || publicKey.isEmpty) {
return null;
}
return publicKey.map((b) => b.toRadixString(16).padLeft(2, '0')).join('');
}
bool _matchesSelfPrefix(Uint8List prefix) {
final selfKeyHex = _selfPublicKeyHex;
if (selfKeyHex == null || prefix.isEmpty) {
return false;
}
final takeLen = prefix.length < 6 ? prefix.length : 6;
final prefixHex = prefix
.sublist(0, takeLen)
.map((b) => b.toRadixString(16).padLeft(2, '0'))
.join('');
return selfKeyHex.startsWith(prefixHex);
}
/// Clear a contact's learned path locally so the UI and next send both
/// prefer flood routing until the radio reports a fresh route.
void markPathUnhealthy(Uint8List publicKey) {
@@ -1532,6 +1660,7 @@ class ContactsProvider with ChangeNotifier {
void clearContacts() {
_contacts.clear();
_pendingAdverts.clear();
_retainedContactsForSync.clear();
_ensurePublicChannelExists();
_persistContacts();
_persistPendingAdverts();
@@ -1556,6 +1685,7 @@ class ContactsProvider with ChangeNotifier {
// Then remove from local storage
_contacts.remove(publicKeyHex);
_pendingAdverts.remove(publicKeyHex);
_retainedContactsForSync.remove(publicKeyHex);
_persistContacts();
_persistPendingAdverts();
notifyListeners();
@@ -1638,6 +1768,10 @@ class ContactsProvider with ChangeNotifier {
_contacts.clear();
_savedContactGroups.clear();
_pendingAdverts.clear();
_estimatedLocations.clear();
_rssiObservations.clear();
_retainedContactsForSync.clear();
_selfTelemetry = null;
}
Map<String, dynamic> _pendingAdvertToJson(PendingAdvert advert) {

View File

@@ -3,6 +3,7 @@ import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/contact.dart';
import '../services/profiles_feature_service.dart';
import 'helpers/raw_session_retransmit.dart';
import '../utils/image_message_parser.dart';
@@ -75,6 +76,8 @@ class ImageProvider with ChangeNotifier {
_restore();
}
String _scopedStorageKey() => ProfileStorageScope.scopedKey(_storageKey);
// ── Accessors ────────────────────────────────────────────────────────────
ImageSession? session(String sessionId) => _sessions[sessionId];
@@ -292,18 +295,22 @@ class ImageProvider with ChangeNotifier {
// ── Persistence ──────────────────────────────────────────────────────────
Future<void> clearAll() async {
_sessions.clear();
_outgoing.clear();
_ignoredIncomingSessions.clear();
_resetInMemoryState();
notifyListeners();
try {
final prefs = await SharedPreferences.getInstance();
await prefs.remove(_storageKey);
await prefs.remove(_scopedStorageKey());
} catch (e) {
debugPrint('❌ [ImageProvider] Failed to clear storage: $e');
}
}
Future<void> reloadProfileScopedState() async {
_resetInMemoryState();
await _restore();
notifyListeners();
}
void _evictExpiredOutgoing() {
final now = DateTime.now();
_outgoing.removeWhere((_, s) => now.difference(s.cachedAt) > _outgoingTtl);
@@ -343,7 +350,7 @@ class ImageProvider with ChangeNotifier {
)
.toList(),
};
await prefs.setString(_storageKey, jsonEncode(payload));
await prefs.setString(_scopedStorageKey(), jsonEncode(payload));
} catch (e) {
debugPrint('❌ [ImageProvider] Failed to persist: $e');
}
@@ -352,7 +359,7 @@ class ImageProvider with ChangeNotifier {
Future<void> _restore() async {
try {
final prefs = await SharedPreferences.getInstance();
final raw = prefs.getString(_storageKey);
final raw = prefs.getString(_scopedStorageKey());
if (raw == null || raw.isEmpty) return;
final parsed = jsonDecode(raw) as Map<String, dynamic>;
@@ -428,6 +435,12 @@ class ImageProvider with ChangeNotifier {
debugPrint('❌ [ImageProvider] Failed to restore: $e');
}
}
void _resetInMemoryState() {
_sessions.clear();
_outgoing.clear();
_ignoredIncomingSessions.clear();
}
}
class _OutgoingSession {

View File

@@ -737,8 +737,15 @@ class MessagesProvider with ChangeNotifier {
if (message.isContactMessage) {
// Match by sender key + sender timestamp (matches official app's DB
// uniqueness: contactPublicKey + senderTimestamp + text + txtType).
return existing.senderKeyShort == message.senderKeyShort &&
existing.senderTimestamp == message.senderTimestamp;
if (existing.senderKeyShort == message.senderKeyShort &&
existing.senderTimestamp == message.senderTimestamp) {
return true;
}
// Fallback dedup when retransmits surface as separate inbound rows
// without a stable timestamp/message id, but still carry the same
// visible sender identity and payload.
return _matchesDuplicateSenderIdentity(existing, message);
}
if (message.isChannelMessage) {
@@ -760,29 +767,29 @@ class MessagesProvider with ChangeNotifier {
return false;
}
final existingSenderKey = existing.senderKeyShort;
final incomingSenderKey = message.senderKeyShort;
if (existingSenderKey != null &&
incomingSenderKey != null &&
existingSenderKey == incomingSenderKey) {
return true;
}
final existingSenderName = _normalizedResolvedSenderName(existing);
final incomingSenderName = _normalizedResolvedSenderName(message);
if (existingSenderName != null &&
incomingSenderName != null &&
existingSenderName == incomingSenderName) {
return true;
}
return false;
return _matchesDuplicateSenderIdentity(existing, message);
}
// System messages and other types: never deduplicate by scope alone.
return false;
}
bool _matchesDuplicateSenderIdentity(Message existing, Message message) {
final existingSenderKey = existing.senderKeyShort;
final incomingSenderKey = message.senderKeyShort;
if (existingSenderKey != null &&
incomingSenderKey != null &&
existingSenderKey == incomingSenderKey) {
return true;
}
final existingSenderName = _normalizedResolvedSenderName(existing);
final incomingSenderName = _normalizedResolvedSenderName(message);
return existingSenderName != null &&
incomingSenderName != null &&
existingSenderName == incomingSenderName;
}
/// Add multiple messages
void addMessages(List<Message> messages) {
int addedCount = 0;

View File

@@ -14,6 +14,7 @@ enum SensorRefreshState { idle, refreshing, success, timeout, unavailable }
class SensorsProvider with ChangeNotifier {
static const Duration _successStateRetention = Duration(minutes: 1);
static const int selfAutoRefreshMinutes = 1;
static const String _watchedSensorsKey = 'watched_sensor_keys';
static const String _visibleSensorMetricsKey = 'visible_sensor_metrics';
static const String _fieldSpanKey = 'sensor_field_spans';
@@ -373,6 +374,20 @@ class SensorsProvider with ChangeNotifier {
return List<String>.unmodifiable(dueKeys);
}
bool _isRefreshDue(
String publicKeyHex, {
required int minutes,
required DateTime refreshTime,
}) {
if (minutes <= 0) {
return false;
}
final lastRefreshAt = _lastRefreshAttemptAt[publicKeyHex];
return lastRefreshAt == null ||
refreshTime.difference(lastRefreshAt) >= Duration(minutes: minutes);
}
Future<void> toggleMetric(
String publicKeyHex,
String fieldKey,
@@ -486,7 +501,14 @@ class SensorsProvider with ChangeNotifier {
final existing = contactsProvider.findContactByKey(
Uint8List.fromList(selfKey),
);
return existing ?? _buildSelfCandidate(connectionProvider);
final selfTelemetry = contactsProvider.selfTelemetry;
if (existing != null) {
return selfTelemetry == null
? existing
: existing.copyWith(telemetry: selfTelemetry);
}
return _buildSelfCandidate(connectionProvider, telemetry: selfTelemetry);
}
Future<void> addSensor(Contact contact) async {
@@ -564,6 +586,31 @@ class SensorsProvider with ChangeNotifier {
notifyListeners();
}
Future<void> reorderSensors(int oldIndex, int newIndex) async {
if (_watchedSensorKeys.length < 2) {
return;
}
if (oldIndex < 0 ||
oldIndex >= _watchedSensorKeys.length ||
newIndex < 0 ||
newIndex > _watchedSensorKeys.length) {
return;
}
var targetIndex = newIndex;
if (oldIndex < targetIndex) {
targetIndex -= 1;
}
if (oldIndex == targetIndex) {
return;
}
final movedKey = _watchedSensorKeys.removeAt(oldIndex);
_watchedSensorKeys.insert(targetIndex, movedKey);
await _persistWatchedSensors();
notifyListeners();
}
List<Contact> availableCandidates(
ContactsProvider contactsProvider, {
ConnectionProvider? connectionProvider,
@@ -604,6 +651,17 @@ class SensorsProvider with ChangeNotifier {
return <String>[self.publicKeyHex];
}
String? displaySelfKey({
required ContactsProvider contactsProvider,
required ConnectionProvider connectionProvider,
}) {
final self = selfContact(contactsProvider, connectionProvider);
if (self == null || _watchedSensorKeys.contains(self.publicKeyHex)) {
return null;
}
return self.publicKeyHex;
}
Contact? contactForDisplay(
String publicKeyHex, {
required ContactsProvider contactsProvider,
@@ -627,7 +685,18 @@ class SensorsProvider with ChangeNotifier {
required ContactsProvider contactsProvider,
required ConnectionProvider connectionProvider,
}) async {
if (_isRefreshingAll || _watchedSensorKeys.isEmpty) {
if (_isRefreshingAll) {
return;
}
final self = selfContact(contactsProvider, connectionProvider);
final keysToRefresh = <String>[
if (self != null) self.publicKeyHex,
..._watchedSensorKeys.where(
(key) => self == null || key != self.publicKeyHex,
),
];
if (keysToRefresh.isEmpty) {
return;
}
@@ -635,7 +704,7 @@ class SensorsProvider with ChangeNotifier {
notifyListeners();
try {
for (final key in _watchedSensorKeys) {
for (final key in keysToRefresh) {
await refreshSensor(
publicKeyHex: key,
contactsProvider: contactsProvider,
@@ -696,7 +765,17 @@ class SensorsProvider with ChangeNotifier {
}
final refreshTime = now ?? DateTime.now();
final dueKeys = dueAutoRefreshSensorKeys(now: refreshTime);
final dueKeys = dueAutoRefreshSensorKeys(now: refreshTime).toList();
final self = selfContact(contactsProvider, connectionProvider);
if (self != null &&
!dueKeys.contains(self.publicKeyHex) &&
_isRefreshDue(
self.publicKeyHex,
minutes: selfAutoRefreshMinutes,
refreshTime: refreshTime,
)) {
dueKeys.insert(0, self.publicKeyHex);
}
if (dueKeys.isEmpty) {
return;
}
@@ -748,7 +827,10 @@ class SensorsProvider with ChangeNotifier {
notifyListeners();
}
Contact? _buildSelfCandidate(ConnectionProvider connectionProvider) {
Contact? _buildSelfCandidate(
ConnectionProvider connectionProvider, {
ContactTelemetry? telemetry,
}) {
final deviceInfo = connectionProvider.deviceInfo;
final selfKey = deviceInfo.publicKey;
if (selfKey == null || selfKey.isEmpty) {
@@ -766,6 +848,7 @@ class SensorsProvider with ChangeNotifier {
advLat: deviceInfo.advLat ?? 0,
advLon: deviceInfo.advLon ?? 0,
lastMod: DateTime.now().millisecondsSinceEpoch ~/ 1000,
telemetry: telemetry,
);
}
}

View File

@@ -4,6 +4,7 @@ import 'dart:typed_data';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/contact.dart';
import '../services/profiles_feature_service.dart';
import 'helpers/raw_session_retransmit.dart';
import '../utils/voice_message_parser.dart';
import '../services/voice_codec_service.dart';
@@ -92,6 +93,9 @@ class VoiceProvider with ChangeNotifier {
_restorePersistedVoiceData();
}
String _storageKey() =>
ProfileStorageScope.scopedKey(_voiceSessionsStorageKey);
// ── Session accessors ────────────────────────────────────────────────────
VoiceSession? session(String sessionId) => _sessions[sessionId];
@@ -329,19 +333,22 @@ class VoiceProvider with ChangeNotifier {
}
Future<void> clearStoredVoiceData() async {
_sessions.clear();
_outgoingSessions.clear();
_ignoredIncomingSessions.clear();
_playingSessionId = null;
await _resetInMemoryState();
notifyListeners();
try {
final prefs = await SharedPreferences.getInstance();
await prefs.remove(_voiceSessionsStorageKey);
await prefs.remove(_storageKey());
} catch (e) {
debugPrint('❌ [VoiceProvider] Failed to clear stored voice data: $e');
}
}
Future<void> reloadProfileScopedState() async {
await _resetInMemoryState();
await _restorePersistedVoiceData();
notifyListeners();
}
Future<void> _persistVoiceData() async {
try {
final prefs = await SharedPreferences.getInstance();
@@ -365,7 +372,7 @@ class VoiceProvider with ChangeNotifier {
)
.toList(),
};
await prefs.setString(_voiceSessionsStorageKey, jsonEncode(payload));
await prefs.setString(_storageKey(), jsonEncode(payload));
} catch (e) {
debugPrint('❌ [VoiceProvider] Failed to persist voice data: $e');
}
@@ -374,7 +381,7 @@ class VoiceProvider with ChangeNotifier {
Future<void> _restorePersistedVoiceData() async {
try {
final prefs = await SharedPreferences.getInstance();
final raw = prefs.getString(_voiceSessionsStorageKey);
final raw = prefs.getString(_storageKey());
if (raw == null || raw.isEmpty) return;
final parsed = jsonDecode(raw) as Map<String, dynamic>;
@@ -437,6 +444,16 @@ class VoiceProvider with ChangeNotifier {
}
}
Future<void> _resetInMemoryState() async {
if (_playingSessionId != null || _player.isPlaying) {
await _player.stop();
}
_sessions.clear();
_outgoingSessions.clear();
_ignoredIncomingSessions.clear();
_playingSessionId = null;
}
@override
void dispose() {
_playerEventsSub.cancel();

View File

@@ -6,7 +6,9 @@ import '../providers/connection_provider.dart';
import '../l10n/app_localizations.dart';
class AddContactScreen extends StatefulWidget {
const AddContactScreen({super.key});
final String? initialAdvert;
const AddContactScreen({super.key, this.initialAdvert});
@override
State<AddContactScreen> createState() => _AddContactScreenState();
@@ -21,7 +23,12 @@ class _AddContactScreenState extends State<AddContactScreen> {
@override
void initState() {
super.initState();
_loadClipboardIfPresent();
if (widget.initialAdvert != null &&
widget.initialAdvert!.trim().isNotEmpty) {
_advertController.text = widget.initialAdvert!.trim();
} else {
_loadClipboardIfPresent();
}
}
@override
@@ -79,9 +86,9 @@ class _AddContactScreenState extends State<AddContactScreen> {
final text = clipboardData?.text;
if (text == null || text.trim().isEmpty) {
if (!mounted) return;
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(AppLocalizations.of(context)!.clipboardIsEmpty)));
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(AppLocalizations.of(context)!.clipboardIsEmpty)),
);
return;
}
@@ -140,9 +147,9 @@ class _AddContactScreenState extends State<AddContactScreen> {
return;
}
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(AppLocalizations.of(context)!.contactImported)));
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(AppLocalizations.of(context)!.contactImported)),
);
setState(() {
_importSucceeded = true;
});

View File

@@ -519,61 +519,58 @@ class _ContactsTabState extends State<ContactsTab> {
final canExportHashChannelPsk = Channel.isHashChannelName(
channel.advName.trim(),
);
showModalBottomSheet(
context: context,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
final actions = <_ChannelSheetAction>[
_ChannelSheetAction(
icon: Icons.message_outlined,
label: l10n.messages,
onTap: () async {
Navigator.pop(context);
await _openMessagesForChannel(context, channel);
},
),
builder: (sheetContext) => SafeArea(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ListTile(
leading: Icon(Icons.message_outlined),
title: Text(l10n.messages),
onTap: () async {
Navigator.pop(sheetContext);
await _openMessagesForChannel(context, channel);
},
),
if (channel.displayLocation != null)
ListTile(
leading: Icon(Icons.map_outlined),
title: Text(l10n.viewOnMap),
onTap: () {
Navigator.pop(sheetContext);
_showChannelOnMap(context, channel);
},
),
if (canExportHashChannelPsk)
ListTile(
leading: const Icon(Icons.key_outlined),
title: Text('${l10n.exportToClipboard} psk_base64'),
onTap: () async {
Navigator.pop(sheetContext);
await _exportHashChannelPskBase64(context, channel);
},
),
if (!channel.isPublicChannel)
ListTile(
leading: Icon(Icons.delete, color: Colors.red),
title: Text(
l10n.deleteChannel,
style: const TextStyle(color: Colors.red),
),
onTap: () async {
Navigator.pop(sheetContext);
await Future<void>.delayed(Duration.zero);
if (!context.mounted) return;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!context.mounted) return;
_showDeleteChannelDialog(context, channel);
});
},
),
],
if (channel.displayLocation != null)
_ChannelSheetAction(
icon: Icons.map_outlined,
label: l10n.viewOnMap,
onTap: () async {
Navigator.pop(context);
_showChannelOnMap(context, channel);
},
),
if (canExportHashChannelPsk)
_ChannelSheetAction(
icon: Icons.key_outlined,
label: '${l10n.exportToClipboard} psk_base64',
onTap: () async {
Navigator.pop(context);
await _exportHashChannelPskBase64(context, channel);
},
),
if (!channel.isPublicChannel)
_ChannelSheetAction(
icon: Icons.delete_outline_rounded,
label: l10n.deleteChannel,
destructive: true,
onTap: () async {
Navigator.pop(context);
await Future<void>.delayed(Duration.zero);
if (!context.mounted) return;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!context.mounted) return;
_showDeleteChannelDialog(context, channel);
});
},
),
];
showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (sheetContext) => _ChannelActionSheet(
channel: channel,
actions: actions,
onClose: () => Navigator.pop(sheetContext),
),
);
}
@@ -1980,6 +1977,302 @@ class _ExpandableParticipantStackState
}
}
class _ChannelSheetAction {
final IconData icon;
final String label;
final Future<void> Function() onTap;
final bool destructive;
const _ChannelSheetAction({
required this.icon,
required this.label,
required this.onTap,
this.destructive = false,
});
}
class _ChannelActionSheet extends StatelessWidget {
final Contact channel;
final List<_ChannelSheetAction> actions;
final VoidCallback onClose;
const _ChannelActionSheet({
required this.channel,
required this.actions,
required this.onClose,
});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
final l10n = AppLocalizations.of(context)!;
final title = channel.getLocalizedDisplayName(context);
final subtitle = channel.isPublicChannel
? l10n.broadcastToAllNearby
: '${l10n.channel} ${channel.publicKey[1]}';
final bottomInset = MediaQuery.of(context).viewPadding.bottom;
return Container(
constraints: BoxConstraints(
maxHeight: MediaQuery.of(context).size.height * 0.82,
),
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(
color: colorScheme.surface,
borderRadius: const BorderRadius.vertical(top: Radius.circular(32)),
boxShadow: [
BoxShadow(
color: colorScheme.shadow.withValues(alpha: 0.12),
blurRadius: 24,
offset: const Offset(0, -4),
),
],
),
child: Material(
color: colorScheme.surface,
child: SingleChildScrollView(
padding: EdgeInsets.fromLTRB(16, 12, 16, 16 + bottomInset),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Center(
child: Container(
width: 44,
height: 4,
decoration: BoxDecoration(
color: colorScheme.outlineVariant,
borderRadius: BorderRadius.circular(999),
),
),
),
const SizedBox(height: 12),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
DecoratedBox(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(24),
boxShadow: [
BoxShadow(
color: colorScheme.shadow.withValues(alpha: 0.08),
blurRadius: 12,
offset: const Offset(0, 4),
),
],
),
child: ContactAvatar(
contact: channel,
radius: 28,
displayName: title,
),
),
const SizedBox(width: 14),
Expanded(
child: Padding(
padding: const EdgeInsets.only(top: 2),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: theme.textTheme.titleLarge?.copyWith(
fontWeight: FontWeight.w900,
letterSpacing: -0.45,
),
),
const SizedBox(height: 4),
Text(
subtitle,
style: theme.textTheme.bodyMedium?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 10),
_ChannelSheetChip(
icon: channel.isPublicChannel
? Icons.broadcast_on_personal_rounded
: Icons.tag_rounded,
label: channel.isPublicChannel
? l10n.broadcastToAllNearby
: channel.publicKeyShort,
monospace: !channel.isPublicChannel,
),
],
),
),
),
const SizedBox(width: 8),
IconButton.filledTonal(
onPressed: onClose,
tooltip: l10n.close,
icon: const Icon(Icons.close_rounded),
),
],
),
if (actions.isNotEmpty) ...[
const SizedBox(height: 20),
LayoutBuilder(
builder: (context, constraints) {
const spacing = 12.0;
const minTileWidth = 132.0;
final actionCount = actions.length;
final maxColumnsByWidth =
((constraints.maxWidth + spacing) /
(minTileWidth + spacing))
.floor()
.clamp(1, 3);
var columnCount = actionCount.clamp(1, maxColumnsByWidth);
if (actionCount > 3 &&
columnCount > 2 &&
actionCount % columnCount == 1) {
columnCount -= 1;
}
final itemWidth =
(constraints.maxWidth - (spacing * (columnCount - 1))) /
columnCount;
return Wrap(
spacing: spacing,
runSpacing: spacing,
children: [
for (final action in actions)
SizedBox(
width: itemWidth,
child: _ChannelPrimaryActionButton(action: action),
),
],
);
},
),
],
],
),
),
),
);
}
}
class _ChannelPrimaryActionButton extends StatelessWidget {
final _ChannelSheetAction action;
const _ChannelPrimaryActionButton({required this.action});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
final accent = action.destructive ? colorScheme.error : colorScheme.primary;
final backgroundColor = action.destructive
? colorScheme.errorContainer.withValues(alpha: 0.82)
: Color.alphaBlend(
accent.withValues(alpha: 0.12),
colorScheme.surfaceContainerLow,
);
final foregroundColor = action.destructive
? colorScheme.onErrorContainer
: accent;
return Material(
color: Colors.transparent,
child: InkWell(
borderRadius: BorderRadius.circular(20),
onTap: action.onTap,
child: Ink(
height: 100,
decoration: BoxDecoration(
color: backgroundColor,
borderRadius: BorderRadius.circular(20),
border: Border.all(
color: action.destructive
? colorScheme.error.withValues(alpha: 0.18)
: accent.withValues(alpha: 0.14),
),
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
width: 30,
height: 30,
decoration: BoxDecoration(
color: foregroundColor.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(11),
),
child: Icon(action.icon, color: foregroundColor, size: 16),
),
const SizedBox(height: 6),
Text(
action.label,
maxLines: 2,
textAlign: TextAlign.center,
overflow: TextOverflow.ellipsis,
style: theme.textTheme.labelLarge?.copyWith(
color: action.destructive
? colorScheme.onErrorContainer
: colorScheme.onSurface,
fontWeight: FontWeight.w800,
letterSpacing: -0.2,
),
),
],
),
),
),
),
);
}
}
class _ChannelSheetChip extends StatelessWidget {
final IconData icon;
final String label;
final bool monospace;
const _ChannelSheetChip({
required this.icon,
required this.label,
this.monospace = false,
});
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
return Container(
constraints: const BoxConstraints(maxWidth: 260),
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
decoration: BoxDecoration(
color: colorScheme.surfaceContainerHigh,
borderRadius: BorderRadius.circular(999),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, size: 14, color: colorScheme.onSurfaceVariant),
const SizedBox(width: 6),
Flexible(
child: Text(
label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.labelMedium?.copyWith(
color: colorScheme.onSurfaceVariant,
fontWeight: FontWeight.w700,
fontFamily: monospace ? 'monospace' : null,
),
),
),
],
),
);
}
}
class _OverflowAvatar extends StatelessWidget {
final int count;

View File

@@ -178,12 +178,20 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
late TextEditingController _lonController;
late TextEditingController _freqController;
late TextEditingController _txPowerController;
late TextEditingController _gpsIntervalController;
late TextEditingController _autoAddMaxHopsController;
late final ConnectionProvider _connectionProvider;
bool _telemetryEnabled = false;
int _baseTelemetryMode = 0;
int _locationTelemetryMode = 0;
int _environmentTelemetryMode = 0;
int _advertLocationPolicy = 0;
bool _multiAcksEnabled = false;
bool _repeatEnabled = false;
bool? _gpsEnabled; // null = not supported by hardware
bool _gpsLoading = false;
bool _isSyncingDeviceTime = false;
int? _selectedPathHashMode;
bool _autoAddDiscoveredContactsEnabled = true;
bool _autoAddUsersEnabled = true;
bool _autoAddRepeatersEnabled = true;
@@ -250,6 +258,10 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
_txPowerController = TextEditingController(
text: deviceInfo.txPower?.toString() ?? '20',
);
_gpsIntervalController = TextEditingController();
_autoAddMaxHopsController = TextEditingController(
text: (deviceInfo.autoAddMaxHops ?? 0).toString(),
);
if (deviceInfo.radioBw != null &&
deviceInfo.radioBw! >= 0 &&
@@ -275,10 +287,17 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
);
_showCustomRadioSettings = _selectedRadioPreset == null;
// Check if telemetry is enabled (check if lat/lon are set and not zero)
_telemetryEnabled =
(deviceInfo.advLat != null && deviceInfo.advLat! != 0) ||
(deviceInfo.advLon != null && deviceInfo.advLon! != 0);
final telemetryModes = deviceInfo.telemetryModes;
_baseTelemetryMode = telemetryModes != null ? telemetryModes & 0x03 : 0;
_locationTelemetryMode = telemetryModes != null
? (telemetryModes >> 2) & 0x03
: 0;
_environmentTelemetryMode = telemetryModes != null
? (telemetryModes >> 4) & 0x03
: 0;
_advertLocationPolicy = deviceInfo.advertLocPolicy ?? 0;
_multiAcksEnabled = (deviceInfo.multiAcks ?? 0) != 0;
_selectedPathHashMode = deviceInfo.pathHashMode;
// Initialize repeat mode from device info (firmware v9+)
_repeatEnabled = deviceInfo.clientRepeat ?? false;
@@ -308,6 +327,8 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
_lonController.dispose();
_freqController.dispose();
_txPowerController.dispose();
_gpsIntervalController.dispose();
_autoAddMaxHopsController.dispose();
super.dispose();
}
@@ -428,6 +449,7 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
deviceInfo.autoAddRoomServers,
deviceInfo.autoAddSensors,
deviceInfo.autoAddOverwriteOldest,
deviceInfo.autoAddMaxHops,
].join('|');
}
@@ -467,22 +489,22 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
_autoAddRoomServersEnabled = deviceInfo.autoAddRoomServers ?? true;
_autoAddSensorsEnabled = deviceInfo.autoAddSensors ?? true;
_overwriteOldestAutoAddEnabled = deviceInfo.autoAddOverwriteOldest ?? false;
_autoAddMaxHopsController.text = (deviceInfo.autoAddMaxHops ?? 0)
.toString();
}
int _telemetryModesForSave(ConnectionProvider connectionProvider) {
final deviceInfo = connectionProvider.deviceInfo;
final telemetryEnabled =
(deviceInfo.advLat != null && deviceInfo.advLat != 0) ||
(deviceInfo.advLon != null && deviceInfo.advLon != 0);
return deviceInfo.telemetryModes ?? (telemetryEnabled ? 0x0A : 0x00);
int _telemetryModesForSave() {
return (_environmentTelemetryMode << 4) |
(_locationTelemetryMode << 2) |
_baseTelemetryMode;
}
int _advertLocationPolicyForSave(ConnectionProvider connectionProvider) {
final deviceInfo = connectionProvider.deviceInfo;
final telemetryEnabled =
(deviceInfo.advLat != null && deviceInfo.advLat != 0) ||
(deviceInfo.advLon != null && deviceInfo.advLon != 0);
return deviceInfo.advertLocPolicy ?? (telemetryEnabled ? 1 : 0);
int _advertLocationPolicyForSave() {
return _advertLocationPolicy;
}
int _multiAcksForSave() {
return _multiAcksEnabled ? 1 : 0;
}
Future<void> _savePublicInfo() async {
@@ -501,8 +523,24 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
await connectionProvider.setAdvertName(_nameController.text);
}
// Save position and telemetry settings
if (_telemetryEnabled) {
final gpsIntervalText = _gpsIntervalController.text.trim();
if (gpsIntervalText.isNotEmpty) {
final gpsInterval = int.tryParse(gpsIntervalText);
if (gpsInterval == null || gpsInterval < 0 || gpsInterval > 86400) {
if (mounted) {
setState(() {
_publicInfoError =
'GPS interval must be a whole number between 0 and 86400 seconds.';
_isSavingPublicInfo = false;
});
}
return;
}
await connectionProvider.setCustomVar('gps_interval', gpsIntervalText);
}
// Save stored coordinates only when the firmware advert policy uses prefs.
if (_advertLocationPolicy == 2) {
// Parse and validate coordinates
final latResult = validator.parseLatitude(_latController.text);
if (!latResult.isSuccess) {
@@ -530,27 +568,15 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
latitude: latResult.value!,
longitude: lonResult.value!,
);
// Set telemetry modes to "Allow All" (mode 2 for both base and location)
final telemetryModes = 0x0A; // binary: 00001010 (base=2, location=2)
await connectionProvider.setOtherParams(
manualAddContacts: _autoAddFilterModeFlag,
telemetryModes: telemetryModes,
advertLocationPolicy: 1,
);
} else {
// Clear position
await connectionProvider.setAdvertLatLon(latitude: 0.0, longitude: 0.0);
// Set telemetry modes to "Deny" (mode 0)
final telemetryModes = 0x00;
await connectionProvider.setOtherParams(
manualAddContacts: _autoAddFilterModeFlag,
telemetryModes: telemetryModes,
advertLocationPolicy: 0,
);
}
await connectionProvider.setOtherParams(
manualAddContacts: _autoAddFilterModeFlag,
telemetryModes: _telemetryModesForSave(),
advertLocationPolicy: _advertLocationPolicyForSave(),
multiAcks: _multiAcksForSave(),
);
// Refetch device info to update UI with new settings
await connectionProvider.refreshDeviceInfo();
@@ -625,6 +651,10 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
// Save TX power
await connectionProvider.setTxPower(txPowerResult.value!);
if (_selectedPathHashMode != null) {
await connectionProvider.setPathHashMode(_selectedPathHashMode!);
}
// Refetch device info to update UI with new settings
await connectionProvider.refreshDeviceInfo();
@@ -658,6 +688,8 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
_autoAddDiscoveredContactsEnabled && _autoAddSensorsEnabled;
final overwriteOldest =
_autoAddDiscoveredContactsEnabled && _overwriteOldestAutoAddEnabled;
final maxHopsText = _autoAddMaxHopsController.text.trim();
final maxHops = int.tryParse(maxHopsText);
setState(() {
_isSavingAutoDiscoverySettings = true;
@@ -666,18 +698,22 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
});
try {
if (maxHops == null || maxHops < 0 || maxHops > 64) {
throw Exception('Auto-add max hops must be between 0 and 64.');
}
await connectionProvider.setAutoaddConfig(
autoAddUsers: autoAddUsers,
autoAddRepeaters: autoAddRepeaters,
autoAddRoomServers: autoAddRoomServers,
autoAddSensors: autoAddSensors,
overwriteOldest: overwriteOldest,
maxHops: maxHops,
);
await connectionProvider.setOtherParams(
manualAddContacts: _autoAddFilterModeFlag,
telemetryModes: _telemetryModesForSave(connectionProvider),
advertLocationPolicy: _advertLocationPolicyForSave(connectionProvider),
multiAcks: connectionProvider.deviceInfo.multiAcks ?? 0,
telemetryModes: _telemetryModesForSave(),
advertLocationPolicy: _advertLocationPolicyForSave(),
multiAcks: _multiAcksForSave(),
);
await connectionProvider.getAutoaddConfig();
@@ -709,8 +745,12 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
final vars = await _connectionProvider.getCustomVars();
if (!mounted) return;
final gpsValue = vars['gps'];
final gpsIntervalValue = vars['gps_interval'];
setState(() {
_gpsEnabled = gpsValue != null ? gpsValue == '1' : null;
if (gpsIntervalValue != null) {
_gpsIntervalController.text = gpsIntervalValue;
}
});
} catch (_) {
// Device may not support custom vars (old firmware / no GPS hardware)
@@ -794,7 +834,10 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
setState(() {
_latController.text = position.latitude.toStringAsFixed(6);
_lonController.text = position.longitude.toStringAsFixed(6);
_telemetryEnabled = true;
_advertLocationPolicy = 2;
if (_locationTelemetryMode == 0) {
_locationTelemetryMode = 2;
}
});
if (mounted) {
@@ -823,6 +866,37 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
}
}
Future<void> _syncDeviceTime() async {
setState(() => _isSyncingDeviceTime = true);
try {
_connectionProvider.clearError();
await _connectionProvider.syncDeviceTime();
final syncError = _connectionProvider.error;
if (syncError != null) {
throw Exception(syncError);
}
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Device time synced to this phone.'),
backgroundColor: Colors.green,
),
);
} catch (e) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Failed to sync device time: $e'),
backgroundColor: Theme.of(context).colorScheme.error,
),
);
} finally {
if (mounted) {
setState(() => _isSyncingDeviceTime = false);
}
}
}
Future<void> _confirmFactoryReset() async {
final confirmed = await showDialog<bool>(
context: context,
@@ -1093,9 +1167,7 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
final deviceInfo = context.watch<ConnectionProvider>().deviceInfo;
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
final locationSet =
(deviceInfo.advLat != null && deviceInfo.advLat != 0) ||
(deviceInfo.advLon != null && deviceInfo.advLon != 0);
final locationSet = _advertLocationPolicy != 0;
return Scaffold(
appBar: AppBar(title: Text(AppLocalizations.of(context)!.settings)),
@@ -1173,6 +1245,130 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
),
),
SizedBox(height: 20),
_ConfigSectionCard(
title: 'Device info',
subtitle:
'Capabilities reported by the connected radio and maintenance tools.',
icon: Icons.info_outline_rounded,
child: LayoutBuilder(
builder: (context, constraints) {
final cardWidth = constraints.maxWidth > 420
? (constraints.maxWidth - 24) / 3
: (constraints.maxWidth - 12) / 2;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Wrap(
spacing: 12,
runSpacing: 12,
children: [
SizedBox(
width: cardWidth,
child: _StorageStat(
label: 'BLE PIN',
value: _formatBlePin(deviceInfo.blePin),
compact: true,
),
),
SizedBox(
width: cardWidth,
child: _StorageStat(
label: AppLocalizations.of(
context,
)!.maxContacts,
value:
deviceInfo.maxContacts?.toString() ??
AppLocalizations.of(context)!.unknown,
compact: true,
),
),
SizedBox(
width: cardWidth,
child: _StorageStat(
label: AppLocalizations.of(
context,
)!.maxChannels,
value:
deviceInfo.maxChannels?.toString() ??
AppLocalizations.of(context)!.unknown,
compact: true,
),
),
if (deviceInfo.pathHashMode != null)
SizedBox(
width: cardWidth,
child: _StorageStat(
label: 'Path hash',
value: _pathHashModeLabel(
deviceInfo.pathHashMode!,
),
compact: true,
),
),
],
),
const SizedBox(height: 16),
Container(
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
color: colorScheme.surfaceContainerLowest,
borderRadius: BorderRadius.circular(20),
border: Border.all(
color: colorScheme.outlineVariant,
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Clock maintenance',
style: theme.textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w800,
),
),
const SizedBox(height: 4),
Text(
'Refresh the radio clock if room logins or message timestamps look off.',
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 12),
SizedBox(
width: double.infinity,
child: OutlinedButton.icon(
onPressed: _isSyncingDeviceTime
? null
: _syncDeviceTime,
icon: _isSyncingDeviceTime
? const SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(
strokeWidth: 2,
),
)
: const Icon(Icons.schedule_rounded),
label: Text(
_isSyncingDeviceTime
? 'Syncing time...'
: 'Sync device time',
),
style: OutlinedButton.styleFrom(
minimumSize: const Size.fromHeight(46),
),
),
),
],
),
),
],
);
},
),
),
SizedBox(height: 20),
_ConfigSectionCard(
title: AppLocalizations.of(context)!.autoDiscovery,
subtitle:
@@ -1310,6 +1506,22 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
: null,
),
),
const SizedBox(height: 16),
TextField(
controller: _autoAddMaxHopsController,
onChanged: (_) => _markAutoDiscoverySettingsDirty(),
decoration: InputDecoration(
labelText: 'Auto-add max hops',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(20),
),
filled: true,
fillColor: colorScheme.surfaceContainerLowest,
helperText:
'0 means no limit. 1 keeps auto-add to direct neighbors only.',
),
keyboardType: TextInputType.number,
),
const SizedBox(height: 18),
if (_autoDiscoverySettingsError != null) ...[
Text(
@@ -1346,27 +1558,87 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_SettingHighlightCard(
icon: _telemetryEnabled
? Icons.travel_explore
: Icons.location_disabled,
title: AppLocalizations.of(
context,
)!.telemetryAndLocationSharing,
description: 'Share your location with nearby devices.',
accentColor: _telemetryEnabled
? colorScheme.primary
: colorScheme.onSurfaceVariant,
trailing: Switch(
value: _telemetryEnabled,
onChanged: (value) {
setState(() {
_telemetryEnabled = value;
_publicInfoSaved = false;
_publicInfoError = null;
});
},
),
_ConfigDropdownField(
label: 'Base telemetry',
value: _baseTelemetryMode,
items: const [
DropdownMenuItem(value: 0, child: Text('Deny')),
DropdownMenuItem(
value: 1,
child: Text('Use contact flags'),
),
DropdownMenuItem(value: 2, child: Text('Allow all')),
],
onChanged: (value) {
if (value == null) return;
setState(() {
_baseTelemetryMode = value;
_markPublicInfoDirty();
});
},
),
const SizedBox(height: 16),
_ConfigDropdownField(
label: 'Location telemetry',
value: _locationTelemetryMode,
items: const [
DropdownMenuItem(value: 0, child: Text('Deny')),
DropdownMenuItem(
value: 1,
child: Text('Use contact flags'),
),
DropdownMenuItem(value: 2, child: Text('Allow all')),
],
onChanged: (value) {
if (value == null) return;
setState(() {
_locationTelemetryMode = value;
_markPublicInfoDirty();
});
},
),
const SizedBox(height: 16),
_ConfigDropdownField(
label: 'Environmental telemetry',
value: _environmentTelemetryMode,
items: const [
DropdownMenuItem(value: 0, child: Text('Deny')),
DropdownMenuItem(
value: 1,
child: Text('Use contact flags'),
),
DropdownMenuItem(value: 2, child: Text('Allow all')),
],
onChanged: (value) {
if (value == null) return;
setState(() {
_environmentTelemetryMode = value;
_markPublicInfoDirty();
});
},
),
const SizedBox(height: 16),
_ConfigDropdownField(
label: 'GPS advert policy',
value: _advertLocationPolicy,
items: const [
DropdownMenuItem(value: 0, child: Text('Hidden')),
DropdownMenuItem(
value: 1,
child: Text('Share live GPS'),
),
DropdownMenuItem(
value: 2,
child: Text('Use saved coordinates'),
),
],
onChanged: (value) {
if (value == null) return;
setState(() {
_advertLocationPolicy = value;
_markPublicInfoDirty();
});
},
),
if (_gpsEnabled != null) ...[
const SizedBox(height: 12),
@@ -1392,6 +1664,43 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
),
),
],
const SizedBox(height: 16),
TextField(
controller: _gpsIntervalController,
onChanged: (_) => _markPublicInfoDirty(),
decoration: InputDecoration(
labelText: 'GPS interval (seconds)',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(20),
),
filled: true,
fillColor: colorScheme.surfaceContainerLowest,
helperText:
'Firmware supports 0-86400 seconds. Older builds may not report the current value back.',
),
keyboardType: TextInputType.number,
),
const SizedBox(height: 12),
_SettingHighlightCard(
icon: _multiAcksEnabled
? Icons.mark_email_read_outlined
: Icons.mark_email_unread_outlined,
title: 'Multi-ACK mode',
description:
'Ask the radio to request extra acknowledgements when the firmware supports it.',
accentColor: _multiAcksEnabled
? colorScheme.primary
: colorScheme.onSurfaceVariant,
trailing: Switch(
value: _multiAcksEnabled,
onChanged: (value) {
setState(() {
_multiAcksEnabled = value;
_markPublicInfoDirty();
});
},
),
),
const SizedBox(height: 18),
TextField(
controller: _nameController,
@@ -1407,7 +1716,7 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
'This is the name other devices will see on the mesh.',
),
),
if (_telemetryEnabled) ...[
if (_advertLocationPolicy == 2) ...[
const SizedBox(height: 16),
Container(
padding: const EdgeInsets.all(14),
@@ -1420,14 +1729,14 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Shared location',
'Saved coordinates',
style: theme.textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w800,
),
),
const SizedBox(height: 4),
Text(
'Set coordinates manually or use your current location.',
'These coordinates are used when advert policy is set to saved coordinates.',
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
),
@@ -1463,6 +1772,22 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
],
),
),
] else if (_advertLocationPolicy == 1) ...[
const SizedBox(height: 16),
Container(
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
color: colorScheme.surfaceContainerLow,
borderRadius: BorderRadius.circular(22),
border: Border.all(color: colorScheme.outlineVariant),
),
child: Text(
'The firmware will advertise the live GPS fix from the onboard sensor manager when available.',
style: theme.textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
),
],
const SizedBox(height: 18),
if (_publicInfoError != null) ...[
@@ -1708,6 +2033,45 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
),
keyboardType: TextInputType.number,
),
if (_selectedPathHashMode != null) ...[
const SizedBox(height: 16),
DropdownButtonFormField<int>(
key: ValueKey('path-hash-$_selectedPathHashMode'),
initialValue: _selectedPathHashMode,
decoration: InputDecoration(
labelText: 'Advert path hash size',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(20),
),
filled: true,
fillColor: colorScheme.surfaceContainerLowest,
helperText:
'Controls the low-level hash size used in adverts and flood paths.',
),
items: const [
DropdownMenuItem(
value: 0,
child: Text('1 byte (mode 0)'),
),
DropdownMenuItem(
value: 1,
child: Text('2 bytes (mode 1)'),
),
DropdownMenuItem(
value: 2,
child: Text('3 bytes (mode 2)'),
),
],
onChanged: (int? newValue) {
if (newValue != null) {
setState(() {
_selectedPathHashMode = newValue;
});
_markRadioSettingsDirty();
}
},
),
],
],
),
),
@@ -1914,6 +2278,26 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
}
return '$storageKb KB';
}
String _formatBlePin(int? blePin) {
if (blePin == null) {
return AppLocalizations.of(context)!.unknown;
}
return blePin.toString().padLeft(6, '0');
}
String _pathHashModeLabel(int mode) {
switch (mode) {
case 0:
return '1 byte';
case 1:
return '2 bytes';
case 2:
return '3 bytes';
default:
return 'Mode $mode';
}
}
}
class _ConfigHeroCard extends StatelessWidget {
@@ -2153,17 +2537,52 @@ class _ConfigSectionCard extends StatelessWidget {
}
}
class _ConfigDropdownField<T> extends StatelessWidget {
final String label;
final T value;
final List<DropdownMenuItem<T>> items;
final ValueChanged<T?> onChanged;
const _ConfigDropdownField({
required this.label,
required this.value,
required this.items,
required this.onChanged,
});
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
return DropdownButtonFormField<T>(
initialValue: value,
decoration: InputDecoration(
labelText: label,
border: OutlineInputBorder(borderRadius: BorderRadius.circular(20)),
filled: true,
fillColor: colorScheme.surfaceContainerLowest,
),
items: items,
onChanged: onChanged,
);
}
}
class _StorageStat extends StatelessWidget {
final String label;
final String value;
final bool compact;
const _StorageStat({required this.label, required this.value});
const _StorageStat({
required this.label,
required this.value,
this.compact = false,
});
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
return Container(
padding: const EdgeInsets.all(14),
padding: EdgeInsets.all(compact ? 12 : 14),
decoration: BoxDecoration(
color: colorScheme.surfaceContainerLowest,
borderRadius: BorderRadius.circular(20),
@@ -2177,14 +2596,16 @@ class _StorageStat extends StatelessWidget {
style: TextStyle(
fontWeight: FontWeight.w600,
color: colorScheme.onSurfaceVariant,
fontSize: compact ? 13 : null,
),
),
const SizedBox(height: 6),
SizedBox(height: compact ? 4 : 6),
Text(
value,
style: TextStyle(
fontWeight: FontWeight.w800,
color: colorScheme.onSurface,
fontSize: compact ? 17 : null,
),
),
],

View File

@@ -9,7 +9,7 @@ import '../providers/contacts_provider.dart';
import '../services/mesh_map_nodes_service.dart';
import '../widgets/compact_signal_indicator.dart' show SignalMetric;
enum _DiscoveryMenuAction { repeaters, sensors }
enum _DiscoveryListFilter { all, repeaters, sensors, others }
class DiscoveryScreen extends StatefulWidget {
const DiscoveryScreen({super.key});
@@ -23,7 +23,10 @@ class _DiscoveryScreenState extends State<DiscoveryScreen> {
static const int _sensorAdvertType = 4;
final Set<String> _resolvingAdvertKeys = <String>{};
final Set<int> _runningDiscoveryTypes = <int>{};
final TextEditingController _searchController = TextEditingController();
bool _isResolvingAll = false;
String _searchQuery = '';
_DiscoveryListFilter _selectedFilter = _DiscoveryListFilter.all;
late final Future<List<MeshMapNode>> _cachedNodesFuture;
@override
@@ -34,15 +37,10 @@ class _DiscoveryScreenState extends State<DiscoveryScreen> {
);
}
Future<void> _handleMenuAction(_DiscoveryMenuAction action) async {
switch (action) {
case _DiscoveryMenuAction.repeaters:
await _discoverNodeType(_repeaterAdvertType);
break;
case _DiscoveryMenuAction.sensors:
await _discoverNodeType(_sensorAdvertType);
break;
}
@override
void dispose() {
_searchController.dispose();
super.dispose();
}
Future<void> _clearAllDiscoveries() async {
@@ -80,7 +78,9 @@ class _DiscoveryScreenState extends State<DiscoveryScreen> {
return;
}
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(AppLocalizations.of(context)!.clearedPendingDiscoveries)),
SnackBar(
content: Text(AppLocalizations.of(context)!.clearedPendingDiscoveries),
),
);
}
@@ -293,8 +293,8 @@ class _DiscoveryScreenState extends State<DiscoveryScreen> {
};
}
String? _typeLabelForAdvert(PendingAdvert advert) {
return switch (advert.typeValue) {
String? _typeLabelForValue(int? typeValue) {
return switch (typeValue) {
_repeaterAdvertType => 'Repeater',
_sensorAdvertType => 'Sensor',
3 => 'Room',
@@ -303,22 +303,22 @@ class _DiscoveryScreenState extends State<DiscoveryScreen> {
};
}
String? _resolvedTypeLabelForAdvert(
int? _resolvedTypeValueForAdvert(
PendingAdvert advert,
List<MeshMapNode> cachedNodes,
) {
final directType = _typeLabelForAdvert(advert);
if (directType != null) {
final directType = advert.typeValue;
if (directType != null && directType != 0) {
return directType;
}
for (final node in cachedNodes) {
if (node.publicKey == advert.publicKeyHex.toLowerCase()) {
return switch (node.type) {
1 => 'Repeater',
4 => 'Sensor',
3 => 'Room',
2 => 'Chat',
1 => _repeaterAdvertType,
4 => _sensorAdvertType,
3 => 3,
2 => 1,
_ => null,
};
}
@@ -327,6 +327,81 @@ class _DiscoveryScreenState extends State<DiscoveryScreen> {
return null;
}
String? _resolvedTypeLabelForAdvert(
PendingAdvert advert,
List<MeshMapNode> cachedNodes,
) {
return _typeLabelForValue(_resolvedTypeValueForAdvert(advert, cachedNodes));
}
bool get _hasActiveInlineFilter =>
_searchQuery.trim().isNotEmpty ||
_selectedFilter != _DiscoveryListFilter.all;
bool _matchesSelectedFilter(
PendingAdvert advert,
List<MeshMapNode> cachedNodes,
) {
if (_selectedFilter == _DiscoveryListFilter.all) {
return true;
}
final resolvedType = _resolvedTypeValueForAdvert(advert, cachedNodes);
return switch (_selectedFilter) {
_DiscoveryListFilter.all => true,
_DiscoveryListFilter.repeaters => resolvedType == _repeaterAdvertType,
_DiscoveryListFilter.sensors => resolvedType == _sensorAdvertType,
_DiscoveryListFilter.others =>
resolvedType != _repeaterAdvertType &&
resolvedType != _sensorAdvertType,
};
}
bool _matchesSearchQuery(
PendingAdvert advert,
ContactsProvider contactsProvider,
List<MeshMapNode> cachedNodes,
) {
final query = _searchQuery.trim().toLowerCase();
if (query.isEmpty) {
return true;
}
final displayName = _displayNameForAdvert(
advert,
contactsProvider,
cachedNodes,
).toLowerCase();
final typeLabel = (_resolvedTypeLabelForAdvert(advert, cachedNodes) ?? '')
.toLowerCase();
return displayName.contains(query) ||
advert.publicKeyHex.toLowerCase().contains(query) ||
advert.shortDisplayKey.toLowerCase().contains(query) ||
typeLabel.contains(query);
}
List<PendingAdvert> _filteredPendingAdverts(
List<PendingAdvert> adverts,
ContactsProvider contactsProvider,
List<MeshMapNode> cachedNodes,
) {
return adverts
.where((advert) => _matchesSelectedFilter(advert, cachedNodes))
.where(
(advert) =>
_matchesSearchQuery(advert, contactsProvider, cachedNodes),
)
.toList();
}
String _summaryTitle({required int totalCount, required int filteredCount}) {
if (filteredCount == totalCount) {
return 'Discovered nodes ($totalCount)';
}
return 'Discovered nodes ($filteredCount/$totalCount)';
}
Widget _buildAdvertTitle(
BuildContext context, {
required String displayName,
@@ -362,193 +437,236 @@ class _DiscoveryScreenState extends State<DiscoveryScreen> {
final l10n = AppLocalizations.of(context)!;
return Scaffold(
appBar: AppBar(
title: Text(l10n.discovery),
actions: [
Consumer<ConnectionProvider>(
builder: (context, connectionProvider, child) {
final isConnected = connectionProvider.deviceInfo.isConnected;
final repeatersBusy = _runningDiscoveryTypes.contains(
_repeaterAdvertType,
);
final sensorsBusy = _runningDiscoveryTypes.contains(
_sensorAdvertType,
);
return PopupMenuButton<_DiscoveryMenuAction>(
tooltip: 'Discovery tools',
onSelected: _handleMenuAction,
itemBuilder: (context) => [
PopupMenuItem<_DiscoveryMenuAction>(
value: _DiscoveryMenuAction.repeaters,
enabled: isConnected && !repeatersBusy,
child: Row(
children: [
repeatersBusy
? const SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(
strokeWidth: 2,
),
)
: const Icon(Icons.router_outlined),
SizedBox(width: 12),
Text(l10n.discoverRepeaters),
],
),
),
PopupMenuItem<_DiscoveryMenuAction>(
value: _DiscoveryMenuAction.sensors,
enabled: isConnected && !sensorsBusy,
child: Row(
children: [
sensorsBusy
? const SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(
strokeWidth: 2,
),
)
: const Icon(Icons.sensors_outlined),
SizedBox(width: 12),
Text(l10n.discoverSensors),
],
),
),
],
);
},
),
],
),
appBar: AppBar(title: Text(l10n.discovery)),
body: FutureBuilder<List<MeshMapNode>>(
future: _cachedNodesFuture,
builder: (context, nodesSnapshot) => Consumer2<ContactsProvider, ConnectionProvider>(
builder: (context, contactsProvider, connectionProvider, child) {
final pendingAdverts = contactsProvider.pendingAdverts;
final isConnected = connectionProvider.deviceInfo.isConnected;
final cachedNodes = nodesSnapshot.data ?? const <MeshMapNode>[];
builder: (context, nodesSnapshot) =>
Consumer2<ContactsProvider, ConnectionProvider>(
builder: (context, contactsProvider, connectionProvider, child) {
final pendingAdverts = contactsProvider.pendingAdverts;
final isConnected = connectionProvider.deviceInfo.isConnected;
final cachedNodes = nodesSnapshot.data ?? const <MeshMapNode>[];
final repeatersBusy = _runningDiscoveryTypes.contains(
_repeaterAdvertType,
);
final sensorsBusy = _runningDiscoveryTypes.contains(
_sensorAdvertType,
);
// Track which pending adverts are already in the contacts list
final resolvedKeySet = <String>{};
for (final advert in pendingAdverts) {
if (contactsProvider.findContactByKey(advert.publicKey) != null) {
resolvedKeySet.add(advert.publicKeyHex);
}
}
// Track which pending adverts are already in the contacts list
final resolvedKeySet = <String>{};
for (final advert in pendingAdverts) {
if (contactsProvider.findContactByKey(advert.publicKey) !=
null) {
resolvedKeySet.add(advert.publicKeyHex);
}
}
final totalCount = pendingAdverts.length;
final totalCount = pendingAdverts.length;
final filteredAdverts = _filteredPendingAdverts(
pendingAdverts,
contactsProvider,
cachedNodes,
);
final filteredCount = filteredAdverts.length;
return ListView(
padding: const EdgeInsets.all(16),
children: [
Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.center,
return ListView(
padding: const EdgeInsets.all(16),
children: [
Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Icon(Icons.person_search),
const SizedBox(width: 12),
Expanded(
child: Text(
'Discovered nodes ($totalCount)',
style: Theme.of(context).textTheme.titleMedium,
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const Icon(Icons.person_search),
const SizedBox(width: 12),
Expanded(
child: Text(
_summaryTitle(
totalCount: totalCount,
filteredCount: filteredCount,
),
style: Theme.of(
context,
).textTheme.titleMedium,
),
),
],
),
const SizedBox(height: 12),
Text(
'Resolve entries manually so they do not auto-populate contacts.',
style: Theme.of(context).textTheme.bodyMedium,
),
if (totalCount > 0) ...[
const SizedBox(height: 12),
_buildInlineSearchField(context),
const SizedBox(height: 10),
Wrap(
spacing: 8,
runSpacing: 8,
children: [
_buildTypeFilterChip(
context,
label: l10n.all,
filter: _DiscoveryListFilter.all,
),
_buildTypeFilterChip(
context,
label: l10n.repeatersFilter,
filter: _DiscoveryListFilter.repeaters,
),
_buildTypeFilterChip(
context,
label: l10n.sensors,
filter: _DiscoveryListFilter.sensors,
),
_buildTypeFilterChip(
context,
label: l10n.others,
filter: _DiscoveryListFilter.others,
),
],
),
],
const SizedBox(height: 14),
LayoutBuilder(
builder: (context, constraints) {
const spacing = 10.0;
final useTwoColumns =
constraints.maxWidth >= 360;
final buttonWidth = useTwoColumns
? (constraints.maxWidth - spacing) / 2
: constraints.maxWidth;
return Wrap(
spacing: spacing,
runSpacing: spacing,
children: [
_buildHeaderActionButton(
width: buttonWidth,
onPressed: isConnected && !repeatersBusy
? () => _discoverNodeType(
_repeaterAdvertType,
)
: null,
icon: repeatersBusy
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(
strokeWidth: 2,
),
)
: const Icon(Icons.router_outlined),
label: Text(l10n.discoverRepeaters),
),
_buildHeaderActionButton(
width: buttonWidth,
onPressed: isConnected && !sensorsBusy
? () => _discoverNodeType(
_sensorAdvertType,
)
: null,
icon: sensorsBusy
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(
strokeWidth: 2,
),
)
: const Icon(Icons.sensors_outlined),
label: Text(l10n.discoverSensors),
),
_buildHeaderActionButton(
width: buttonWidth,
onPressed:
isConnected &&
pendingAdverts.isNotEmpty &&
!_isResolvingAll
? () => _resolveAll(pendingAdverts)
: null,
icon: _isResolvingAll
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(
strokeWidth: 2,
),
)
: const Icon(
Icons
.download_for_offline_outlined,
),
label: Text(l10n.resolveAll),
),
_buildHeaderActionButton(
width: buttonWidth,
onPressed: pendingAdverts.isNotEmpty
? _clearAllDiscoveries
: null,
icon: const Icon(Icons.clear_all_rounded),
label: Text(l10n.clearAllLabel),
),
],
);
},
),
],
),
const SizedBox(height: 12),
Text(
'Resolve entries manually so they do not auto-populate contacts.',
style: Theme.of(context).textTheme.bodyMedium,
),
const SizedBox(height: 14),
Row(
),
),
const SizedBox(height: 16),
if (totalCount == 0)
Padding(
padding: const EdgeInsets.symmetric(vertical: 48),
child: Column(
children: [
Expanded(
child: OutlinedButton.icon(
onPressed:
isConnected &&
pendingAdverts.isNotEmpty &&
!_isResolvingAll
? () => _resolveAll(pendingAdverts)
: null,
icon: _isResolvingAll
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(
strokeWidth: 2,
),
)
: const Icon(
Icons.download_for_offline_outlined,
),
label: Text(l10n.resolveAll),
),
Icon(
Icons.person_search_outlined,
size: 64,
color: Theme.of(context).disabledColor,
),
const SizedBox(width: 10),
Expanded(
child: OutlinedButton.icon(
onPressed: pendingAdverts.isNotEmpty
? _clearAllDiscoveries
: null,
icon: Icon(Icons.clear_all_rounded),
label: Text(l10n.clearAllLabel),
),
const SizedBox(height: 16),
Text(
'No discovered nodes',
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(height: 8),
Text(
'Use the discovery actions above to find repeaters and sensors on the mesh.',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodyMedium,
),
],
),
],
),
if (_hasActiveInlineFilter &&
totalCount > 0 &&
filteredCount == 0)
_buildNoFilterResults(context),
...filteredAdverts.map(
(advert) => _buildPendingAdvertCard(
context,
advert: advert,
contactsProvider: contactsProvider,
isConnected: isConnected,
isResolved: resolvedKeySet.contains(
advert.publicKeyHex,
),
cachedNodes: cachedNodes,
l10n: l10n,
),
),
),
),
const SizedBox(height: 16),
if (totalCount == 0)
Padding(
padding: const EdgeInsets.symmetric(vertical: 48),
child: Column(
children: [
Icon(
Icons.person_search_outlined,
size: 64,
color: Theme.of(context).disabledColor,
),
const SizedBox(height: 16),
Text(
'No discovered nodes',
style: Theme.of(context).textTheme.titleLarge,
),
const SizedBox(height: 8),
Text(
'Use the menu to discover repeaters and sensors on the mesh.',
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodyMedium,
),
],
),
),
...pendingAdverts.map((advert) =>
_buildPendingAdvertCard(
context,
advert: advert,
contactsProvider: contactsProvider,
isConnected: isConnected,
isResolved: resolvedKeySet.contains(advert.publicKeyHex),
cachedNodes: cachedNodes,
l10n: l10n,
),
),
],
);
},
),
],
);
},
),
),
);
}
@@ -563,7 +681,11 @@ class _DiscoveryScreenState extends State<DiscoveryScreen> {
required AppLocalizations l10n,
}) {
final isResolving = _resolvingAdvertKeys.contains(advert.publicKeyHex);
final displayName = _displayNameForAdvert(advert, contactsProvider, cachedNodes);
final displayName = _displayNameForAdvert(
advert,
contactsProvider,
cachedNodes,
);
final typeLabel = _resolvedTypeLabelForAdvert(advert, cachedNodes);
final downMetric = SignalMetric.fromValues(
rssiDbm: advert.rxRssiDbm,
@@ -652,6 +774,180 @@ class _DiscoveryScreenState extends State<DiscoveryScreen> {
);
}
Widget _buildInlineSearchField(BuildContext context) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
final hasFilter = _searchQuery.trim().isNotEmpty;
return Material(
color: Colors.transparent,
child: Ink(
decoration: BoxDecoration(
color: colorScheme.surface,
borderRadius: BorderRadius.circular(16),
border: Border.all(
color: hasFilter
? colorScheme.primary.withValues(alpha: 0.38)
: colorScheme.outline.withValues(alpha: 0.32),
width: 1.2,
),
boxShadow: [
BoxShadow(
color: colorScheme.shadow.withValues(alpha: 0.025),
blurRadius: 8,
offset: const Offset(0, 2),
),
],
),
child: ClipRRect(
borderRadius: BorderRadius.circular(16),
child: SizedBox(
height: 42,
child: Row(
children: [
Padding(
padding: const EdgeInsets.only(left: 12, right: 8),
child: Icon(
Icons.search_rounded,
size: 17,
color: hasFilter
? colorScheme.primary
: colorScheme.onSurfaceVariant,
),
),
Expanded(
child: TextField(
controller: _searchController,
onChanged: (value) {
setState(() {
_searchQuery = value;
});
},
cursorColor: colorScheme.primary,
style: theme.textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w600,
height: 1.1,
),
decoration: InputDecoration(
hintText: 'Search discovered nodes',
hintStyle: theme.textTheme.bodyMedium?.copyWith(
color: colorScheme.onSurfaceVariant.withValues(
alpha: 0.85,
),
),
filled: true,
fillColor: Colors.transparent,
border: InputBorder.none,
enabledBorder: InputBorder.none,
focusedBorder: InputBorder.none,
disabledBorder: InputBorder.none,
isDense: true,
contentPadding: const EdgeInsets.symmetric(vertical: 10),
),
),
),
if (hasFilter)
Padding(
padding: const EdgeInsets.only(right: 6),
child: Material(
color: colorScheme.primary.withValues(alpha: 0.10),
shape: const CircleBorder(),
child: InkWell(
customBorder: const CircleBorder(),
onTap: () {
_searchController.clear();
setState(() {
_searchQuery = '';
});
},
child: Padding(
padding: const EdgeInsets.all(6),
child: Icon(
Icons.close_rounded,
size: 14,
color: colorScheme.primary,
),
),
),
),
),
],
),
),
),
),
);
}
Widget _buildTypeFilterChip(
BuildContext context, {
required String label,
required _DiscoveryListFilter filter,
}) {
final scheme = Theme.of(context).colorScheme;
final selected = _selectedFilter == filter;
final color = selected ? scheme.primary : scheme.outline;
return InkWell(
onTap: () {
if (_selectedFilter == filter) {
return;
}
setState(() {
_selectedFilter = filter;
});
},
borderRadius: BorderRadius.circular(999),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
decoration: BoxDecoration(
color: color.withValues(alpha: selected ? 0.14 : 0.08),
borderRadius: BorderRadius.circular(999),
border: Border.all(
color: color.withValues(alpha: selected ? 0.45 : 0.22),
),
),
child: Text(
label,
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w700,
color: color,
),
),
),
);
}
Widget _buildNoFilterResults(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 24),
child: Text(
'No matches',
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
textAlign: TextAlign.center,
),
);
}
Widget _buildHeaderActionButton({
required double width,
required VoidCallback? onPressed,
required Widget icon,
required Widget label,
}) {
return SizedBox(
width: width,
child: OutlinedButton.icon(
onPressed: onPressed,
icon: icon,
label: label,
),
);
}
Widget _buildSignalSummary(
BuildContext context, {
SignalMetric? downMetric,

View File

@@ -8,7 +8,6 @@ import 'package:shared_preferences/shared_preferences.dart';
import 'package:vibration/vibration.dart';
import '../providers/connection_provider.dart';
import '../providers/app_provider.dart';
import '../models/contact.dart';
import '../models/device_info.dart' show ConnectionMode, DeviceInfo;
import '../providers/messages_provider.dart';
import '../providers/contacts_provider.dart';
@@ -439,133 +438,129 @@ class _HomeScreenState extends State<HomeScreen>
// Request self telemetry so it's fresh
context.read<ConnectionProvider>().requestSelfTelemetry();
// Find the device's own contact to show self telemetry
final selfKey = deviceInfo.publicKey;
Contact? selfContact;
if (selfKey != null) {
selfContact = context.read<ContactsProvider>().findContactByKey(
Uint8List.fromList(selfKey),
);
}
final telemetry = selfContact?.telemetry;
showModalBottomSheet(
context: context,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
),
builder: (context) => SafeArea(
child: Padding(
padding: const EdgeInsets.all(20),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 40,
height: 4,
decoration: BoxDecoration(
color: Theme.of(context).dividerColor,
borderRadius: BorderRadius.circular(2),
),
builder: (context) => Consumer<ContactsProvider>(
builder: (context, contactsProvider, child) {
final telemetry = contactsProvider.selfTelemetry;
return SafeArea(
child: Padding(
padding: const EdgeInsets.all(20),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 40,
height: 4,
decoration: BoxDecoration(
color: Theme.of(context).dividerColor,
borderRadius: BorderRadius.circular(2),
),
),
const SizedBox(height: 16),
Text(
deviceInfo.selfName ?? deviceInfo.deviceName ?? 'Device',
style: Theme.of(context).textTheme.titleMedium,
),
const SizedBox(height: 16),
_deviceInfoRow(
context,
Icons.bluetooth,
'BLE Signal',
deviceInfo.signalRssi != null
? '${deviceInfo.signalRssi} dBm'
: 'N/A',
),
if (deviceInfo.batteryPercent != null)
_deviceInfoRow(
context,
BatteryDisplayHelper.getBatteryIcon(
deviceInfo.batteryPercent!,
),
'Battery',
'${deviceInfo.batteryPercent!.round()}%',
),
if (deviceInfo.batteryMilliVolts != null)
_deviceInfoRow(
context,
Icons.bolt,
'Voltage',
'${(deviceInfo.batteryMilliVolts! / 1000).toStringAsFixed(2)}V',
),
if (deviceInfo.storageUsedKb != null &&
deviceInfo.storageTotalKb != null)
_deviceInfoRow(
context,
Icons.storage,
'Storage',
'${deviceInfo.storageUsedKb} / ${deviceInfo.storageTotalKb} KB',
),
if (deviceInfo.firmwareVersion != null)
_deviceInfoRow(
context,
Icons.system_update,
'Firmware',
'v${deviceInfo.firmwareVersion}',
),
if (deviceInfo.radioFreq != null)
_deviceInfoRow(
context,
Icons.radio,
'Frequency',
'${(deviceInfo.radioFreq! / 1000).toStringAsFixed(3)} MHz',
),
if (deviceInfo.txPower != null)
_deviceInfoRow(
context,
Icons.power,
'TX Power',
'${deviceInfo.txPower} dBm',
),
if (telemetry != null) ...[
const Divider(height: 24),
Text(
'Self Telemetry',
style: Theme.of(context).textTheme.titleSmall,
),
const SizedBox(height: 8),
if (telemetry.temperature != null)
_deviceInfoRow(
context,
Icons.thermostat,
'Temperature',
'${telemetry.temperature!.toStringAsFixed(1)}°C',
),
if (telemetry.humidity != null)
_deviceInfoRow(
context,
Icons.water_drop,
'Humidity',
'${telemetry.humidity!.toStringAsFixed(1)}%',
),
if (telemetry.pressure != null)
_deviceInfoRow(
context,
Icons.compress,
'Pressure',
'${telemetry.pressure!.toStringAsFixed(1)} hPa',
),
if (telemetry.gpsLocation != null)
_deviceInfoRow(
context,
Icons.gps_fixed,
'GPS',
'${telemetry.gpsLocation!.latitude.toStringAsFixed(5)}, ${telemetry.gpsLocation!.longitude.toStringAsFixed(5)}',
),
],
],
),
const SizedBox(height: 16),
Text(
deviceInfo.selfName ?? deviceInfo.deviceName ?? 'Device',
style: Theme.of(context).textTheme.titleMedium,
),
const SizedBox(height: 16),
_deviceInfoRow(
context,
Icons.bluetooth,
'BLE Signal',
deviceInfo.signalRssi != null
? '${deviceInfo.signalRssi} dBm'
: 'N/A',
),
if (deviceInfo.batteryPercent != null)
_deviceInfoRow(
context,
BatteryDisplayHelper.getBatteryIcon(
deviceInfo.batteryPercent!,
),
'Battery',
'${deviceInfo.batteryPercent!.round()}%',
),
if (deviceInfo.batteryMilliVolts != null)
_deviceInfoRow(
context,
Icons.bolt,
'Voltage',
'${(deviceInfo.batteryMilliVolts! / 1000).toStringAsFixed(2)}V',
),
if (deviceInfo.storageUsedKb != null &&
deviceInfo.storageTotalKb != null)
_deviceInfoRow(
context,
Icons.storage,
'Storage',
'${deviceInfo.storageUsedKb} / ${deviceInfo.storageTotalKb} KB',
),
if (deviceInfo.firmwareVersion != null)
_deviceInfoRow(
context,
Icons.system_update,
'Firmware',
'v${deviceInfo.firmwareVersion}',
),
if (deviceInfo.radioFreq != null)
_deviceInfoRow(
context,
Icons.radio,
'Frequency',
'${(deviceInfo.radioFreq! / 1000).toStringAsFixed(3)} MHz',
),
if (deviceInfo.txPower != null)
_deviceInfoRow(
context,
Icons.power,
'TX Power',
'${deviceInfo.txPower} dBm',
),
if (telemetry != null) ...[
const Divider(height: 24),
Text(
'Self Telemetry',
style: Theme.of(context).textTheme.titleSmall,
),
const SizedBox(height: 8),
if (telemetry.temperature != null)
_deviceInfoRow(
context,
Icons.thermostat,
'Temperature',
'${telemetry.temperature!.toStringAsFixed(1)}°C',
),
if (telemetry.humidity != null)
_deviceInfoRow(
context,
Icons.water_drop,
'Humidity',
'${telemetry.humidity!.toStringAsFixed(1)}%',
),
if (telemetry.pressure != null)
_deviceInfoRow(
context,
Icons.compress,
'Pressure',
'${telemetry.pressure!.toStringAsFixed(1)} hPa',
),
if (telemetry.gpsLocation != null)
_deviceInfoRow(
context,
Icons.gps_fixed,
'GPS',
'${telemetry.gpsLocation!.latitude.toStringAsFixed(5)}, ${telemetry.gpsLocation!.longitude.toStringAsFixed(5)}',
),
],
],
),
),
),
);
},
),
);
}
@@ -587,9 +582,9 @@ class _HomeScreenState extends State<HomeScreen>
),
Text(
value,
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w600,
),
style: Theme.of(
context,
).textTheme.bodyMedium?.copyWith(fontWeight: FontWeight.w600),
),
],
),
@@ -1224,58 +1219,56 @@ class _HomeScreenState extends State<HomeScreen>
),
const SizedBox(height: 2),
GestureDetector(
onTap: () => _showDeviceInfoSheet(
context,
deviceInfo,
),
onTap: () =>
_showDeviceInfoSheet(context, deviceInfo),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
isTcpConnected
? Icons.wifi_rounded
: Icons.bluetooth_connected_rounded,
size: 13,
color: signalColor,
),
if (!isTcpConnected &&
deviceInfo.signalRssi != null) ...[
const SizedBox(width: 4),
_buildMiniSignalBars(
activeBars:
BatteryDisplayHelper.getSignalBars(
deviceInfo.signalRssi!,
),
mainAxisSize: MainAxisSize.min,
children: [
Icon(
isTcpConnected
? Icons.wifi_rounded
: Icons.bluetooth_connected_rounded,
size: 13,
color: signalColor,
),
],
if (deviceInfo.batteryPercent != null) ...[
const SizedBox(width: 8),
Icon(
BatteryDisplayHelper.getBatteryIcon(
deviceInfo.batteryPercent!,
if (!isTcpConnected &&
deviceInfo.signalRssi != null) ...[
const SizedBox(width: 4),
_buildMiniSignalBars(
activeBars:
BatteryDisplayHelper.getSignalBars(
deviceInfo.signalRssi!,
),
color: signalColor,
),
size: 13,
color:
BatteryDisplayHelper.getBatteryColor(
deviceInfo.batteryPercent!,
),
),
const SizedBox(width: 2),
Text(
'${deviceInfo.batteryPercent!.round()}%',
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.w600,
],
if (deviceInfo.batteryPercent != null) ...[
const SizedBox(width: 8),
Icon(
BatteryDisplayHelper.getBatteryIcon(
deviceInfo.batteryPercent!,
),
size: 13,
color:
BatteryDisplayHelper.getBatteryColor(
deviceInfo.batteryPercent!,
),
),
),
const SizedBox(width: 2),
Text(
'${deviceInfo.batteryPercent!.round()}%',
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.w600,
color:
BatteryDisplayHelper.getBatteryColor(
deviceInfo.batteryPercent!,
),
),
),
],
],
],
),
),
),
],
),

View File

@@ -48,6 +48,110 @@ class MessagesTab extends StatefulWidget {
State<MessagesTab> createState() => _MessagesTabState();
}
class _ComposerActionTile extends StatelessWidget {
final IconData icon;
final String title;
final String subtitle;
final Color color;
final bool enabled;
final VoidCallback? onTap;
const _ComposerActionTile({
required this.icon,
required this.title,
required this.subtitle,
required this.color,
this.enabled = true,
this.onTap,
});
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
final effectiveColor = enabled
? color
: colorScheme.onSurfaceVariant.withValues(alpha: 0.45);
return Material(
color: Colors.transparent,
child: InkWell(
borderRadius: BorderRadius.circular(24),
onTap: enabled ? onTap : null,
child: Ink(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
enabled
? colorScheme.surfaceContainerLow
: colorScheme.surfaceContainerHighest,
enabled
? effectiveColor.withValues(alpha: 0.08)
: colorScheme.surfaceContainerHigh,
],
),
borderRadius: BorderRadius.circular(24),
border: Border.all(
color: enabled
? effectiveColor.withValues(alpha: 0.16)
: colorScheme.outlineVariant.withValues(alpha: 0.16),
),
boxShadow: [
BoxShadow(
color: effectiveColor.withValues(alpha: enabled ? 0.08 : 0.03),
blurRadius: 14,
offset: const Offset(0, 8),
),
],
),
child: Padding(
padding: const EdgeInsets.all(12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
width: 38,
height: 38,
decoration: BoxDecoration(
color: effectiveColor.withValues(alpha: enabled ? 0.14 : 0.10),
borderRadius: BorderRadius.circular(14),
),
alignment: Alignment.center,
child: Icon(icon, color: effectiveColor, size: 20),
),
const SizedBox(height: 8),
Text(
title,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w800,
letterSpacing: -0.2,
color: enabled
? colorScheme.onSurface
: colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 4),
Text(
subtitle,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
height: 1.15,
),
),
],
),
),
),
),
);
}
}
class _MessagesTabState extends State<MessagesTab> {
static const int _maxContactMessageBytes = 156;
static const int _maxChannelMessageBytes = 127;
@@ -667,7 +771,6 @@ class _MessagesTabState extends State<MessagesTab> {
}
_textController.clear();
_focusNode.unfocus();
try {
// Check destination type and send accordingly
@@ -1469,81 +1572,207 @@ class _MessagesTabState extends State<MessagesTab> {
void _showComposerActions() {
showModalBottomSheet(
context: context,
backgroundColor: Colors.transparent,
builder: (sheetContext) {
final theme = Theme.of(sheetContext);
final colorScheme = theme.colorScheme;
final l10n = AppLocalizations.of(context)!;
Future<void> runAction(Future<void> Function() action) async {
await _runAfterSheetDismissal(sheetContext, action);
}
return SafeArea(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
ListTile(
leading: Icon(Icons.search),
title: Text(AppLocalizations.of(context)!.searchMessages),
onTap: () async {
await _runAfterSheetDismissal(sheetContext, () async {
_showFilteredMessageSearch();
});
},
),
ListTile(
leading: Icon(Icons.add_location_alt),
title: Text(AppLocalizations.of(context)!.sendSarMarker),
onTap: () async {
await _runAfterSheetDismissal(sheetContext, () async {
_showSarDialog();
});
},
),
if (_voiceSupported)
ListTile(
enabled: !_isSendingVoice,
leading: Icon(_isRecording ? Icons.stop : Icons.mic),
title: Text(_isRecording ? 'Stop recording' : 'Record voice'),
onTap: _isSendingVoice
? null
: () async {
await _runAfterSheetDismissal(sheetContext, () async {
if (_isRecording) {
await _stopAndSendVoice();
} else {
await _startVoiceRecording();
}
});
},
child: ConstrainedBox(
constraints: BoxConstraints(
maxHeight: MediaQuery.of(sheetContext).size.height * 0.72,
),
child: Container(
margin: const EdgeInsets.fromLTRB(12, 0, 12, 12),
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
colorScheme.surface,
colorScheme.surfaceContainerLow,
],
),
ListTile(
enabled: !_isSendingImage,
leading: Icon(Icons.photo_library),
title: Text(AppLocalizations.of(context)!.sendImageFromGallery),
onTap: _isSendingImage
? null
: () async {
await _runAfterSheetDismissal(sheetContext, () async {
await _pickAndSendImage(source: ImageSource.gallery);
});
borderRadius: const BorderRadius.vertical(
top: Radius.circular(32),
bottom: Radius.circular(28),
),
boxShadow: [
BoxShadow(
color: colorScheme.shadow.withValues(alpha: 0.14),
blurRadius: 28,
offset: const Offset(0, 10),
),
],
),
child: SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 18),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Center(
child: Container(
width: 44,
height: 4,
decoration: BoxDecoration(
color: colorScheme.outlineVariant,
borderRadius: BorderRadius.circular(999),
),
),
),
const SizedBox(height: 14),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'More actions',
style: theme.textTheme.titleLarge?.copyWith(
fontWeight: FontWeight.w900,
letterSpacing: -0.4,
),
),
const SizedBox(height: 4),
Text(
'Search, share, or start something from this chat.',
style: theme.textTheme.bodyMedium?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
],
),
),
const SizedBox(width: 12),
Container(
decoration: BoxDecoration(
color: colorScheme.surfaceContainerHigh,
borderRadius: BorderRadius.circular(18),
border: Border.all(
color: colorScheme.outlineVariant.withValues(
alpha: 0.18,
),
),
),
child: IconButton(
onPressed: () => Navigator.pop(sheetContext),
tooltip: l10n.close,
icon: const Icon(Icons.close_rounded),
),
),
],
),
const SizedBox(height: 18),
LayoutBuilder(
builder: (context, constraints) {
final actions = <Widget>[
_ComposerActionTile(
icon: Icons.search_rounded,
title: l10n.searchMessages,
subtitle: 'Find text in the current conversation',
color: const Color(0xFF2B6CB0),
onTap: () => runAction(() async {
_showFilteredMessageSearch();
}),
),
_ComposerActionTile(
icon: Icons.add_location_alt_rounded,
title: l10n.sendSarMarker,
subtitle: 'Share a marker with coordinates',
color: const Color(0xFFB45309),
onTap: () => runAction(() async {
_showSarDialog();
}),
),
if (_voiceSupported)
_ComposerActionTile(
icon: _isRecording
? Icons.stop_rounded
: Icons.mic_rounded,
title: _isRecording
? 'Stop recording'
: 'Record voice',
subtitle: _isSendingVoice
? 'Voice message is sending'
: _isRecording
? 'Finish and send your clip'
: 'Capture and send a voice note',
color: const Color(0xFF7C3AED),
enabled: !_isSendingVoice,
onTap: !_isSendingVoice
? () => runAction(() async {
if (_isRecording) {
await _stopAndSendVoice();
} else {
await _startVoiceRecording();
}
})
: null,
),
_ComposerActionTile(
icon: Icons.photo_library_rounded,
title: l10n.sendImageFromGallery,
subtitle: 'Choose an image from your library',
color: const Color(0xFF0F766E),
enabled: !_isSendingImage,
onTap: !_isSendingImage
? () => runAction(() async {
await _pickAndSendImage(
source: ImageSource.gallery,
);
})
: null,
),
_ComposerActionTile(
icon: Icons.camera_alt_rounded,
title: l10n.takePhoto,
subtitle: 'Capture something right now',
color: const Color(0xFF2563EB),
enabled: !_isSendingImage,
onTap: !_isSendingImage
? () => runAction(() async {
await _pickAndSendImage(
source: ImageSource.camera,
);
})
: null,
),
_ComposerActionTile(
icon: Icons.grid_3x3_rounded,
title: l10n.startTictactoe,
subtitle: l10n.dmOnly,
color: const Color(0xFFBE185D),
onTap: () => runAction(() async {
await _startTicTacToeGame();
}),
),
];
return GridView.builder(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemCount: actions.length,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
mainAxisSpacing: 12,
crossAxisSpacing: 12,
mainAxisExtent: 126,
),
itemBuilder: (context, index) => actions[index],
);
},
),
],
),
),
ListTile(
enabled: !_isSendingImage,
leading: Icon(Icons.camera_alt),
title: Text(AppLocalizations.of(context)!.takePhoto),
onTap: _isSendingImage
? null
: () async {
await _runAfterSheetDismissal(sheetContext, () async {
await _pickAndSendImage(source: ImageSource.camera);
});
},
),
ListTile(
leading: Icon(Icons.grid_3x3),
title: Text(AppLocalizations.of(context)!.startTictactoe),
subtitle: Text(AppLocalizations.of(context)!.dmOnly),
onTap: () async {
await _runAfterSheetDismissal(sheetContext, () async {
await _startTicTacToeGame();
});
},
),
],
),
),
);
},

View File

@@ -7,6 +7,7 @@ import '../models/contact.dart';
import '../providers/connection_provider.dart';
import '../providers/contacts_provider.dart';
import '../providers/sensors_provider.dart';
import '../widgets/sensors/bthome_met_history_sheet.dart';
import '../widgets/sensors/sensor_telemetry_card.dart';
import '../l10n/app_localizations.dart';
@@ -104,74 +105,120 @@ class _SensorsTabState extends State<SensorsTab> {
contactsProvider,
connectionProvider: context.read<ConnectionProvider>(),
);
final searchController = TextEditingController();
await showModalBottomSheet<void>(
context: context,
showDragHandle: true,
builder: (sheetContext) {
if (candidates.isEmpty) {
return const SafeArea(
child: Padding(
padding: EdgeInsets.all(24),
child: Text(
'No eligible nodes available. Discover a relay or node first.',
),
),
);
}
return SafeArea(
child: ListView(
shrinkWrap: true,
padding: const EdgeInsets.only(bottom: 20),
children: [
ListTile(
title: const Text(
'Add sensor node',
style: TextStyle(fontWeight: FontWeight.bold),
),
subtitle: Text(
AppLocalizations.of(
context,
)!.pickARelayOrNodeToWatchInSensors,
try {
await showModalBottomSheet<void>(
context: context,
showDragHandle: true,
isScrollControlled: true,
builder: (sheetContext) {
if (candidates.isEmpty) {
return const SafeArea(
child: Padding(
padding: EdgeInsets.all(24),
child: Text(
'No eligible nodes available. Discover a relay or node first.',
),
),
...candidates.map(
(contact) => ListTile(
contentPadding: const EdgeInsets.symmetric(
horizontal: 20,
vertical: 4,
);
}
return StatefulBuilder(
builder: (context, setModalState) {
final query = searchController.text.trim().toLowerCase();
final filteredCandidates = candidates.where((contact) {
if (query.isEmpty) {
return true;
}
return contact.displayName.toLowerCase().contains(query) ||
contact.publicKeyHex.toLowerCase().contains(query);
}).toList();
return SafeArea(
child: Padding(
padding: EdgeInsets.only(
bottom: MediaQuery.of(context).viewInsets.bottom,
),
leading: CircleAvatar(
radius: 24,
backgroundColor: const Color(0xFFDDEAF8),
child: Icon(
_typeIcon(contact),
color: const Color(0xFF1E4F7A),
),
),
title: Text(contact.displayName),
subtitle: _SensorCandidatePreview(contact: contact),
isThreeLine: true,
onTap: () async {
await sensorsProvider.addSensor(contact);
if (!sheetContext.mounted) return;
Navigator.of(sheetContext).pop();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
'${contact.displayName} added to Sensors',
child: ListView(
shrinkWrap: true,
padding: const EdgeInsets.only(bottom: 20),
children: [
ListTile(
title: const Text(
'Add sensor node',
style: TextStyle(fontWeight: FontWeight.bold),
),
subtitle: Text(
AppLocalizations.of(
context,
)!.pickARelayOrNodeToWatchInSensors,
),
),
);
},
Padding(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 12),
child: TextField(
controller: searchController,
onChanged: (_) => setModalState(() {}),
decoration: const InputDecoration(
prefixIcon: Icon(Icons.search),
hintText: 'Search sensors',
border: OutlineInputBorder(),
),
),
),
if (filteredCandidates.isEmpty)
const Padding(
padding: EdgeInsets.symmetric(
horizontal: 20,
vertical: 16,
),
child: Text(
'No sensor candidates match your search.',
),
),
...filteredCandidates.map(
(contact) => ListTile(
contentPadding: const EdgeInsets.symmetric(
horizontal: 20,
vertical: 4,
),
leading: CircleAvatar(
radius: 24,
backgroundColor: const Color(0xFFDDEAF8),
child: Icon(
_typeIcon(contact),
color: const Color(0xFF1E4F7A),
),
),
title: Text(contact.displayName),
subtitle: _SensorCandidatePreview(contact: contact),
isThreeLine: true,
onTap: () async {
await sensorsProvider.addSensor(contact);
if (!sheetContext.mounted) return;
Navigator.of(sheetContext).pop();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
'${contact.displayName} added to Sensors',
),
),
);
},
),
),
],
),
),
),
],
),
);
},
);
);
},
);
},
);
} finally {
searchController.dispose();
}
}
Future<void> _showMetricSelector(
@@ -291,61 +338,135 @@ class _SensorsTabState extends State<SensorsTab> {
connectionProvider,
child,
) {
final displayKeys = sensorsProvider.displaySensorKeys(
final watchedKeys = sensorsProvider.watchedSensorKeys;
final hasPersistedSensors = watchedKeys.isNotEmpty;
final selfDisplayKey = sensorsProvider.displaySelfKey(
contactsProvider: contactsProvider,
connectionProvider: connectionProvider,
);
final hasPersistedSensors =
sensorsProvider.watchedSensorKeys.isNotEmpty;
final hasAnyCards =
selfDisplayKey != null || watchedKeys.isNotEmpty;
Widget buildSensorCard(
String key, {
required int index,
required int totalCount,
required bool isWatchedCard,
}) {
final contact = sensorsProvider.contactForDisplay(
key,
contactsProvider: contactsProvider,
connectionProvider: connectionProvider,
);
final availableFieldKeys = sensorMetricKeysFor(contact);
final visibleFields = sensorsProvider.effectiveVisibleFieldsFor(
key,
availableFieldKeys,
);
return Padding(
key: ValueKey<String>('sensor_card_$key'),
padding: EdgeInsets.only(
bottom: index == totalCount - 1 ? 0 : 12,
),
child: ReorderableDelayedDragStartListener(
enabled: isWatchedCard,
index: index,
child: SensorTelemetryCard(
contact: contact,
state: sensorsProvider.stateFor(key),
visibleFields: visibleFields,
fieldOrder: sensorsProvider.metricOrderFor(
key,
availableFieldKeys,
),
labelOverrides: sensorsProvider.labelOverridesFor(key),
fieldSpans: {
for (final field in visibleFields)
field: sensorsProvider.fieldSpanFor(key, field),
},
onRemove: isWatchedCard
? () async {
await sensorsProvider.removeSensor(key);
}
: null,
onCustomize: () =>
_showMetricSelector(context, key, contact),
onShowMetHistory: (contact) =>
showBTHomeMetHistorySheet(context, contact: contact),
onMoveUp: isWatchedCard && index > 0
? () =>
sensorsProvider.reorderSensors(index, index - 1)
: null,
onMoveDown: isWatchedCard && index < totalCount - 1
? () =>
sensorsProvider.reorderSensors(index, index + 2)
: null,
onRefresh: () => sensorsProvider.refreshSensor(
publicKeyHex: key,
contactsProvider: contactsProvider,
connectionProvider: connectionProvider,
),
),
),
);
}
return RefreshIndicator(
onRefresh: () => _refreshAll(context),
child: ListView(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 96),
children: [
if (displayKeys.isEmpty)
const _EmptySensorsState()
else
...displayKeys.map((key) {
final contact = sensorsProvider.contactForDisplay(
key,
contactsProvider: contactsProvider,
connectionProvider: connectionProvider,
);
final availableFieldKeys = sensorMetricKeysFor(contact);
final visibleFields = sensorsProvider
.effectiveVisibleFieldsFor(key, availableFieldKeys);
return SensorTelemetryCard(
contact: contact,
state: sensorsProvider.stateFor(key),
visibleFields: visibleFields,
fieldOrder: sensorsProvider.metricOrderFor(
key,
availableFieldKeys,
),
labelOverrides: sensorsProvider.labelOverridesFor(
key,
),
fieldSpans: {
for (final field in visibleFields)
field: sensorsProvider.fieldSpanFor(key, field),
},
onRemove: hasPersistedSensors
? () async {
await sensorsProvider.removeSensor(key);
}
: null,
onCustomize: () =>
_showMetricSelector(context, key, contact),
onRefresh: () => sensorsProvider.refreshSensor(
publicKeyHex: key,
contactsProvider: contactsProvider,
connectionProvider: connectionProvider,
),
);
}),
],
),
child: !hasAnyCards
? ListView(
physics: const AlwaysScrollableScrollPhysics(),
padding: const EdgeInsets.fromLTRB(16, 16, 16, 96),
children: const [_EmptySensorsState()],
)
: hasPersistedSensors && selfDisplayKey == null
? ReorderableListView.builder(
buildDefaultDragHandles: false,
physics: const AlwaysScrollableScrollPhysics(),
padding: const EdgeInsets.fromLTRB(16, 16, 16, 96),
itemCount: watchedKeys.length,
onReorder: (oldIndex, newIndex) =>
sensorsProvider.reorderSensors(oldIndex, newIndex),
itemBuilder: (context, index) => buildSensorCard(
watchedKeys[index],
index: index,
totalCount: watchedKeys.length,
isWatchedCard: true,
),
)
: ListView(
physics: const AlwaysScrollableScrollPhysics(),
padding: const EdgeInsets.fromLTRB(16, 16, 16, 96),
children: [
if (selfDisplayKey != null)
buildSensorCard(
selfDisplayKey,
index: 0,
totalCount: watchedKeys.isEmpty ? 1 : 2,
isWatchedCard: false,
),
if (selfDisplayKey != null && watchedKeys.isEmpty)
_SelfOnlySensorsCta(
onAddSensor: () => _showAddSensorSheet(context),
),
if (watchedKeys.isNotEmpty)
ReorderableListView.builder(
shrinkWrap: true,
buildDefaultDragHandles: false,
physics: const NeverScrollableScrollPhysics(),
itemCount: watchedKeys.length,
onReorder: (oldIndex, newIndex) => sensorsProvider
.reorderSensors(oldIndex, newIndex),
itemBuilder: (context, index) => buildSensorCard(
watchedKeys[index],
index: index,
totalCount: watchedKeys.length,
isWatchedCard: true,
),
),
],
),
);
},
),
@@ -427,6 +548,12 @@ class _SensorCustomizeView extends StatelessWidget {
labelOverrides: sensorsProvider.labelOverridesFor(
publicKeyHex,
),
onShowMetHistory: contact == null
? null
: (contact) => showBTHomeMetHistorySheet(
context,
contact: contact,
),
fieldSpans: {
for (final field in visibleFields)
field: sensorsProvider.fieldSpanFor(publicKeyHex, field),
@@ -935,6 +1062,81 @@ class _EmptySensorsStateState extends State<_EmptySensorsState> {
}
}
class _SelfOnlySensorsCta extends StatelessWidget {
final VoidCallback onAddSensor;
const _SelfOnlySensorsCta({required this.onAddSensor});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Container(
margin: const EdgeInsets.only(top: 8),
padding: const EdgeInsets.fromLTRB(18, 18, 18, 20),
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerLow,
borderRadius: BorderRadius.circular(24),
border: Border.all(
color: theme.colorScheme.outlineVariant.withValues(alpha: 0.35),
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
width: 44,
height: 44,
decoration: BoxDecoration(
color: theme.colorScheme.primaryContainer,
borderRadius: BorderRadius.circular(16),
),
child: Icon(
Icons.add_chart_rounded,
color: theme.colorScheme.onPrimaryContainer,
),
),
const SizedBox(width: 14),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Add another device',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 8),
Text(
'Bring in weather stations, repeaters, or other devices to watch them here.',
style: theme.textTheme.bodyMedium?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
height: 1.35,
),
),
],
),
),
],
),
const SizedBox(height: 16),
Align(
alignment: Alignment.centerLeft,
child: FilledButton.icon(
onPressed: onAddSensor,
icon: const Icon(Icons.add, size: 18),
label: const Text('Choose'),
),
),
],
),
);
}
}
IconData _typeIcon(Contact contact) {
if (contact.isSensor) {
return Icons.sensors;

View File

@@ -0,0 +1,178 @@
import '../models/contact.dart';
enum BTHomeMetMeasurement {
temperature(1, 'Temperature', '°C'),
humidity(2, 'Humidity', '%'),
windSpeed(3, 'Wind speed', 'm/s'),
gust(4, 'Wind gust', 'm/s'),
rain(5, 'Rain', 'mm');
const BTHomeMetMeasurement(this.id, this.label, this.unit);
final int id;
final String label;
final String unit;
static BTHomeMetMeasurement? fromId(int id) {
for (final value in BTHomeMetMeasurement.values) {
if (value.id == id) {
return value;
}
}
return null;
}
}
class BTHomeMetHistoryPage {
const BTHomeMetHistoryPage({
required this.measurement,
required this.page,
required this.values,
});
final BTHomeMetMeasurement measurement;
final int page;
final List<double> values;
double? get latest => values.isEmpty ? null : values.last;
double? get minimum => values.isEmpty
? null
: values.reduce((left, right) => left < right ? left : right);
double? get maximum => values.isEmpty
? null
: values.reduce((left, right) => left > right ? left : right);
}
class BTHomeMetHistoryFormatException implements Exception {
const BTHomeMetHistoryFormatException(this.message);
final String message;
@override
String toString() => message;
}
class BTHomeMetHistoryParser {
static BTHomeMetHistoryPage parse(String text) {
final parts = text
.trim()
.split(',')
.map((part) => part.trim())
.toList(growable: false);
if (parts.length < 3) {
throw const BTHomeMetHistoryFormatException(
'MET history response is too short.',
);
}
final measurementId = int.tryParse(parts[0]);
final page = int.tryParse(parts[1]);
final count = int.tryParse(parts[2]);
if (measurementId == null || page == null || count == null) {
throw const BTHomeMetHistoryFormatException(
'MET history header is invalid.',
);
}
final measurement = BTHomeMetMeasurement.fromId(measurementId);
if (measurement == null) {
throw BTHomeMetHistoryFormatException(
'Unsupported MET history measurement id: $measurementId',
);
}
if (count < 0) {
throw const BTHomeMetHistoryFormatException(
'MET history sample count is invalid.',
);
}
if (parts.length != count + 3) {
throw BTHomeMetHistoryFormatException(
'MET history sample count mismatch: expected $count values, got ${parts.length - 3}.',
);
}
final values = <double>[];
for (final part in parts.skip(3)) {
final value = double.tryParse(part);
if (value == null) {
throw BTHomeMetHistoryFormatException(
'Invalid MET history sample value: $part',
);
}
values.add(value);
}
return BTHomeMetHistoryPage(
measurement: measurement,
page: page,
values: List<double>.unmodifiable(values),
);
}
}
bool _isTruthyCapabilityValue(Object? value) {
if (value is num) {
return value > 0;
}
if (value is bool) {
return value;
}
return false;
}
bool _hasBTHomeMetCapability(Contact? contact) {
final extraSensorData = contact?.telemetry?.extraSensorData;
if (extraSensorData == null) {
return false;
}
// MET history is only enabled when the node advertises an explicit
// capability marker on channel 1. Accept a small set of channel-1 marker
// keys so the app remains tolerant while firmware-side encoding settles.
const capabilityKeys = <String>[
'met_capability',
'met_capability_1',
'generic_sensor_1',
'light_level_1',
];
for (final key in capabilityKeys) {
if (_isTruthyCapabilityValue(extraSensorData[key])) {
return true;
}
}
return false;
}
List<BTHomeMetMeasurement> bTHomeMetMeasurementsForContact(Contact? contact) {
final telemetry = contact?.telemetry;
if (telemetry == null || !_hasBTHomeMetCapability(contact)) {
return const <BTHomeMetMeasurement>[];
}
final measurements = <BTHomeMetMeasurement>[
if (telemetry.temperature != null) BTHomeMetMeasurement.temperature,
if (telemetry.humidity != null) BTHomeMetMeasurement.humidity,
];
final extraSensorData = telemetry.extraSensorData;
if (extraSensorData != null) {
if (extraSensorData.keys.any(
(key) => key.startsWith('speed_') || key.startsWith('signed_speed_'),
)) {
measurements.add(BTHomeMetMeasurement.windSpeed);
}
if (extraSensorData.keys.any((key) => key.startsWith('gust_'))) {
measurements.add(BTHomeMetMeasurement.gust);
}
if (extraSensorData.keys.any((key) => key.startsWith('rain_'))) {
measurements.add(BTHomeMetMeasurement.rain);
}
}
return List<BTHomeMetMeasurement>.unmodifiable(measurements);
}
bool supportsBTHomeMetHistory(Contact? contact) =>
bTHomeMetMeasurementsForContact(contact).isNotEmpty;

View File

@@ -88,10 +88,13 @@ class CayenneLppParser {
LatLng? gpsLocation;
double? batteryPercentage;
double? batteryMilliVolts;
double? deferredBatteryMilliVolts;
double? deferredBatteryPercentage;
double? temperature;
double? humidity;
double? pressure;
final extraSensorData = <String, dynamic>{};
bool sawNonSelfChannel = false;
int fieldCount = 0;
while (reader.hasRemaining) {
@@ -112,6 +115,9 @@ class CayenneLppParser {
final channel = reader.readByte();
debugPrint(' Channel: $channel');
if (channel != _selfTelemetryChannel) {
sawNonSelfChannel = true;
}
final type = reader.readByte();
debugPrint(
@@ -136,7 +142,7 @@ class CayenneLppParser {
final value = rawValue / 100.0;
debugPrint(' Analog Input (raw): $rawValue');
debugPrint(' Analog Input (volts): ${value}V');
if (_isBatteryChannel(channel)) {
if (_isDedicatedBatteryChannel(channel)) {
batteryMilliVolts = value * 1000;
batteryPercentage = _calculateBatteryPercentage(value);
extraSensorData[_sourceChannelKey('battery')] = channel;
@@ -144,6 +150,10 @@ class CayenneLppParser {
debugPrint(
' → Battery: ${batteryPercentage.toStringAsFixed(1)}% (${batteryMilliVolts.toStringAsFixed(0)}mV)',
);
} else if (_isDeferredBatteryChannel(channel)) {
deferredBatteryMilliVolts = value * 1000;
deferredBatteryPercentage = _calculateBatteryPercentage(value);
extraSensorData['analog_input_$channel'] = value;
} else {
extraSensorData['analog_input_$channel'] = value;
}
@@ -237,7 +247,7 @@ class CayenneLppParser {
final value = rawValue / 100.0;
debugPrint(' Voltage (raw): $rawValue');
debugPrint(' Voltage: ${value}V');
if (_isBatteryChannel(channel)) {
if (_isDedicatedBatteryChannel(channel)) {
batteryMilliVolts = value * 1000;
batteryPercentage = _calculateBatteryPercentage(value);
extraSensorData[_sourceChannelKey('battery')] = channel;
@@ -245,6 +255,10 @@ class CayenneLppParser {
debugPrint(
' → Battery: ${batteryPercentage.toStringAsFixed(1)}% (${batteryMilliVolts.toStringAsFixed(0)}mV)',
);
} else if (_isDeferredBatteryChannel(channel)) {
deferredBatteryMilliVolts = value * 1000;
deferredBatteryPercentage = _calculateBatteryPercentage(value);
extraSensorData['voltage_$channel'] = value;
} else {
extraSensorData['voltage_$channel'] = value;
}
@@ -327,7 +341,7 @@ class CayenneLppParser {
case _lppPercentage:
final value = reader.readByte().toDouble();
debugPrint(' Percentage: $value%');
if (_isBatteryChannel(channel)) {
if (_isDedicatedBatteryChannel(channel) || _isDeferredBatteryChannel(channel)) {
batteryPercentage = value;
extraSensorData[_sourceChannelKey('battery')] = channel;
} else {
@@ -631,6 +645,21 @@ class CayenneLppParser {
}
}
if (batteryMilliVolts == null &&
batteryPercentage == null &&
deferredBatteryMilliVolts != null &&
deferredBatteryPercentage != null &&
!sawNonSelfChannel) {
batteryMilliVolts = deferredBatteryMilliVolts;
batteryPercentage = deferredBatteryPercentage;
extraSensorData[_sourceChannelKey('battery')] = _selfTelemetryChannel;
extraSensorData[_sourceChannelKey('voltage')] = _selfTelemetryChannel;
debugPrint(
' Promoted self-channel voltage to battery: '
'${batteryPercentage.toStringAsFixed(1)}% (${batteryMilliVolts.toStringAsFixed(0)}mV)',
);
}
debugPrint(' Parsed $fieldCount fields');
debugPrint(' ✅ [CayenneLPP] Parsing complete');
debugPrint(
@@ -677,8 +706,10 @@ class CayenneLppParser {
return ((voltage - 3.0) / 1.2) * 100.0;
}
static bool _isBatteryChannel(int channel) =>
channel == 0 || channel == _selfTelemetryChannel;
static bool _isDedicatedBatteryChannel(int channel) => channel == 0;
static bool _isDeferredBatteryChannel(int channel) =>
channel == _selfTelemetryChannel;
static int _readUInt32BE(BufferReader reader) {
final bytes = reader.readBytes(4);

View File

@@ -14,6 +14,8 @@ import '../providers/drawing_provider.dart';
import '../providers/map_provider.dart';
import '../providers/messages_provider.dart';
import '../providers/sensors_provider.dart';
import '../providers/voice_provider.dart';
import '../providers/image_provider.dart' as ip;
import 'app_config_snapshot_service.dart';
import 'contact_storage_service.dart';
import 'device_config_applicator.dart';
@@ -33,6 +35,8 @@ class ProfileWorkspaceCoordinator {
required this.mapProvider,
required this.drawingProvider,
required this.channelsProvider,
required this.voiceProvider,
required this.imageProvider,
required this.appProvider,
AppConfigSnapshotService? appConfigSnapshotService,
MapWorkspaceSnapshotService? mapWorkspaceSnapshotService,
@@ -58,13 +62,15 @@ class ProfileWorkspaceCoordinator {
final MapProvider mapProvider;
final DrawingProvider drawingProvider;
final ChannelsProvider channelsProvider;
final VoiceProvider voiceProvider;
final ip.ImageProvider imageProvider;
final AppProvider appProvider;
final AppConfigSnapshotService _appConfigSnapshotService;
final MapWorkspaceSnapshotService _mapWorkspaceSnapshotService;
final DeviceConfigApplicator _deviceConfigApplicator;
final MessageStorageService _messageStorageService;
final ContactStorageService _contactStorageService;
bool _isSyncingDeviceProfile = false;
Future<void>? _deviceProfileSyncFuture;
Future<void> setProfilesEnabled(bool enabled) async {
final wasEnabled = profileManager.profilesEnabled;
@@ -279,41 +285,54 @@ class ProfileWorkspaceCoordinator {
}
Future<void> syncActiveProfileForCurrentDevice() async {
if (!profileManager.profilesEnabled || _isSyncingDeviceProfile) {
if (!profileManager.profilesEnabled) {
return;
}
final inFlightSync = _deviceProfileSyncFuture;
if (inFlightSync != null) {
await inFlightSync;
return;
}
final syncFuture = _syncActiveProfileForCurrentDeviceInternal();
_deviceProfileSyncFuture = syncFuture;
try {
await syncFuture;
} finally {
if (identical(_deviceProfileSyncFuture, syncFuture)) {
_deviceProfileSyncFuture = null;
}
}
}
Future<void> _syncActiveProfileForCurrentDeviceInternal() async {
final deviceKey = _currentDeviceProfileKey;
if (deviceKey == null) {
return;
}
_isSyncingDeviceProfile = true;
try {
final profile = await _ensureProfileForCurrentDevice();
final targetProfileId = profile.id;
if (targetProfileId == profileManager.activeProfileId) {
return;
}
await _persistCurrentState();
await profileManager.setActiveProfileIdForDevice(
targetProfileId,
deviceKey: deviceKey,
);
await _switchRuntimeScope(targetProfileId);
await _appConfigSnapshotService.apply(
profile.sections.appSettings,
appProvider,
);
await _mapWorkspaceSnapshotService.apply(
profile.sections.mapWorkspace,
mapProvider: mapProvider,
drawingProvider: drawingProvider,
);
} finally {
_isSyncingDeviceProfile = false;
final profile = await _ensureProfileForCurrentDevice();
final targetProfileId = profile.id;
if (targetProfileId == profileManager.activeProfileId) {
return;
}
await _persistCurrentState();
await profileManager.setActiveProfileIdForDevice(
targetProfileId,
deviceKey: deviceKey,
);
await _switchRuntimeScope(targetProfileId);
await _appConfigSnapshotService.apply(
profile.sections.appSettings,
appProvider,
);
await _mapWorkspaceSnapshotService.apply(
profile.sections.mapWorkspace,
mapProvider: mapProvider,
drawingProvider: drawingProvider,
);
}
Future<ConfigProfile> _ensureProfileForCurrentDevice() async {
@@ -387,6 +406,8 @@ class ProfileWorkspaceCoordinator {
await sensorsProvider.reloadProfileScopedState();
await drawingProvider.reloadProfileScopedState();
await mapProvider.reloadProfileScopedState();
await voiceProvider.reloadProfileScopedState();
await imageProvider.reloadProfileScopedState();
await appProvider.reloadProfileScopedSettings();
}

View File

@@ -5,8 +5,17 @@ import '../l10n/app_localizations.dart';
import '../providers/app_provider.dart';
import '../providers/connection_provider.dart';
import '../services/network_scanner_service.dart';
import '../services/profile_workspace_coordinator.dart';
import '../services/serial/serial_transport.dart';
Future<void> _initializeConnectedWorkspace({
required ProfileWorkspaceCoordinator profileWorkspaceCoordinator,
required AppProvider appProvider,
}) async {
await profileWorkspaceCoordinator.syncActiveProfileForCurrentDevice();
await appProvider.initialize();
}
/// Connection Dialog with tabs for BLE devices and Network servers
class ConnectionDialog extends StatefulWidget {
const ConnectionDialog({super.key});
@@ -426,6 +435,8 @@ class _ConnectionDialogState extends State<ConnectionDialog>
Future<void> connectBle() async {
final appProvider = context.read<AppProvider>();
final profileWorkspaceCoordinator = context
.read<ProfileWorkspaceCoordinator>();
setState(() {
_connectingBleDeviceId = deviceId;
});
@@ -436,7 +447,11 @@ class _ConnectionDialogState extends State<ConnectionDialog>
);
if (success &&
connectionProvider.deviceInfo.isConnected) {
await appProvider.initialize();
await _initializeConnectedWorkspace(
profileWorkspaceCoordinator:
profileWorkspaceCoordinator,
appProvider: appProvider,
);
}
} finally {
if (mounted) {
@@ -533,6 +548,8 @@ class _ConnectionDialogState extends State<ConnectionDialog>
final connectionProvider = context
.read<ConnectionProvider>();
final appProvider = context.read<AppProvider>();
final profileWorkspaceCoordinator = context
.read<ProfileWorkspaceCoordinator>();
final navigator = Navigator.of(context);
final messenger = ScaffoldMessenger.of(context);
@@ -554,7 +571,11 @@ class _ConnectionDialogState extends State<ConnectionDialog>
server.ipAddress,
server.port,
);
await appProvider.initialize();
await _initializeConnectedWorkspace(
profileWorkspaceCoordinator:
profileWorkspaceCoordinator,
appProvider: appProvider,
);
if (mounted) {
navigator.pop();
@@ -781,6 +802,8 @@ class _SerialDeviceListState extends State<_SerialDeviceList> {
try {
final connectionProvider = context.read<ConnectionProvider>();
final appProvider = context.read<AppProvider>();
final profileWorkspaceCoordinator = context
.read<ProfileWorkspaceCoordinator>();
final connection = await _transport.connect(device);
final success = await connectionProvider.connectSerial(
service: connection.service,
@@ -791,7 +814,10 @@ class _SerialDeviceListState extends State<_SerialDeviceList> {
if (!mounted) return;
if (success) {
await appProvider.initialize();
await _initializeConnectedWorkspace(
profileWorkspaceCoordinator: profileWorkspaceCoordinator,
appProvider: appProvider,
);
widget.onConnected();
} else {
await connection.disconnect();

View File

@@ -16,6 +16,7 @@ import 'contact_route_dialog.dart';
import 'contact_trace_sheet.dart';
import 'room_login_sheet.dart';
import '../common/contact_avatar.dart';
import '../sensors/bthome_met_history_sheet.dart';
import '../sensors/sensor_telemetry_card.dart';
import '../../utils/link_quality.dart';
import '../../utils/time_ago_extensions.dart';
@@ -351,6 +352,7 @@ class ContactTile extends StatelessWidget {
void _showContactActionSheet(BuildContext context, Contact contact) {
final l10n = AppLocalizations.of(context)!;
final canToggleFavourite = !contact.isChannel;
final canMessage =
contact.type == ContactType.chat ||
contact.type == ContactType.room ||
@@ -368,192 +370,167 @@ class ContactTile extends StatelessWidget {
final sensorsProvider = context.read<SensorsProvider>();
final isInSensors = sensorsProvider.isWatched(contact.publicKeyHex);
showModalBottomSheet(
context: context,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
),
builder: (sheetContext) => SafeArea(
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (!contact.isChannel)
ListTile(
leading: Icon(
contact.isFavourite ? Icons.star : Icons.star_outline,
color: contact.isFavourite ? Colors.amber : null,
),
title: Text(
contact.isFavourite
? 'Remove from Favourites'
: 'Add to Favourites',
),
onTap: () async {
Navigator.pop(sheetContext);
final toggled = contact.toggleFavourite();
final connectionProvider = context
.read<ConnectionProvider>();
await connectionProvider.addOrUpdateContact(toggled);
if (context.mounted) {
// Refresh contact from device so the local cache is updated
await connectionProvider.getContact(contact.publicKey);
}
},
),
if (!contact.isChannel)
ListTile(
leading: Icon(Icons.share_outlined),
title: Text(l10n.shareContact),
onTap: () async {
Navigator.pop(sheetContext);
final connectionProvider = context
.read<ConnectionProvider>();
final url = await connectionProvider.exportContactUrl(
contact.publicKey,
);
if (url != null && context.mounted) {
await Clipboard.setData(ClipboardData(text: url));
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(l10n.contactLinkCopiedToClipboard),
),
);
}
} else if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(l10n.failedToExportContact)),
);
}
},
),
ListTile(
leading: Icon(Icons.message_outlined),
title: Text(l10n.messages),
enabled: canMessage,
onTap: !canMessage
? null
: () async {
Navigator.pop(sheetContext);
await _openMessagesForContact(context, contact);
},
),
if (contact.displayLocation != null)
ListTile(
leading: Icon(Icons.map_outlined),
title: Text(l10n.viewOnMap),
onTap: () {
Navigator.pop(sheetContext);
_showContactOnMap(context, contact);
},
),
if (contact.type == ContactType.room && !contact.isPublicChannel)
ListTile(
leading: const Icon(Icons.login),
title: Text(
context
.read<ConnectionProvider>()
.getRoomLoginState(contact.publicKeyPrefix)
?.isLoggedIn ==
true
? AppLocalizations.of(context)!.reLoginToRoom
: AppLocalizations.of(context)!.loginToRoom,
),
onTap: () {
Navigator.pop(sheetContext);
_showRoomLoginDialog(context, contact);
},
),
if (canPreviewSensor)
ListTile(
leading: Icon(Icons.visibility_outlined),
title: Text(l10n.preview),
onTap: () async {
Navigator.pop(sheetContext);
await Future<void>.delayed(Duration.zero);
if (!context.mounted) return;
await _showSensorPreviewView(context, contact);
},
),
if (canAddToSensors)
ListTile(
leading: Icon(
isInSensors ? Icons.sensors : Icons.sensors_outlined,
),
title: Text(
isInSensors
? l10n.contactInSensors
: l10n.contactAddToSensors,
),
enabled: !isInSensors,
onTap: isInSensors
? null
: () async {
Navigator.pop(sheetContext);
await _addContactToSensors(context, contact);
},
),
if (canSetPath)
ListTile(
leading: Icon(Icons.alt_route),
title: Text(l10n.contactSetPath),
onTap: () {
Navigator.pop(sheetContext);
_showSetRouteDialog(context, contact);
},
),
if (!contact.isChannel)
ListTile(
leading: Icon(Icons.route),
title: Text(l10n.trace),
onTap: () {
Navigator.pop(sheetContext);
_showTraceSheet(context, contact);
},
),
if (contact.type == ContactType.repeater)
ListTile(
leading: const Icon(Icons.hub_outlined),
title: const Text('View Neighbours'),
onTap: () {
Navigator.pop(sheetContext);
_showNeighbours(context, contact);
},
),
if (!contact.isPublicChannel)
ListTile(
leading: Icon(Icons.edit_outlined),
title: Text(l10n.editName),
onTap: () {
Navigator.pop(sheetContext);
_showNameOverrideDialog(context, contact);
},
),
if (!contact.isPublicChannel)
ListTile(
leading: Icon(Icons.delete, color: Colors.red),
title: Text(
contact.isChannel ? l10n.deleteChannel : l10n.deleteContact,
style: const TextStyle(color: Colors.red),
),
onTap: () async {
Navigator.pop(sheetContext);
await Future<void>.delayed(Duration.zero);
if (!context.mounted) return;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!context.mounted) return;
if (contact.isChannel) {
_showDeleteChannelDialog(context, contact);
} else {
_showDeleteConfirmation(context, contact);
}
});
},
),
],
),
final primaryActions = <_ContactSheetAction>[
if (canMessage)
_ContactSheetAction(
icon: Icons.message_outlined,
label: l10n.messages,
onTap: () async {
Navigator.pop(context);
await _openMessagesForContact(context, contact);
},
),
if (!contact.isChannel)
_ContactSheetAction(
icon: Icons.share_outlined,
label: l10n.share,
onTap: () async {
Navigator.pop(context);
final connectionProvider = context.read<ConnectionProvider>();
final url = await connectionProvider.exportContactUrl(
contact.publicKey,
);
if (url != null && context.mounted) {
await Clipboard.setData(ClipboardData(text: url));
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(l10n.contactLinkCopiedToClipboard)),
);
}
} else if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(l10n.failedToExportContact)),
);
}
},
),
if (canSetPath)
_ContactSheetAction(
icon: Icons.alt_route,
label: l10n.contactSetPath,
onTap: () async {
Navigator.pop(context);
await _showSetRouteDialog(context, contact);
},
),
if (!contact.isPublicChannel)
_ContactSheetAction(
icon: Icons.delete_outline_rounded,
label: l10n.delete,
destructive: true,
onTap: () async {
Navigator.pop(context);
await Future<void>.delayed(Duration.zero);
if (!context.mounted) return;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!context.mounted) return;
if (contact.isChannel) {
_showDeleteChannelDialog(context, contact);
} else {
_showDeleteConfirmation(context, contact);
}
});
},
),
];
final secondaryActions = <_ContactSheetAction>[
if (contact.displayLocation != null)
_ContactSheetAction(
icon: Icons.map_outlined,
label: l10n.viewOnMap,
onTap: () async {
Navigator.pop(context);
_showContactOnMap(context, contact);
},
),
if (contact.type == ContactType.room && !contact.isPublicChannel)
_ContactSheetAction(
icon: Icons.login,
label:
context
.read<ConnectionProvider>()
.getRoomLoginState(contact.publicKeyPrefix)
?.isLoggedIn ==
true
? l10n.reLoginToRoom
: l10n.loginToRoom,
onTap: () async {
Navigator.pop(context);
_showRoomLoginDialog(context, contact);
},
),
if (canPreviewSensor)
_ContactSheetAction(
icon: Icons.visibility_outlined,
label: l10n.preview,
onTap: () async {
Navigator.pop(context);
await Future<void>.delayed(Duration.zero);
if (!context.mounted) return;
await _showSensorPreviewView(context, contact);
},
),
if (canAddToSensors)
_ContactSheetAction(
icon: isInSensors ? Icons.sensors : Icons.sensors_outlined,
label: isInSensors ? l10n.contactInSensors : l10n.contactAddToSensors,
enabled: !isInSensors,
onTap: () async {
Navigator.pop(context);
await _addContactToSensors(context, contact);
},
),
if (!contact.isChannel)
_ContactSheetAction(
icon: Icons.route,
label: l10n.trace,
onTap: () async {
Navigator.pop(context);
_showTraceSheet(context, contact);
},
),
if (contact.type == ContactType.repeater)
_ContactSheetAction(
icon: Icons.hub_outlined,
label: 'View Neighbours',
onTap: () async {
Navigator.pop(context);
_showNeighbours(context, contact);
},
),
if (!contact.isPublicChannel)
_ContactSheetAction(
icon: Icons.edit_outlined,
label: l10n.editName,
onTap: () async {
Navigator.pop(context);
_showNameOverrideDialog(context, contact);
},
),
];
showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
backgroundColor: Colors.transparent,
builder: (sheetContext) => _ContactActionSheet(
contact: contact,
primaryActions: primaryActions,
secondaryActions: secondaryActions,
showFavouriteButton: canToggleFavourite,
initialFavourite: contact.isFavourite,
onClose: () => Navigator.pop(sheetContext),
onToggleFavourite: !canToggleFavourite
? null
: () async {
final toggled = contact.toggleFavourite();
final connectionProvider = context.read<ConnectionProvider>();
await connectionProvider.addOrUpdateContact(toggled);
if (context.mounted) {
await connectionProvider.getContact(contact.publicKey);
}
},
),
);
}
@@ -1153,6 +1130,8 @@ class _SensorPreviewView extends StatelessWidget {
visibleFields: visibleFields,
fieldOrder: fieldOrder,
labelOverrides: sensorsProvider.labelOverridesFor(publicKeyHex),
onShowMetHistory: (contact) =>
showBTHomeMetHistorySheet(context, contact: contact),
fieldSpans: sensorFullWidthFieldSpans(visibleFields),
margin: EdgeInsets.zero,
emptyMetricsMessage: 'No telemetry fields available yet.',
@@ -1165,6 +1144,484 @@ class _SensorPreviewView extends StatelessWidget {
}
}
class _ContactSheetAction {
final IconData icon;
final String label;
final Future<void> Function() onTap;
final bool destructive;
final bool enabled;
const _ContactSheetAction({
required this.icon,
required this.label,
required this.onTap,
this.destructive = false,
this.enabled = true,
});
}
class _ContactActionSheet extends StatefulWidget {
final Contact contact;
final List<_ContactSheetAction> primaryActions;
final List<_ContactSheetAction> secondaryActions;
final bool showFavouriteButton;
final bool initialFavourite;
final VoidCallback onClose;
final Future<void> Function()? onToggleFavourite;
const _ContactActionSheet({
required this.contact,
required this.primaryActions,
required this.secondaryActions,
required this.showFavouriteButton,
required this.initialFavourite,
required this.onClose,
required this.onToggleFavourite,
});
@override
State<_ContactActionSheet> createState() => _ContactActionSheetState();
}
class _ContactActionSheetState extends State<_ContactActionSheet> {
late bool _isFavourite;
bool _isUpdatingFavourite = false;
@override
void initState() {
super.initState();
_isFavourite = widget.initialFavourite;
}
Future<void> _toggleFavourite() async {
final callback = widget.onToggleFavourite;
if (callback == null || _isUpdatingFavourite) {
return;
}
setState(() {
_isUpdatingFavourite = true;
});
try {
await callback();
if (!mounted) {
return;
}
setState(() {
_isFavourite = !_isFavourite;
});
} finally {
if (mounted) {
setState(() {
_isUpdatingFavourite = false;
});
}
}
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
final l10n = AppLocalizations.of(context)!;
final contact = widget.contact;
final title = contact.getLocalizedDisplayName(context);
final routeLabel = !contact.routeHasPath || contact.routeHopCount <= 0
? l10n.direct
: contact.routeCanonicalText;
final bottomInset = MediaQuery.of(context).viewPadding.bottom;
return Container(
constraints: BoxConstraints(
maxHeight: MediaQuery.of(context).size.height * 0.88,
),
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(
color: colorScheme.surface,
borderRadius: const BorderRadius.vertical(top: Radius.circular(32)),
boxShadow: [
BoxShadow(
color: colorScheme.shadow.withValues(alpha: 0.12),
blurRadius: 24,
offset: const Offset(0, -4),
),
],
),
child: Material(
color: colorScheme.surface,
child: SingleChildScrollView(
padding: EdgeInsets.fromLTRB(16, 12, 16, 16 + bottomInset),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Center(
child: Container(
width: 44,
height: 4,
decoration: BoxDecoration(
color: colorScheme.outlineVariant,
borderRadius: BorderRadius.circular(999),
),
),
),
const SizedBox(height: 12),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
DecoratedBox(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(24),
boxShadow: [
BoxShadow(
color: colorScheme.shadow.withValues(alpha: 0.08),
blurRadius: 12,
offset: const Offset(0, 4),
),
],
),
child: ContactAvatar(
contact: contact,
radius: 28,
displayName: title,
),
),
const SizedBox(width: 14),
Expanded(
child: Padding(
padding: const EdgeInsets.only(top: 2),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: theme.textTheme.titleLarge?.copyWith(
fontWeight: FontWeight.w900,
letterSpacing: -0.45,
),
),
const SizedBox(height: 4),
Text(
contact.isPublicChannel
? l10n.broadcastToAllNearby
: contact.publicKeyShort,
style: theme.textTheme.bodyMedium?.copyWith(
color: colorScheme.onSurfaceVariant,
fontFamily: contact.isPublicChannel
? null
: 'monospace',
),
),
const SizedBox(height: 10),
Wrap(
spacing: 8,
runSpacing: 8,
children: [
_ContactSheetChip(
icon:
contact.routeHasPath &&
contact.routeHopCount > 0
? Icons.alt_route
: Icons.north_east_rounded,
label: routeLabel,
monospace:
contact.routeHasPath &&
contact.routeHopCount > 0,
),
],
),
],
),
),
),
Row(
mainAxisSize: MainAxisSize.min,
children: [
if (widget.showFavouriteButton)
IconButton.filledTonal(
onPressed: _isUpdatingFavourite
? null
: _toggleFavourite,
tooltip: l10n.favourites,
icon: _isUpdatingFavourite
? SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(
strokeWidth: 2,
color: colorScheme.primary,
),
)
: Icon(
_isFavourite
? Icons.star_rounded
: Icons.star_outline,
color: _isFavourite ? Colors.amber : null,
),
),
if (widget.showFavouriteButton) const SizedBox(width: 8),
IconButton(
onPressed: widget.onClose,
tooltip: l10n.close,
icon: const Icon(Icons.close_rounded),
),
],
),
],
),
if (widget.primaryActions.isNotEmpty) ...[
const SizedBox(height: 20),
LayoutBuilder(
builder: (context, constraints) {
const spacing = 12.0;
const minTileWidth = 104.0;
final actionCount = widget.primaryActions.length;
final maxColumnsByWidth =
((constraints.maxWidth + spacing) /
(minTileWidth + spacing))
.floor()
.clamp(1, 4);
var columnCount = actionCount.clamp(1, maxColumnsByWidth);
if (actionCount > 3 &&
columnCount > 2 &&
actionCount % columnCount == 1) {
columnCount -= 1;
}
final itemWidth =
(constraints.maxWidth - (spacing * (columnCount - 1))) /
columnCount;
return Wrap(
spacing: spacing,
runSpacing: spacing,
children: [
for (final action in widget.primaryActions)
SizedBox(
width: itemWidth,
child: _ContactPrimaryActionButton(action: action),
),
],
);
},
),
],
if (widget.secondaryActions.isNotEmpty) ...[
const SizedBox(height: 20),
Padding(
padding: const EdgeInsets.only(left: 4, bottom: 8),
child: Align(
alignment: Alignment.centerLeft,
child: Text(
l10n.others,
style: theme.textTheme.labelLarge?.copyWith(
color: colorScheme.onSurfaceVariant,
fontWeight: FontWeight.w700,
letterSpacing: 0.2,
),
),
),
),
Container(
decoration: BoxDecoration(
color: colorScheme.surfaceContainerLow,
borderRadius: BorderRadius.circular(24),
border: Border.all(
color: colorScheme.outlineVariant.withValues(alpha: 0.28),
),
),
child: Column(
children: [
for (
var index = 0;
index < widget.secondaryActions.length;
index++
)
_ContactSecondaryActionTile(
action: widget.secondaryActions[index],
showDivider:
index != widget.secondaryActions.length - 1,
),
],
),
),
],
],
),
),
),
);
}
}
class _ContactPrimaryActionButton extends StatelessWidget {
final _ContactSheetAction action;
const _ContactPrimaryActionButton({required this.action});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colorScheme = theme.colorScheme;
final accent = action.destructive ? colorScheme.error : colorScheme.primary;
final backgroundColor = action.destructive
? colorScheme.errorContainer.withValues(alpha: 0.82)
: Color.alphaBlend(
accent.withValues(alpha: 0.12),
colorScheme.surfaceContainerLow,
);
final foregroundColor = action.destructive
? colorScheme.onErrorContainer
: accent;
return Material(
color: Colors.transparent,
child: InkWell(
borderRadius: BorderRadius.circular(18),
onTap: action.enabled ? action.onTap : null,
child: Ink(
height: 80,
decoration: BoxDecoration(
color: backgroundColor,
borderRadius: BorderRadius.circular(18),
border: Border.all(
color: action.destructive
? colorScheme.error.withValues(alpha: 0.18)
: accent.withValues(alpha: 0.14),
),
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
width: 28,
height: 28,
decoration: BoxDecoration(
color: foregroundColor.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(10),
),
child: Icon(action.icon, color: foregroundColor, size: 15),
),
const SizedBox(height: 6),
Text(
action.label,
maxLines: 1,
textAlign: TextAlign.center,
overflow: TextOverflow.ellipsis,
style: theme.textTheme.labelLarge?.copyWith(
color: action.enabled
? (action.destructive
? colorScheme.onErrorContainer
: colorScheme.onSurface)
: colorScheme.onSurfaceVariant,
fontWeight: FontWeight.w800,
letterSpacing: -0.1,
),
),
],
),
),
),
),
);
}
}
class _ContactSecondaryActionTile extends StatelessWidget {
final _ContactSheetAction action;
final bool showDivider;
const _ContactSecondaryActionTile({
required this.action,
required this.showDivider,
});
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
final iconColor = action.enabled
? (action.destructive
? colorScheme.error
: colorScheme.onSurfaceVariant)
: colorScheme.onSurfaceVariant.withValues(alpha: 0.5);
final textColor = action.enabled
? (action.destructive ? colorScheme.error : colorScheme.onSurface)
: colorScheme.onSurfaceVariant;
return Column(
mainAxisSize: MainAxisSize.min,
children: [
ListTile(
enabled: action.enabled,
onTap: action.enabled ? action.onTap : null,
leading: Icon(action.icon, color: iconColor),
title: Text(
action.label,
style: TextStyle(color: textColor, fontWeight: FontWeight.w600),
),
minLeadingWidth: 18,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(18),
),
),
if (showDivider)
Divider(
height: 1,
indent: 56,
endIndent: 16,
color: colorScheme.outlineVariant.withValues(alpha: 0.24),
),
],
);
}
}
class _ContactSheetChip extends StatelessWidget {
final IconData icon;
final String label;
final bool monospace;
const _ContactSheetChip({
required this.icon,
required this.label,
this.monospace = false,
});
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
return Container(
constraints: const BoxConstraints(maxWidth: 220),
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
decoration: BoxDecoration(
color: colorScheme.surfaceContainerHigh,
borderRadius: BorderRadius.circular(999),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, size: 14, color: colorScheme.onSurfaceVariant),
const SizedBox(width: 6),
Flexible(
child: Text(
label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.labelMedium?.copyWith(
color: colorScheme.onSurfaceVariant,
fontWeight: FontWeight.w700,
fontFamily: monospace ? 'monospace' : null,
),
),
),
],
),
);
}
}
class _ContactNameOverrideSheet extends StatefulWidget {
final String initialValue;
final String advertisedName;

View File

@@ -1,8 +1,10 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/gestures.dart';
import 'package:latlong2/latlong.dart';
import 'package:share_plus/share_plus.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../models/contact.dart';
import '../../models/message.dart';
import '../../models/sar_marker.dart';
@@ -31,6 +33,7 @@ import '../../l10n/app_localizations.dart';
import '../../utils/message_extensions.dart';
import '../../utils/log_rx_route_decoder.dart';
import '../../models/message_transfer_details.dart';
import '../../screens/add_contact_screen.dart';
import 'voice_message_bubble.dart';
import 'image_message_bubble.dart';
import 'tictactoe_message_bubble.dart';
@@ -72,9 +75,28 @@ class MessageBubble extends StatefulWidget {
}
class _MessageBubbleState extends State<MessageBubble> {
static const int _meshcoreAdvertMinBytes = 98;
static final RegExp _mentionPattern = RegExp(r'@\[(.+?)\]');
static final RegExp _linkPattern = RegExp(
r'(?:(?:https?:\/\/)|(?:www\.)|(?:meshcore:\/\/))[^\s<]+',
caseSensitive: false,
);
static final RegExp _rawMeshcoreAdvertPattern = RegExp(
r'(?<![0-9a-fA-F])[0-9a-fA-F]{196,}(?![0-9a-fA-F])',
);
static final RegExp _messageTokenPattern = RegExp(
r'@\[(.+?)\]|(?:(?:https?:\/\/)|(?:www\.)|(?:meshcore:\/\/))[^\s<]+|(?<![0-9a-fA-F])[0-9a-fA-F]{196,}(?![0-9a-fA-F])',
caseSensitive: false,
);
bool _isExpanded = false;
bool _showReceivedStats = false;
final List<TapGestureRecognizer> _linkRecognizers = [];
@override
void dispose() {
_disposeLinkRecognizers();
super.dispose();
}
@override
void didUpdateWidget(MessageBubble oldWidget) {
@@ -100,14 +122,108 @@ class _MessageBubbleState extends State<MessageBubble> {
});
}
void _disposeLinkRecognizers() {
for (final recognizer in _linkRecognizers) {
recognizer.dispose();
}
_linkRecognizers.clear();
}
String _trimTrailingUrlPunctuation(String value) {
var trimmed = value;
while (trimmed.isNotEmpty) {
final lastChar = trimmed[trimmed.length - 1];
final shouldTrim = switch (lastChar) {
'.' || ',' || '!' || '?' || ':' || ';' => true,
')' => '('.allMatches(trimmed).length < ')'.allMatches(trimmed).length,
']' => '['.allMatches(trimmed).length < ']'.allMatches(trimmed).length,
'}' => '{'.allMatches(trimmed).length < '}'.allMatches(trimmed).length,
_ => false,
};
if (!shouldTrim) {
break;
}
trimmed = trimmed.substring(0, trimmed.length - 1);
}
return trimmed;
}
Uri? _parseMessageLink(String value) {
final trimmed = _trimTrailingUrlPunctuation(value);
if (trimmed.isEmpty) {
return null;
}
if (_isRawMeshcoreAdvert(trimmed)) {
return Uri.parse('meshcore://$trimmed');
}
final normalized = trimmed.startsWith('www.')
? 'https://$trimmed'
: trimmed;
final uri = Uri.tryParse(normalized);
if (uri == null || !uri.hasScheme || uri.host.isEmpty) {
return null;
}
return uri;
}
bool _isRawMeshcoreAdvert(String value) {
if (!_rawMeshcoreAdvertPattern.hasMatch(value)) {
return false;
}
return value.length.isEven && value.length >= _meshcoreAdvertMinBytes * 2;
}
Future<void> _openMessageLink(String rawUrl) async {
final uri = _parseMessageLink(rawUrl);
if (uri == null) {
ToastLogger.error(context, 'Invalid link');
return;
}
if (uri.scheme.toLowerCase() == 'meshcore') {
if (!mounted) {
return;
}
await Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => AddContactScreen(initialAdvert: rawUrl),
),
);
return;
}
try {
if (!await canLaunchUrl(uri)) {
if (!mounted) {
return;
}
ToastLogger.error(context, 'Cannot open link');
return;
}
await launchUrl(uri, mode: LaunchMode.externalApplication);
} catch (error) {
if (!mounted) {
return;
}
ToastLogger.error(context, 'Failed to open link');
}
}
Widget _buildMessageTextContent(String text, TextStyle? baseBodyStyle) {
final matches = _mentionPattern.allMatches(text).toList();
_disposeLinkRecognizers();
final matches = _messageTokenPattern.allMatches(text).toList();
if (matches.isEmpty) {
return Text(text, style: baseBodyStyle);
}
final textColor =
baseBodyStyle?.color ?? Theme.of(context).colorScheme.onSurface;
final linkColor = Theme.of(context).colorScheme.primary;
final mentionFontSize = (baseBodyStyle?.fontSize ?? 14) - 1;
final backgroundColor = Theme.of(
context,
@@ -129,8 +245,9 @@ class _MessageBubbleState extends State<MessageBubble> {
);
}
final rawMatch = match.group(0) ?? '';
final mentionName = match.group(1)?.trim() ?? '';
if (mentionName.isNotEmpty) {
if (_mentionPattern.hasMatch(rawMatch) && mentionName.isNotEmpty) {
spans.add(
WidgetSpan(
alignment: PlaceholderAlignment.middle,
@@ -154,8 +271,34 @@ class _MessageBubbleState extends State<MessageBubble> {
),
),
);
} else if (_linkPattern.hasMatch(rawMatch) ||
_isRawMeshcoreAdvert(rawMatch)) {
final trimmedUrl = _trimTrailingUrlPunctuation(rawMatch);
final trailingText = rawMatch.substring(trimmedUrl.length);
final uri = _parseMessageLink(rawMatch);
if (uri != null) {
final recognizer = TapGestureRecognizer()
..onTap = () => _openMessageLink(rawMatch);
_linkRecognizers.add(recognizer);
spans.add(
TextSpan(
text: trimmedUrl,
style: baseBodyStyle?.copyWith(
color: linkColor,
decoration: TextDecoration.underline,
decorationColor: linkColor,
),
recognizer: recognizer,
),
);
if (trailingText.isNotEmpty) {
spans.add(TextSpan(text: trailingText, style: baseBodyStyle));
}
} else {
spans.add(TextSpan(text: rawMatch, style: baseBodyStyle));
}
} else {
spans.add(TextSpan(text: match.group(0), style: baseBodyStyle));
spans.add(TextSpan(text: rawMatch, style: baseBodyStyle));
}
cursor = match.end;

View File

@@ -87,6 +87,9 @@ class _RecipientSelectorSheetState extends State<RecipientSelectorSheet> {
return lastSeenCompare;
}
} else if (_sortMode == _RecipientSortMode.activity) {
if (a.isFavourite != b.isFavourite) {
return a.isFavourite ? -1 : 1;
}
final unreadCompare = _unreadFor(b).compareTo(_unreadFor(a));
if (unreadCompare != 0) {
return unreadCompare;
@@ -147,6 +150,32 @@ class _RecipientSelectorSheetState extends State<RecipientSelectorSheet> {
}
}
String _sectionDescription(AppLocalizations l10n, String type) {
switch (type) {
case 'channel':
return 'Broadcast lanes for nearby mesh traffic';
case 'room':
return 'Shared spaces for ongoing team coordination';
case 'contact':
return 'Direct people and devices you can reach';
default:
return '';
}
}
String _channelSubtitle(BuildContext context, Contact channel) {
final l10n = AppLocalizations.of(context)!;
if (channel.isPublicChannel) {
return l10n.broadcastToAllNearby;
}
final channelIdx = channel.publicKey.length > 1 ? channel.publicKey[1] : 0;
final shortKey = channel.publicKeyShort.toUpperCase();
return '${l10n.channel} $channelIdx$shortKey';
}
bool _isDenseSection(String type) => type == 'channel' || type == 'contact';
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
@@ -194,21 +223,45 @@ class _RecipientSelectorSheetState extends State<RecipientSelectorSheet> {
),
const SizedBox(height: 12),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Text(
l10n.selectRecipient,
style: Theme.of(context).textTheme.titleLarge?.copyWith(
fontWeight: FontWeight.w900,
letterSpacing: -0.5,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
l10n.selectRecipient,
style: Theme.of(context).textTheme.titleLarge
?.copyWith(
fontWeight: FontWeight.w900,
letterSpacing: -0.5,
),
),
const SizedBox(height: 4),
Text(
'Pick a channel, room, or direct contact.',
style: Theme.of(context).textTheme.bodyMedium
?.copyWith(color: colorScheme.onSurfaceVariant),
),
],
),
),
const SizedBox(width: 12),
IconButton.filledTonal(
onPressed: () => Navigator.pop(context),
tooltip: l10n.close,
icon: const Icon(Icons.close_rounded),
Container(
decoration: BoxDecoration(
color: colorScheme.surfaceContainerHigh,
borderRadius: BorderRadius.circular(18),
border: Border.all(
color: colorScheme.outlineVariant.withValues(
alpha: 0.18,
),
),
),
child: IconButton(
onPressed: () => Navigator.pop(context),
tooltip: l10n.close,
icon: const Icon(Icons.close_rounded),
),
),
],
),
@@ -278,11 +331,10 @@ class _RecipientSelectorSheetState extends State<RecipientSelectorSheet> {
type: 'channel',
contact: channel,
title: channel.getLocalizedDisplayName(context),
subtitle: channel.isPublicChannel
? l10n.broadcastToAllNearby
: '${l10n.channel} ${channel.publicKey[1]}',
subtitle: _channelSubtitle(context, channel),
unreadCount: _unreadFor(channel),
isSelected: _isSelected('channel', channel),
compact: true,
onTap: () {
widget.onSelect('channel', channel);
Navigator.pop(context);
@@ -308,6 +360,7 @@ class _RecipientSelectorSheetState extends State<RecipientSelectorSheet> {
subtitle: contact.publicKeyShort,
unreadCount: _unreadFor(contact),
isSelected: _isSelected('contact', contact),
compact: true,
onTap: () {
widget.onSelect('contact', contact);
Navigator.pop(context);
@@ -455,10 +508,11 @@ class _RecipientSelectorSheetState extends State<RecipientSelectorSheet> {
}) {
final colorScheme = Theme.of(context).colorScheme;
final accentColor = _sectionColor(context, type);
final compact = _isDenseSection(type);
return Container(
margin: const EdgeInsets.only(bottom: 12),
padding: const EdgeInsets.all(14),
padding: EdgeInsets.all(compact ? 12 : 14),
decoration: BoxDecoration(
color: colorScheme.surfaceContainerLow,
borderRadius: BorderRadius.circular(24),
@@ -470,16 +524,16 @@ class _RecipientSelectorSheetState extends State<RecipientSelectorSheet> {
Row(
children: [
Container(
width: 38,
height: 38,
width: compact ? 34 : 38,
height: compact ? 34 : 38,
decoration: BoxDecoration(
color: accentColor.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(12),
),
alignment: Alignment.center,
child: Icon(icon, size: 18, color: accentColor),
child: Icon(icon, size: compact ? 16 : 18, color: accentColor),
),
const SizedBox(width: 10),
SizedBox(width: compact ? 8 : 10),
Expanded(
child: Text(
title,
@@ -490,9 +544,9 @@ class _RecipientSelectorSheetState extends State<RecipientSelectorSheet> {
),
),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 10,
vertical: 5,
padding: EdgeInsets.symmetric(
horizontal: compact ? 9 : 10,
vertical: compact ? 4 : 5,
),
decoration: BoxDecoration(
color: colorScheme.surface,
@@ -511,7 +565,14 @@ class _RecipientSelectorSheetState extends State<RecipientSelectorSheet> {
),
],
),
const SizedBox(height: 12),
const SizedBox(height: 8),
Text(
_sectionDescription(AppLocalizations.of(context)!, type),
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
SizedBox(height: compact ? 10 : 12),
if (children.isEmpty)
Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
@@ -526,7 +587,7 @@ class _RecipientSelectorSheetState extends State<RecipientSelectorSheet> {
else ...[
for (var i = 0; i < children.length; i++) ...[
children[i],
if (i != children.length - 1) const SizedBox(height: 8),
if (i != children.length - 1) SizedBox(height: compact ? 6 : 8),
],
],
],
@@ -623,6 +684,7 @@ class _RecipientSelectorSheetState extends State<RecipientSelectorSheet> {
required String subtitle,
required int unreadCount,
required bool isSelected,
bool compact = false,
required VoidCallback onTap,
}) {
final colorScheme = Theme.of(context).colorScheme;
@@ -631,14 +693,14 @@ class _RecipientSelectorSheetState extends State<RecipientSelectorSheet> {
return Material(
color: Colors.transparent,
child: InkWell(
borderRadius: BorderRadius.circular(20),
borderRadius: BorderRadius.circular(compact ? 18 : 20),
onTap: onTap,
child: Ink(
decoration: BoxDecoration(
color: isSelected
? accentColor.withValues(alpha: 0.12)
: colorScheme.surface.withValues(alpha: 0.82),
borderRadius: BorderRadius.circular(20),
borderRadius: BorderRadius.circular(compact ? 18 : 20),
border: Border.all(
color: isSelected
? accentColor.withValues(alpha: 0.24)
@@ -646,7 +708,7 @@ class _RecipientSelectorSheetState extends State<RecipientSelectorSheet> {
),
),
child: Padding(
padding: const EdgeInsets.all(12),
padding: EdgeInsets.all(compact ? 10 : 12),
child: Row(
children: [
Stack(
@@ -654,15 +716,15 @@ class _RecipientSelectorSheetState extends State<RecipientSelectorSheet> {
children: [
ContactAvatar(
contact: contact,
radius: 22,
radius: compact ? 20 : 22,
displayName: title,
),
Positioned(
right: -3,
bottom: -3,
child: Container(
width: 18,
height: 18,
width: compact ? 16 : 18,
height: compact ? 16 : 18,
decoration: BoxDecoration(
color: colorScheme.surface,
shape: BoxShape.circle,
@@ -673,28 +735,56 @@ class _RecipientSelectorSheetState extends State<RecipientSelectorSheet> {
alignment: Alignment.center,
child: Icon(
_typeIcon(contact),
size: 10,
size: compact ? 9 : 10,
color: accentColor,
),
),
),
],
),
const SizedBox(width: 12),
SizedBox(width: compact ? 10 : 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w800,
letterSpacing: -0.2,
),
Row(
children: [
Flexible(
child: Text(
title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.titleSmall
?.copyWith(
fontWeight: FontWeight.w800,
letterSpacing: -0.2,
),
),
),
if (contact.isPublicChannel) ...[
SizedBox(width: compact ? 6 : 8),
Container(
padding: EdgeInsets.symmetric(
horizontal: compact ? 7 : 8,
vertical: compact ? 2 : 3,
),
decoration: BoxDecoration(
color: accentColor.withValues(alpha: 0.10),
borderRadius: BorderRadius.circular(999),
),
child: Text(
'Public',
style: Theme.of(context).textTheme.labelSmall
?.copyWith(
color: accentColor,
fontWeight: FontWeight.w800,
),
),
),
],
],
),
const SizedBox(height: 4),
SizedBox(height: compact ? 2 : 4),
Text(
subtitle,
maxLines: 1,
@@ -707,7 +797,7 @@ class _RecipientSelectorSheetState extends State<RecipientSelectorSheet> {
],
),
),
const SizedBox(width: 10),
SizedBox(width: compact ? 8 : 10),
_buildTrailing(
context,
unreadCount: unreadCount,

View File

@@ -0,0 +1,819 @@
import 'dart:async';
import 'dart:math' as math;
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:meshcore_client/meshcore_client.dart' show Message;
import 'package:provider/provider.dart';
import '../../models/contact.dart';
import '../../providers/connection_provider.dart';
import '../../services/bthome_met_history.dart';
Future<void> showBTHomeMetHistorySheet(
BuildContext context, {
required Contact contact,
}) {
return showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
showDragHandle: true,
builder: (sheetContext) => _BTHomeMetHistorySheet(contact: contact),
);
}
class _BTHomeMetHistorySheet extends StatefulWidget {
const _BTHomeMetHistorySheet({required this.contact});
final Contact contact;
@override
State<_BTHomeMetHistorySheet> createState() => _BTHomeMetHistorySheetState();
}
class _BTHomeMetHistorySheetState extends State<_BTHomeMetHistorySheet> {
late final List<BTHomeMetMeasurement> _availableMeasurements;
late BTHomeMetMeasurement _selectedMeasurement;
BTHomeMetHistoryPage? _history;
bool _loading = true;
String? _error;
@override
void initState() {
super.initState();
_availableMeasurements = bTHomeMetMeasurementsForContact(widget.contact);
_selectedMeasurement = _availableMeasurements.isEmpty
? BTHomeMetMeasurement.temperature
: _availableMeasurements.first;
if (_availableMeasurements.isEmpty) {
_loading = false;
_error = 'No BTHome MET-compatible telemetry is available for this node.';
return;
}
unawaited(_loadHistory(measurement: _selectedMeasurement, page: 0));
}
Future<void> _loadHistory({
required BTHomeMetMeasurement measurement,
required int page,
}) async {
final connectionProvider = context.read<ConnectionProvider>();
final previousOnMessageReceived = connectionProvider.onMessageReceived;
String? responseText;
void onMessage(Message message) {
previousOnMessageReceived?.call(message);
if (_matchesContact(message)) {
responseText = message.text;
}
}
connectionProvider.onMessageReceived = onMessage;
if (mounted) {
setState(() {
_loading = true;
_error = null;
});
}
try {
final sent = await connectionProvider.sendTextMessage(
contactPublicKey: widget.contact.publicKey,
text: 'bthome met history ${measurement.id} $page',
);
if (!sent) {
throw Exception('Failed to send MET history request.');
}
for (var i = 0; i < 30; i++) {
await Future.delayed(const Duration(milliseconds: 500));
if (responseText != null) {
break;
}
}
final text = responseText?.trim();
if (text == null || text.isEmpty) {
throw TimeoutException('No response from sensor.');
}
if (_looksLikeError(text)) {
throw Exception(text);
}
final history = BTHomeMetHistoryParser.parse(text);
if (!mounted) {
return;
}
setState(() {
_selectedMeasurement = measurement;
_history = history;
_loading = false;
_error = null;
});
} catch (error) {
if (!mounted) {
return;
}
setState(() {
_selectedMeasurement = measurement;
_history = null;
_loading = false;
_error = _formatError(error);
});
} finally {
if (identical(connectionProvider.onMessageReceived, onMessage)) {
connectionProvider.onMessageReceived = previousOnMessageReceived;
}
}
}
bool _matchesContact(Message message) {
final prefix = message.senderPublicKeyPrefix;
if (prefix == null ||
prefix.length < 6 ||
widget.contact.publicKey.length < 6) {
return false;
}
for (var i = 0; i < 6; i++) {
if (prefix[i] != widget.contact.publicKey[i]) {
return false;
}
}
return true;
}
bool _looksLikeError(String text) {
final lower = text.toLowerCase();
return lower.startsWith('err') ||
lower.contains('unknown') ||
lower.contains('unsupported');
}
String _formatError(Object error) {
if (error is TimeoutException) {
return error.message ?? 'Timed out waiting for MET history.';
}
return error.toString().replaceFirst('Exception: ', '');
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final height = MediaQuery.of(context).size.height * 0.8;
final history = _history;
return SafeArea(
child: SizedBox(
height: height,
child: Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'MET history',
style: theme.textTheme.titleLarge?.copyWith(
fontWeight: FontWeight.w700,
),
),
Text(
widget.contact.displayName,
style: theme.textTheme.bodyMedium?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
],
),
),
IconButton(
onPressed: () => Navigator.of(context).pop(),
icon: const Icon(Icons.close),
),
],
),
const SizedBox(height: 12),
Wrap(
spacing: 8,
runSpacing: 8,
children: _availableMeasurements
.map(
(measurement) => ChoiceChip(
label: Text(measurement.label),
selected: measurement == _selectedMeasurement,
onSelected: (selected) {
if (!selected || _loading) {
return;
}
unawaited(
_loadHistory(measurement: measurement, page: 0),
);
},
),
)
.toList(growable: false),
),
const SizedBox(height: 16),
Row(
children: [
OutlinedButton.icon(
onPressed: _loading || (history?.page ?? 0) == 0
? null
: () => unawaited(
_loadHistory(
measurement: _selectedMeasurement,
page: history!.page - 1,
),
),
icon: const Icon(Icons.chevron_left),
label: const Text('Newer'),
),
const SizedBox(width: 8),
OutlinedButton.icon(
onPressed:
_loading ||
history == null ||
history.values.length < 12
? null
: () => unawaited(
_loadHistory(
measurement: _selectedMeasurement,
page: history.page + 1,
),
),
icon: const Icon(Icons.chevron_right),
label: const Text('Older'),
),
const Spacer(),
if (_loading)
const SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(strokeWidth: 2),
)
else
Text(
'Page ${history?.page ?? 0}',
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
],
),
const SizedBox(height: 12),
Expanded(
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (_error != null)
_HistoryMessageCard(
icon: Icons.error_outline,
title: 'Could not load MET history',
body: _error!,
)
else if (_loading && history == null)
const _HistoryMessageCard(
icon: Icons.hourglass_top,
title: 'Loading',
body: 'Waiting for the sensor to reply.',
)
else if (history != null) ...[
_HistoryChartCard(history: history),
const SizedBox(height: 12),
_HistoryStatsGrid(history: history),
const SizedBox(height: 12),
_HistorySamplesCard(history: history),
],
],
),
),
),
],
),
),
),
);
}
}
class _HistoryChartCard extends StatelessWidget {
const _HistoryChartCard({required this.history});
final BTHomeMetHistoryPage history;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Container(
width: double.infinity,
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerLow,
borderRadius: BorderRadius.circular(24),
border: Border.all(
color: theme.colorScheme.outlineVariant.withValues(alpha: 0.4),
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
history.measurement.label,
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 4),
Text(
'Samples are shown oldest to newest. Firmware replies do not include timestamps.',
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 16),
SizedBox(
height: 180,
child: LineChart(_historyLineChartData(context, history: history)),
),
],
),
);
}
}
class _HistoryStatsGrid extends StatelessWidget {
const _HistoryStatsGrid({required this.history});
final BTHomeMetHistoryPage history;
@override
Widget build(BuildContext context) {
final measurement = history.measurement;
return LayoutBuilder(
builder: (context, constraints) {
final compact = constraints.maxWidth < 520;
final tiles = <Widget>[
_HistoryStatTile(
label: 'Latest',
value: _formatMeasurementValue(measurement, history.latest),
),
_HistoryStatTile(
label: 'Min',
value: _formatMeasurementValue(measurement, history.minimum),
),
_HistoryStatTile(
label: 'Max',
value: _formatMeasurementValue(measurement, history.maximum),
),
_HistoryStatTile(
label: 'Samples',
value: history.values.length.toString(),
),
];
if (compact) {
return Column(
children: [
Row(
children: [
Expanded(child: tiles[0]),
const SizedBox(width: 8),
Expanded(child: tiles[1]),
],
),
const SizedBox(height: 8),
Row(
children: [
Expanded(child: tiles[2]),
const SizedBox(width: 8),
Expanded(child: tiles[3]),
],
),
],
);
}
return Row(
children: [
Expanded(child: tiles[0]),
const SizedBox(width: 8),
Expanded(child: tiles[1]),
const SizedBox(width: 8),
Expanded(child: tiles[2]),
const SizedBox(width: 8),
Expanded(child: tiles[3]),
],
);
},
);
}
}
class _HistoryStatTile extends StatelessWidget {
const _HistoryStatTile({required this.label, required this.value});
final String label;
final String value;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.5),
borderRadius: BorderRadius.circular(18),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
label,
style: theme.textTheme.labelMedium?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: 4),
Text(
value,
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
],
),
);
}
}
class _HistorySamplesCard extends StatelessWidget {
const _HistorySamplesCard({required this.history});
final BTHomeMetHistoryPage history;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Container(
width: double.infinity,
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerLow,
borderRadius: BorderRadius.circular(24),
border: Border.all(
color: theme.colorScheme.outlineVariant.withValues(alpha: 0.4),
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Samples',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 10),
Wrap(
spacing: 8,
runSpacing: 8,
children: history.values
.asMap()
.entries
.map((entry) {
final sampleIndex = entry.key + 1;
final isLatest = entry.key == history.values.length - 1;
return Container(
padding: const EdgeInsets.symmetric(
horizontal: 10,
vertical: 8,
),
decoration: BoxDecoration(
color: isLatest
? _historyColor(
history.measurement,
).withValues(alpha: 0.12)
: theme.colorScheme.surfaceContainerHighest
.withValues(alpha: 0.45),
borderRadius: BorderRadius.circular(14),
),
child: Text(
'$sampleIndex. ${_formatMeasurementValue(history.measurement, entry.value)}${isLatest ? ' latest' : ''}',
style: theme.textTheme.bodyMedium?.copyWith(
fontWeight: isLatest
? FontWeight.w700
: FontWeight.w500,
),
),
);
})
.toList(growable: false),
),
],
),
);
}
}
class _HistoryMessageCard extends StatelessWidget {
const _HistoryMessageCard({
required this.icon,
required this.title,
required this.body,
});
final IconData icon;
final String title;
final String body;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Container(
width: double.infinity,
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerLow,
borderRadius: BorderRadius.circular(24),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(icon, color: theme.colorScheme.primary),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 4),
Text(body),
],
),
),
],
),
);
}
}
Color _historyColor(BTHomeMetMeasurement measurement) {
switch (measurement) {
case BTHomeMetMeasurement.temperature:
return const Color(0xFFC76821);
case BTHomeMetMeasurement.humidity:
return const Color(0xFF246BB2);
case BTHomeMetMeasurement.windSpeed:
return const Color(0xFF2B78A0);
case BTHomeMetMeasurement.gust:
return const Color(0xFF1E88A8);
case BTHomeMetMeasurement.rain:
return const Color(0xFF2C6BA0);
}
}
String _formatMeasurementValue(BTHomeMetMeasurement measurement, num? value) {
if (value == null) {
return '--';
}
final digits = switch (measurement) {
BTHomeMetMeasurement.humidity => 0,
BTHomeMetMeasurement.temperature => 1,
BTHomeMetMeasurement.windSpeed => 1,
BTHomeMetMeasurement.gust => 1,
BTHomeMetMeasurement.rain => 1,
};
final text = value
.toStringAsFixed(digits)
.replaceFirst(RegExp(r'\.?0+$'), '');
return '$text${measurement.unit}';
}
LineChartData _historyLineChartData(
BuildContext context, {
required BTHomeMetHistoryPage history,
}) {
final theme = Theme.of(context);
final color = _historyColor(history.measurement);
final values = history.values;
final spots = values
.asMap()
.entries
.map((entry) => FlSpot(entry.key.toDouble(), entry.value))
.toList(growable: false);
final chartMinY = _historyChartMinY(history);
final chartMaxY = _historyChartMaxY(history);
final yInterval = _historyYAxisInterval(
measurement: history.measurement,
minY: chartMinY,
maxY: chartMaxY,
);
return LineChartData(
minX: 0,
maxX: values.length <= 1 ? 1.0 : (values.length - 1).toDouble(),
minY: chartMinY,
maxY: chartMaxY,
clipData: const FlClipData.all(),
lineTouchData: const LineTouchData(enabled: false),
gridData: FlGridData(
show: true,
drawVerticalLine: false,
horizontalInterval: yInterval,
getDrawingHorizontalLine: (value) => FlLine(
color: theme.colorScheme.outlineVariant.withValues(alpha: 0.28),
strokeWidth: 1,
),
),
borderData: FlBorderData(show: false),
titlesData: FlTitlesData(
topTitles: const AxisTitles(sideTitles: SideTitles(showTitles: false)),
rightTitles: const AxisTitles(sideTitles: SideTitles(showTitles: false)),
leftTitles: AxisTitles(
sideTitles: SideTitles(
showTitles: true,
reservedSize: 42,
interval: yInterval,
getTitlesWidget: (value, meta) => SideTitleWidget(
meta: meta,
space: 8,
child: Text(
_formatHistoryAxisValue(history.measurement, value),
style: Theme.of(context).textTheme.labelSmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
fontWeight: FontWeight.w600,
),
),
),
),
),
bottomTitles: AxisTitles(
sideTitles: SideTitles(
showTitles: true,
reservedSize: 24,
interval: 1,
getTitlesWidget: (value, meta) {
final index = value.round();
if (value != index.toDouble() ||
!_shouldShowBottomSampleLabel(index, values.length)) {
return const SizedBox.shrink();
}
return SideTitleWidget(
meta: meta,
space: 6,
child: Text(
'${index + 1}',
style: Theme.of(context).textTheme.labelSmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
fontWeight: FontWeight.w600,
),
),
);
},
),
),
),
lineBarsData: [
LineChartBarData(
spots: spots,
color: color,
barWidth: 2.8,
isCurved: false,
isStrokeCapRound: true,
dotData: FlDotData(
show: true,
checkToShowDot: (spot, barData) =>
barData.spots.length <= 10 || spot == barData.spots.last,
getDotPainter: (spot, percent, barData, index) => FlDotCirclePainter(
radius: spot == barData.spots.last ? 4 : 2.5,
color: color,
strokeColor: theme.colorScheme.surface,
strokeWidth: 1.6,
),
),
belowBarData: BarAreaData(
show: true,
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
color.withValues(alpha: 0.24),
color.withValues(alpha: 0.03),
],
),
),
),
],
);
}
double _historyChartMinY(BTHomeMetHistoryPage history) {
final minValue = history.minimum ?? 0;
final maxValue = history.maximum ?? 0;
final spread = maxValue - minValue;
final padding = spread == 0
? _historyMinimumPadding(history.measurement, minValue)
: math.max(
spread * 0.18,
_historyMinimumPadding(history.measurement, minValue),
);
return minValue - padding;
}
double _historyChartMaxY(BTHomeMetHistoryPage history) {
final minValue = history.minimum ?? 0;
final maxValue = history.maximum ?? 0;
final spread = maxValue - minValue;
final padding = spread == 0
? _historyMinimumPadding(history.measurement, maxValue)
: math.max(
spread * 0.18,
_historyMinimumPadding(history.measurement, maxValue),
);
return maxValue + padding;
}
double _historyMinimumPadding(
BTHomeMetMeasurement measurement,
double reference,
) {
final scaled = math.max(reference.abs() * 0.05, 0.1);
return switch (measurement) {
BTHomeMetMeasurement.temperature => math.max(0.4, scaled),
BTHomeMetMeasurement.humidity => math.max(2.0, scaled),
BTHomeMetMeasurement.windSpeed => math.max(0.4, scaled),
BTHomeMetMeasurement.gust => math.max(0.4, scaled),
BTHomeMetMeasurement.rain => math.max(0.4, scaled),
};
}
double _historyYAxisInterval({
required BTHomeMetMeasurement measurement,
required double minY,
required double maxY,
}) {
final span = maxY - minY;
if (span <= 0) {
return 1;
}
final rough = span / 3;
return switch (measurement) {
BTHomeMetMeasurement.humidity => math.max(1, rough.round()).toDouble(),
BTHomeMetMeasurement.temperature => _niceStep(rough, minStep: 0.5),
BTHomeMetMeasurement.windSpeed => _niceStep(rough, minStep: 0.5),
BTHomeMetMeasurement.gust => _niceStep(rough, minStep: 0.5),
BTHomeMetMeasurement.rain => _niceStep(rough, minStep: 0.5),
};
}
double _niceStep(double value, {required double minStep}) {
if (value <= minStep) {
return minStep;
}
final exponent = math
.pow(10.0, (math.log(value) / math.ln10).floor())
.toDouble();
final normalized = value / exponent;
final stepped = switch (normalized) {
< 1.5 => 1.0,
< 3.0 => 2.0,
< 7.0 => 5.0,
_ => 10.0,
};
return math.max(minStep, stepped * exponent);
}
String _formatHistoryAxisValue(BTHomeMetMeasurement measurement, double value) {
final digits = measurement == BTHomeMetMeasurement.humidity ? 0 : 1;
return value.toStringAsFixed(digits).replaceFirst(RegExp(r'\.?0+$'), '');
}
bool _shouldShowBottomSampleLabel(int index, int sampleCount) {
if (index < 0 || index >= sampleCount) {
return false;
}
if (sampleCount <= 3) {
return true;
}
final middle = (sampleCount - 1) ~/ 2;
return index == 0 || index == middle || index == sampleCount - 1;
}

View File

@@ -1,12 +1,14 @@
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_map/flutter_map.dart' as flutter_map;
import 'package:latlong2/latlong.dart';
import '../../l10n/app_localizations.dart';
import '../../models/contact.dart';
import '../../providers/sensors_provider.dart';
import '../../services/bthome_met_history.dart';
import '../../utils/location_formats.dart';
class SensorMetricOption {
@@ -546,12 +548,15 @@ SensorMetricCardData? _buildOptionPreviewCardData(
fieldKey: fieldKey,
icon: Icons.explore_outlined,
label: label,
value: previewValue,
value: degrees == null
? previewValue
: '${_formatPreviewNumber(degrees, maxFractionDigits: 0)}°',
secondaryValue: degrees == null
? null
: _previewFormatCardinalDirection(degrees),
accent: const Color(0xFF8A5A44),
channel: metricKey.channel,
directionDegrees: degrees,
);
case 'unixtime':
return SensorMetricCardData(
@@ -1006,6 +1011,13 @@ String _formatPreviewNumber(num value, {int maxFractionDigits = 2}) {
? math.min(maxFractionDigits, 1)
: maxFractionDigits;
final text = value.toStringAsFixed(digits);
return _trimFractionZeros(text);
}
String _trimFractionZeros(String text) {
if (!text.contains('.')) {
return text;
}
return text.replaceFirst(RegExp(r'\.?0+$'), '');
}
@@ -1028,6 +1040,9 @@ class SensorTelemetryCard extends StatelessWidget {
final Future<void> Function()? onRemove;
final Future<void> Function()? onRefresh;
final VoidCallback? onCustomize;
final Future<void> Function(Contact contact)? onShowMetHistory;
final Future<void> Function()? onMoveUp;
final Future<void> Function()? onMoveDown;
final EdgeInsetsGeometry margin;
final String emptyMetricsMessage;
final Map<String, String> labelOverrides;
@@ -1042,6 +1057,9 @@ class SensorTelemetryCard extends StatelessWidget {
this.onRemove,
this.onRefresh,
this.onCustomize,
this.onShowMetHistory,
this.onMoveUp,
this.onMoveDown,
this.margin = const EdgeInsets.only(bottom: 16),
this.emptyMetricsMessage =
'All fields are hidden. Use Visible fields to choose what to show.',
@@ -1049,7 +1067,15 @@ class SensorTelemetryCard extends StatelessWidget {
});
bool get _showsMenu =>
onRefresh != null || onCustomize != null || onRemove != null;
onRefresh != null ||
onCustomize != null ||
onRemove != null ||
onMoveUp != null ||
onMoveDown != null ||
_rawTelemetryHex(contact?.telemetry) != null ||
(contact != null &&
onShowMetHistory != null &&
supportsBTHomeMetHistory(contact));
@override
Widget build(BuildContext context) {
@@ -1128,21 +1154,21 @@ class SensorTelemetryCard extends StatelessWidget {
),
if (state == SensorRefreshState.refreshing)
_InlineStateMeta(
label: l10n.refreshing,
color: Color(0xFF266AC2),
spinning: true,
tooltip: l10n.refreshing,
),
if (state == SensorRefreshState.success)
const _InlineStateMeta(
label: 'Updated',
color: Color(0xFF218B63),
icon: Icons.check_circle,
tooltip: 'Updated',
),
if (state == SensorRefreshState.unavailable)
_InlineStateMeta(
label: l10n.unavailable,
color: Color(0xFFB13B55),
icon: Icons.error_outline,
tooltip: l10n.unavailable,
),
],
),
@@ -1155,10 +1181,34 @@ class SensorTelemetryCard extends StatelessWidget {
onSelected: (value) async {
if (value == 'refresh' && onRefresh != null) {
await onRefresh!();
} else if (value == 'move_up' && onMoveUp != null) {
await onMoveUp!();
} else if (value == 'move_down' && onMoveDown != null) {
await onMoveDown!();
} else if (value == 'copy_raw') {
final rawTelemetry = _rawTelemetryHex(
contact?.telemetry,
);
if (rawTelemetry != null && context.mounted) {
await Clipboard.setData(
ClipboardData(text: rawTelemetry),
);
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Raw response copied'),
),
);
}
}
} else if (value == 'remove' && onRemove != null) {
await onRemove!();
} else if (value == 'customize' && onCustomize != null) {
onCustomize!();
} else if (value == 'met_history' &&
contact != null &&
onShowMetHistory != null) {
await onShowMetHistory!(contact!);
}
},
itemBuilder: (context) {
@@ -1171,6 +1221,30 @@ class SensorTelemetryCard extends StatelessWidget {
),
);
}
if (onMoveUp != null) {
items.add(
const PopupMenuItem<String>(
value: 'move_up',
child: Text('Move up'),
),
);
}
if (onMoveDown != null) {
items.add(
const PopupMenuItem<String>(
value: 'move_down',
child: Text('Move down'),
),
);
}
if (_rawTelemetryHex(contact?.telemetry) != null) {
items.add(
const PopupMenuItem<String>(
value: 'copy_raw',
child: Text('Copy raw response'),
),
);
}
if (onCustomize != null) {
items.add(
PopupMenuItem<String>(
@@ -1179,6 +1253,16 @@ class SensorTelemetryCard extends StatelessWidget {
),
);
}
if (contact != null &&
onShowMetHistory != null &&
supportsBTHomeMetHistory(contact)) {
items.add(
const PopupMenuItem<String>(
value: 'met_history',
child: Text('MET history'),
),
);
}
if (onRemove != null) {
items.add(
PopupMenuItem<String>(
@@ -1221,6 +1305,11 @@ class SensorTelemetryCard extends StatelessWidget {
metric.wide)
? constraints.maxWidth
: compactWidth,
onLongPress: onRefresh == null
? null
: () async {
await onRefresh!();
},
),
)
.toList(),
@@ -1784,10 +1873,11 @@ class SensorTelemetryCard extends StatelessWidget {
fieldKey: _extraFieldKey(rawKey),
icon: Icons.explore_outlined,
label: label,
value: '${_formatNumber(degrees, maxFractionDigits: 0)} deg',
value: '${_formatNumber(degrees, maxFractionDigits: 0)}°',
secondaryValue: _formatCardinalDirection(degrees),
accent: const Color(0xFF8A5A44),
channel: metricKey.channel,
directionDegrees: degrees,
);
case 'rotation':
@@ -2027,7 +2117,7 @@ class SensorTelemetryCard extends StatelessWidget {
? math.min(maxFractionDigits, 1)
: maxFractionDigits;
final text = value.toStringAsFixed(digits);
return text.replaceFirst(RegExp(r'\.?0+$'), '');
return _trimFractionZeros(text);
}
_Vector3? _asVector3(dynamic value) {
@@ -2091,31 +2181,28 @@ class SensorTelemetryCard extends StatelessWidget {
}
class _InlineStateMeta extends StatelessWidget {
final String label;
final Color color;
final IconData? icon;
final bool spinning;
final String? tooltip;
const _InlineStateMeta({
required this.label,
required this.color,
this.icon,
this.spinning = false,
this.tooltip,
});
@override
Widget build(BuildContext context) {
return Container(
final badge = Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
decoration: BoxDecoration(
color: color.withValues(alpha: 0.10),
borderRadius: BorderRadius.circular(999),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (spinning)
SizedBox(
child: spinning
? SizedBox(
width: 11,
height: 11,
child: CircularProgressIndicator(
@@ -2123,18 +2210,20 @@ class _InlineStateMeta extends StatelessWidget {
valueColor: AlwaysStoppedAnimation<Color>(color),
),
)
else if (icon != null)
Icon(icon, size: 11, color: color),
const SizedBox(width: 4),
Text(
label,
style: Theme.of(context).textTheme.labelSmall?.copyWith(
: Icon(
icon ?? Icons.info_outline,
size: 11,
color: color,
fontWeight: FontWeight.w700,
),
),
],
),
);
if (tooltip == null || tooltip!.isEmpty) {
return badge;
}
return Tooltip(
message: tooltip!,
child: badge,
);
}
}
@@ -2168,6 +2257,7 @@ class SensorMetricTile extends StatelessWidget {
final double width;
final String keyPrefix;
final bool allowMapPreview;
final GestureLongPressCallback? onLongPress;
const SensorMetricTile({
super.key,
@@ -2175,6 +2265,7 @@ class SensorMetricTile extends StatelessWidget {
required this.width,
this.keyPrefix = 'sensor_metric',
this.allowMapPreview = true,
this.onLongPress,
});
Future<void> _showExpandedMap(BuildContext context) async {
@@ -2249,142 +2340,185 @@ class SensorMetricTile extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
key: ValueKey('${keyPrefix}_${data.fieldKey}'),
width: width,
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: data.accent.withValues(alpha: 0.08),
return Material(
color: Colors.transparent,
child: InkWell(
key: ValueKey('${keyPrefix}_${data.fieldKey}'),
borderRadius: BorderRadius.circular(22),
border: Border.all(color: data.accent.withValues(alpha: 0.14)),
),
child: data.mapLocation == null || !allowMapPreview
? Stack(
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
onLongPress: onLongPress,
child: Container(
width: width,
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: data.accent.withValues(alpha: 0.08),
borderRadius: BorderRadius.circular(22),
border: Border.all(color: data.accent.withValues(alpha: 0.14)),
),
child: data.directionDegrees != null
? Stack(
children: [
_MetricIcon(accent: data.accent, icon: data.icon),
const SizedBox(width: 10),
Expanded(
child: _MetricText(data: data, keyPrefix: keyPrefix),
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
_DirectionDial(
accent: data.accent,
degrees: data.directionDegrees!,
cardinal: data.secondaryValue ?? '',
compact: true,
),
const SizedBox(width: 10),
Expanded(
child: _MetricText(data: data, keyPrefix: keyPrefix),
),
],
),
],
),
if (data.channel != null)
Positioned(
right: 0,
bottom: 0,
child: Text(
'ch${data.channel}',
style: TextStyle(
fontSize: 9,
fontWeight: FontWeight.w700,
color: data.accent.withValues(alpha: 0.5),
if (data.channel != null)
Positioned(
right: 0,
bottom: 0,
child: Text(
'ch${data.channel}',
style: TextStyle(
fontSize: 9,
fontWeight: FontWeight.w700,
color: data.accent.withValues(alpha: 0.5),
),
),
),
],
)
: data.mapLocation == null || !allowMapPreview
? Stack(
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_MetricIcon(accent: data.accent, icon: data.icon),
const SizedBox(width: 10),
Expanded(
child: _MetricText(data: data, keyPrefix: keyPrefix),
),
],
),
),
],
)
: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
if (data.channel != null)
Positioned(
right: 0,
bottom: 0,
child: Text(
'ch${data.channel}',
style: TextStyle(
fontSize: 9,
fontWeight: FontWeight.w700,
color: data.accent.withValues(alpha: 0.5),
),
),
),
],
)
: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_MetricIcon(accent: data.accent, icon: data.icon),
const SizedBox(width: 10),
Expanded(
child: _MetricText(data: data, keyPrefix: keyPrefix),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_MetricIcon(accent: data.accent, icon: data.icon),
const SizedBox(width: 10),
Expanded(
child: _MetricText(data: data, keyPrefix: keyPrefix),
),
],
),
],
),
const SizedBox(height: 10),
Material(
color: Colors.transparent,
child: InkWell(
borderRadius: BorderRadius.circular(14),
onTap: () => _showExpandedMap(context),
child: ClipRRect(
borderRadius: BorderRadius.circular(14),
child: SizedBox(
height: 104,
width: double.infinity,
child: Stack(
children: [
flutter_map.FlutterMap(
options: flutter_map.MapOptions(
initialCenter: data.mapLocation!,
initialZoom: 14,
interactionOptions:
const flutter_map.InteractionOptions(
flags: flutter_map.InteractiveFlag.none,
),
),
const SizedBox(height: 10),
Material(
color: Colors.transparent,
child: InkWell(
borderRadius: BorderRadius.circular(14),
onTap: () => _showExpandedMap(context),
child: ClipRRect(
borderRadius: BorderRadius.circular(14),
child: SizedBox(
height: 104,
width: double.infinity,
child: Stack(
children: [
flutter_map.TileLayer(
urlTemplate:
'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
userAgentPackageName:
'com.meshcore.sar.meshcore_sar_app',
),
flutter_map.MarkerLayer(
markers: [
flutter_map.Marker(
point: data.mapLocation!,
width: 32,
height: 32,
child: Icon(
Icons.location_on,
color: data.accent,
size: 28,
),
flutter_map.FlutterMap(
options: flutter_map.MapOptions(
initialCenter: data.mapLocation!,
initialZoom: 14,
interactionOptions:
const flutter_map.InteractionOptions(
flags:
flutter_map.InteractiveFlag.none,
),
),
children: [
flutter_map.TileLayer(
urlTemplate:
'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
userAgentPackageName:
'com.meshcore.sar.meshcore_sar_app',
),
flutter_map.MarkerLayer(
markers: [
flutter_map.Marker(
point: data.mapLocation!,
width: 32,
height: 32,
child: Icon(
Icons.location_on,
color: data.accent,
size: 28,
),
),
],
),
],
),
Positioned(
right: 8,
bottom: 8,
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 6,
vertical: 3,
),
decoration: BoxDecoration(
color: Colors.black.withValues(
alpha: 0.55,
),
borderRadius: BorderRadius.circular(999),
),
child: const Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.open_in_full,
size: 12,
color: Colors.white,
),
SizedBox(width: 4),
Text(
'Open map',
style: TextStyle(
color: Colors.white,
fontSize: 11,
fontWeight: FontWeight.w600,
),
),
],
),
),
),
],
),
Positioned(
right: 8,
bottom: 8,
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 6,
vertical: 3,
),
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: 0.55),
borderRadius: BorderRadius.circular(999),
),
child: const Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.open_in_full,
size: 12,
color: Colors.white,
),
SizedBox(width: 4),
Text(
'Open map',
style: TextStyle(
color: Colors.white,
fontSize: 11,
fontWeight: FontWeight.w600,
),
),
],
),
),
),
],
),
),
),
),
),
],
),
],
),
),
),
);
}
}
@@ -2417,6 +2551,10 @@ class _MetricText extends StatelessWidget {
@override
Widget build(BuildContext context) {
if (data.directionDegrees != null) {
return _DirectionMetricText(data: data);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
@@ -2456,12 +2594,138 @@ class _MetricText extends StatelessWidget {
}
}
class _DirectionMetricText extends StatelessWidget {
final SensorMetricCardData data;
const _DirectionMetricText({required this.data});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final directionLabel = data.secondaryValue ?? '';
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
data.label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: theme.textTheme.labelMedium?.copyWith(
color: data.accent,
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 4),
Wrap(
spacing: 8,
runSpacing: 4,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
Text(
data.value,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: theme.textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w800,
height: 1.1,
),
),
if (directionLabel.isNotEmpty)
Text(
directionLabel,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: theme.textTheme.titleSmall?.copyWith(
color: data.accent.withValues(alpha: 0.9),
fontWeight: FontWeight.w800,
height: 1.1,
),
),
],
),
],
);
}
}
class _DirectionDial extends StatelessWidget {
final Color accent;
final double degrees;
final String cardinal;
final bool compact;
const _DirectionDial({
required this.accent,
required this.degrees,
required this.cardinal,
this.compact = false,
});
@override
Widget build(BuildContext context) {
final normalized = ((degrees % 360) + 360) % 360;
final size = compact ? 34.0 : 44.0;
final innerSize = compact ? 24.0 : 30.0;
final arrowSize = compact ? 14.0 : 16.0;
final northTop = compact ? 1.0 : 3.0;
return SizedBox(
width: size,
height: size,
child: Stack(
alignment: Alignment.center,
children: [
Container(
width: size,
height: size,
decoration: BoxDecoration(
color: accent.withValues(alpha: 0.08),
shape: BoxShape.circle,
border: Border.all(color: accent.withValues(alpha: 0.2)),
),
),
Container(
width: innerSize,
height: innerSize,
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(color: accent.withValues(alpha: 0.2)),
),
),
Transform.rotate(
angle: normalized * math.pi / 180,
child: Icon(
Icons.navigation_rounded,
size: arrowSize,
color: accent,
),
),
Positioned(
top: northTop,
child: Text(
'N',
style: Theme.of(context).textTheme.labelSmall?.copyWith(
color: accent.withValues(alpha: 0.65),
fontWeight: FontWeight.w800,
fontSize: compact ? 7.5 : 9,
),
),
),
],
),
);
}
}
class SensorMetricCardData {
final String fieldKey;
final IconData icon;
final String label;
final String value;
final String? secondaryValue;
final double? directionDegrees;
final Color accent;
final bool wide;
final LatLng? mapLocation;
@@ -2473,6 +2737,7 @@ class SensorMetricCardData {
required this.label,
required this.value,
this.secondaryValue,
this.directionDegrees,
required this.accent,
this.wide = false,
this.mapLocation,
@@ -2504,13 +2769,20 @@ class _RgbColor {
}
const String _telemetrySourceChannelPrefix = '__source_channel:';
const String _rawTelemetryHexKey = '__raw_lpp_hex';
String _extraFieldKey(String label) {
return 'extra:$label';
}
bool _isTelemetryMetadataKey(String key) {
return key.startsWith(_telemetrySourceChannelPrefix);
return key.startsWith(_telemetrySourceChannelPrefix) ||
key == _rawTelemetryHexKey;
}
String? _rawTelemetryHex(ContactTelemetry? telemetry) {
final value = telemetry?.extraSensorData?[_rawTelemetryHexKey];
return value is String && value.trim().isNotEmpty ? value : null;
}
String _telemetrySourceChannelKey(String fieldKey) {

View File

@@ -226,6 +226,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "0.3.3"
equatable:
dependency: transitive
description:
name: equatable
sha256: "3e0141505477fd8ad55d6eb4e7776d3fe8430be8e497ccb1521370c3f21a3e2b"
url: "https://pub.dev"
source: hosted
version: "2.0.8"
exif:
dependency: transitive
description:
@@ -306,6 +314,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.1.1"
fl_chart:
dependency: "direct main"
description:
name: fl_chart
sha256: b938f77d042cbcd822936a7a359a7235bad8bd72070de1f827efc2cc297ac888
url: "https://pub.dev"
source: hosted
version: "1.2.0"
flutter:
dependency: "direct main"
description: flutter
@@ -812,7 +828,7 @@ packages:
description:
path: "."
ref: main
resolved-ref: "3dbc82170583f616b590e5204a307a02f2b8833d"
resolved-ref: "71902401e9a6bc7d2ed1193f8961e7256646ab76"
url: "https://github.com/dz0ny/meshcore_client.git"
source: git
version: "0.1.0"

View File

@@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 2026.0320.1+36
version: 2026.0322.1+38
environment:
sdk: ^3.9.2
@@ -71,6 +71,7 @@ dependencies:
url: https://github.com/fleaflet/flutter_map.git
ref: master
latlong2: ^0.9.0
fl_chart: ^1.2.0
http: ^1.2.0

View File

@@ -0,0 +1,25 @@
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_sar_app/providers/channels_provider.dart';
void main() {
group('ChannelsProvider device sync preparation', () {
test('clears runtime channel state before sync', () {
final provider = ChannelsProvider();
provider.addOrUpdateChannel(
index: 2,
name: 'Ops',
secret: Uint8List.fromList(List<int>.filled(16, 7)),
);
provider.selectChannel(2);
provider.prepareForDeviceSync();
expect(provider.channels, isEmpty);
expect(provider.selectedChannelIndex, 0);
expect(provider.selectedChannel, isNull);
});
});
}

View File

@@ -0,0 +1,69 @@
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_sar_app/models/contact.dart';
import 'package:meshcore_sar_app/providers/contacts_provider.dart';
import 'package:meshcore_sar_app/services/contact_storage_service.dart';
import 'package:meshcore_sar_app/services/profiles_feature_service.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
Contact createContact({required Uint8List key, required String name}) {
return Contact(
publicKey: key,
type: ContactType.chat,
flags: 0,
outPathLen: 0,
outPath: Uint8List(64),
advName: name,
lastAdvert: DateTime.now().millisecondsSinceEpoch ~/ 1000,
advLat: (46.0569 * 1e6).round(),
advLon: (14.5058 * 1e6).round(),
lastMod: DateTime.now().millisecondsSinceEpoch ~/ 1000,
);
}
setUp(() {
SharedPreferences.setMockInitialValues({});
ProfileStorageScope.setScope(
profilesEnabled: true,
activeProfileId: 'default',
);
});
test(
'initializeEarly respects the active profile storage namespace',
() async {
final storage = ContactStorageService();
final defaultContact = createContact(
key: Uint8List.fromList(List<int>.filled(32, 1)),
name: 'Default Contact',
);
final alphaContact = createContact(
key: Uint8List.fromList(List<int>.filled(32, 2)),
name: 'Alpha Contact',
);
await storage.saveContacts([defaultContact]);
await storage.saveContacts([alphaContact], namespace: 'alpha');
ProfileStorageScope.setScope(
profilesEnabled: true,
activeProfileId: 'alpha',
);
final provider = ContactsProvider();
await provider.initializeEarly();
final names = provider.contacts
.where((contact) => !contact.isChannel)
.map((contact) => contact.advName)
.toList();
expect(names, <String>['Alpha Contact']);
expect(provider.storageNamespace, 'alpha');
},
);
}

View File

@@ -173,14 +173,8 @@ void main() {
var updated = scopedProvider.findContactByKey(scopedKey)!;
expect(updated.telemetry, isNotNull);
expect(updated.telemetry!.gpsLocation, isNull);
expect(
updated.displayLocation!.latitude,
closeTo(45.1234, 0.0001),
);
expect(
updated.displayLocation!.longitude,
closeTo(13.8765, 0.0001),
);
expect(updated.displayLocation!.latitude, closeTo(45.1234, 0.0001));
expect(updated.displayLocation!.longitude, closeTo(13.8765, 0.0001));
// Invalid 0,0 GPS frame should behave the same way.
final invalidGps = CayenneLppParser.createGpsData(
@@ -192,14 +186,8 @@ void main() {
updated = scopedProvider.findContactByKey(scopedKey)!;
expect(updated.telemetry, isNotNull);
expect(updated.telemetry!.gpsLocation, isNull);
expect(
updated.displayLocation!.latitude,
closeTo(45.1234, 0.0001),
);
expect(
updated.displayLocation!.longitude,
closeTo(13.8765, 0.0001),
);
expect(updated.displayLocation!.latitude, closeTo(45.1234, 0.0001));
expect(updated.displayLocation!.longitude, closeTo(13.8765, 0.0001));
}
},
);
@@ -337,95 +325,107 @@ void main() {
expect(updated.telemetry!.extraSensorData, containsPair('co2', 415.0));
});
test('retains scalar telemetry but wipes stale extra sensor fields on refresh', () {
final fullTelemetry = ContactTelemetry(
gpsLocation: const LatLng(46.0569, 14.5058),
batteryPercentage: 54.0,
batteryMilliVolts: 3780,
temperature: 19.5,
timestamp: DateTime.now().subtract(const Duration(minutes: 2)),
humidity: 58.0,
pressure: 1011.2,
extraSensorData: const {'pm25': 8.0},
);
test(
'retains scalar telemetry but wipes stale extra sensor fields on refresh',
() {
final fullTelemetry = ContactTelemetry(
gpsLocation: const LatLng(46.0569, 14.5058),
batteryPercentage: 54.0,
batteryMilliVolts: 3780,
temperature: 19.5,
timestamp: DateTime.now().subtract(const Duration(minutes: 2)),
humidity: 58.0,
pressure: 1011.2,
extraSensorData: const {'pm25': 8.0},
);
provider.addOrUpdateContact(
createContact(
key: publicKey,
type: ContactType.chat,
).copyWith(telemetry: fullTelemetry),
);
provider.addOrUpdateContact(
createContact(
key: publicKey,
type: ContactType.chat,
).copyWith(telemetry: fullTelemetry),
);
final batteryOnly = CayenneLppParser.createBatteryData(3.95);
provider.updateTelemetry(publicKey.sublist(0, 6), batteryOnly);
final batteryOnly = CayenneLppParser.createBatteryData(3.95);
provider.updateTelemetry(publicKey.sublist(0, 6), batteryOnly);
final updated = provider.findContactByKey(publicKey)!;
expect(updated.telemetry, isNotNull);
expect(updated.telemetry!.gpsLocation, isNull);
expect(updated.displayLocation, const LatLng(46.0569, 14.5058));
expect(updated.telemetry!.batteryMilliVolts, isNotNull);
expect(updated.telemetry!.batteryPercentage, isNotNull);
expect(updated.telemetry!.temperature, equals(19.5));
expect(updated.telemetry!.humidity, equals(58.0));
expect(updated.telemetry!.pressure, equals(1011.2));
expect(
updated.telemetry!.extraSensorData,
containsPair('__source_channel:battery', 0),
);
expect(
updated.telemetry!.extraSensorData,
containsPair('__source_channel:voltage', 0),
);
expect(updated.telemetry!.extraSensorData, isNot(contains('pm25')));
});
final updated = provider.findContactByKey(publicKey)!;
expect(updated.telemetry, isNotNull);
expect(updated.telemetry!.gpsLocation, isNull);
expect(updated.displayLocation, const LatLng(46.0569, 14.5058));
expect(updated.telemetry!.batteryMilliVolts, isNotNull);
expect(updated.telemetry!.batteryPercentage, isNotNull);
expect(updated.telemetry!.temperature, equals(19.5));
expect(updated.telemetry!.humidity, equals(58.0));
expect(updated.telemetry!.pressure, equals(1011.2));
expect(
updated.telemetry!.extraSensorData,
containsPair('__source_channel:battery', 0),
);
expect(
updated.telemetry!.extraSensorData,
containsPair('__source_channel:voltage', 0),
);
expect(updated.telemetry!.extraSensorData, isNot(contains('pm25')));
},
);
test('replaces old source-channel mappings when a metric moves channels', () {
final initialTelemetry = ContactTelemetry(
gpsLocation: null,
batteryPercentage: null,
batteryMilliVolts: null,
temperature: 21.5,
timestamp: DateTime.now().subtract(const Duration(minutes: 2)),
humidity: null,
pressure: null,
extraSensorData: const {
'__source_channel:temperature': 2,
'temperature_2': 21.5,
'humidity_4': 66.0,
},
);
test(
'replaces old source-channel mappings when a metric moves channels',
() {
final initialTelemetry = ContactTelemetry(
gpsLocation: null,
batteryPercentage: null,
batteryMilliVolts: null,
temperature: 21.5,
timestamp: DateTime.now().subtract(const Duration(minutes: 2)),
humidity: null,
pressure: null,
extraSensorData: const {
'__source_channel:temperature': 2,
'temperature_2': 21.5,
'humidity_4': 66.0,
},
);
provider.addOrUpdateContact(
createContact(
key: publicKey,
type: ContactType.chat,
).copyWith(telemetry: initialTelemetry),
);
provider.addOrUpdateContact(
createContact(
key: publicKey,
type: ContactType.chat,
).copyWith(telemetry: initialTelemetry),
);
final movedChannelTelemetry = CayenneLppParser.createTemperatureData(
23.5,
channel: 3,
);
final movedChannelTelemetry = CayenneLppParser.createTemperatureData(
23.5,
channel: 3,
);
provider.updateTelemetry(publicKey.sublist(0, 6), movedChannelTelemetry);
provider.updateTelemetry(
publicKey.sublist(0, 6),
movedChannelTelemetry,
);
final updated = provider.findContactByKey(publicKey)!;
expect(updated.telemetry, isNotNull);
expect(updated.telemetry!.temperature, closeTo(23.5, 0.1));
expect(
updated.telemetry!.extraSensorData,
containsPair('__source_channel:temperature', 3),
);
expect(
updated.telemetry!.extraSensorData,
containsPair('temperature_3', closeTo(23.5, 0.1)),
);
expect(
updated.telemetry!.extraSensorData,
isNot(contains('temperature_2')),
);
expect(updated.telemetry!.extraSensorData, isNot(contains('humidity_4')));
});
final updated = provider.findContactByKey(publicKey)!;
expect(updated.telemetry, isNotNull);
expect(updated.telemetry!.temperature, closeTo(23.5, 0.1));
expect(
updated.telemetry!.extraSensorData,
containsPair('__source_channel:temperature', 3),
);
expect(
updated.telemetry!.extraSensorData,
containsPair('temperature_3', closeTo(23.5, 0.1)),
);
expect(
updated.telemetry!.extraSensorData,
isNot(contains('temperature_2')),
);
expect(
updated.telemetry!.extraSensorData,
isNot(contains('humidity_4')),
);
},
);
test('builds message snapshot from latest valid telemetry', () {
final telemetryData = CayenneLppParser.createGpsData(
@@ -870,6 +870,139 @@ void main() {
);
});
});
group('ContactsProvider device sync preparation', () {
late ContactsProvider provider;
setUp(() {
SharedPreferences.setMockInitialValues({});
provider = ContactsProvider();
});
test(
'clears runtime contacts before sync without erasing persisted contacts or saved groups',
() async {
final key = createPublicKey(140);
final pendingKey = createPublicKey(180);
provider.addOrUpdateContact(
createContact(key: key, type: ContactType.chat, name: 'Synced Later'),
);
provider.addPendingAdvert(pendingKey);
await provider.addSavedGroupForFilter('teamMembers', 'alpha');
await provider.prepareForDeviceContactSync();
expect(provider.chatContacts, isEmpty);
expect(provider.pendingAdverts, isEmpty);
expect(provider.savedGroupsForSection('teamMembers'), hasLength(1));
final restored = ContactsProvider();
await restored.initializeEarly();
expect(
restored.chatContacts.map((contact) => contact.advName),
contains('Synced Later'),
);
expect(restored.savedGroupsForSection('teamMembers'), hasLength(1));
},
);
test(
'retains cached telemetry when sync re-adds a contact without telemetry',
() async {
final key = createPublicKey(141);
final contact = createContact(
key: key,
type: ContactType.sensor,
name: 'Sparse Sync Sensor',
).copyWith(
telemetry: ContactTelemetry(
temperature: 18.5,
humidity: 64.0,
timestamp: DateTime(2026, 3, 22, 8, 30),
),
);
provider.addOrUpdateContact(contact);
await provider.prepareForDeviceContactSync();
provider.addOrUpdateContact(
createContact(
key: key,
type: ContactType.sensor,
name: 'Sparse Sync Sensor',
),
);
final restored = provider.findContactByKey(key);
expect(restored, isNotNull);
expect(restored!.telemetry, isNotNull);
expect(restored.telemetry!.temperature, closeTo(18.5, 0.01));
expect(restored.telemetry!.humidity, closeTo(64.0, 0.01));
},
);
test('keeps self telemetry cached across reconnect for the same device', () async {
final selfKey = createPublicKey(200);
await provider.initialize(devicePublicKey: selfKey);
provider.updateTelemetry(
selfKey.sublist(0, 6),
CayenneLppParser.createTemperatureData(23.5, channel: 1),
);
await provider.prepareForDeviceContactSync(devicePublicKey: selfKey);
expect(provider.selfTelemetry, isNotNull);
expect(provider.selfTelemetry!.temperature, closeTo(23.5, 0.1));
});
});
group('ContactsProvider self telemetry', () {
test(
'stores self telemetry without re-adding the device as a contact',
() async {
SharedPreferences.setMockInitialValues({});
final provider = ContactsProvider();
final selfKey = createPublicKey(200);
await provider.initialize(devicePublicKey: selfKey);
provider.updateTelemetry(
selfKey.sublist(0, 6),
CayenneLppParser.createTemperatureData(23.5, channel: 1),
);
expect(provider.selfTelemetry, isNotNull);
expect(provider.selfTelemetry!.temperature, closeTo(23.5, 0.1));
expect(provider.findContactByKey(selfKey), isNull);
expect(
provider.contacts.any(
(contact) => contact.publicKeyHex == publicKeyHex(selfKey),
),
isFalse,
);
},
);
});
test('stores raw telemetry hex in metadata for verification', () async {
SharedPreferences.setMockInitialValues({});
final provider = ContactsProvider();
final telemetryKey = createPublicKey(150);
final contact = createContact(
key: telemetryKey,
type: ContactType.chat,
name: 'Telemetry Node',
);
provider.addOrUpdateContact(contact);
final payload = Uint8List.fromList(<int>[0x01, 0x67, 0x00, 0xEB]);
provider.updateTelemetry(telemetryKey.sublist(0, 6), payload);
final updated = provider.findContactByKey(telemetryKey)!;
expect(updated.telemetry?.extraSensorData?['__raw_lpp_hex'], '01 67 00 eb');
});
}
String publicKeyHex(Uint8List publicKey) {

View File

@@ -0,0 +1,134 @@
import 'dart:async';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_sar_app/providers/image_provider.dart';
import 'package:meshcore_sar_app/providers/voice_provider.dart';
import 'package:meshcore_sar_app/services/profiles_feature_service.dart';
import 'package:meshcore_sar_app/services/voice_codec_service.dart';
import 'package:meshcore_sar_app/services/voice_player_service.dart';
import 'package:meshcore_sar_app/utils/image_message_parser.dart';
import 'package:meshcore_sar_app/utils/voice_message_parser.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
setUp(() {
SharedPreferences.setMockInitialValues({});
ProfileStorageScope.setScope(
profilesEnabled: true,
activeProfileId: 'alpha',
);
});
test('VoiceProvider reloads profile-scoped sessions', () async {
final player = _FakeVoicePlayerService();
final provider = VoiceProvider(codec: VoiceCodecService(), player: player);
addTearDown(provider.dispose);
await provider.reloadProfileScopedState();
provider.registerEnvelope(
const VoiceEnvelope(
sessionId: 'a1b2c3d4',
mode: VoicePacketMode.mode1200,
total: 2,
durationMs: 1600,
),
);
await Future<void>.delayed(const Duration(milliseconds: 50));
ProfileStorageScope.setScope(
profilesEnabled: true,
activeProfileId: 'beta',
);
await provider.reloadProfileScopedState();
expect(provider.session('a1b2c3d4'), isNull);
ProfileStorageScope.setScope(
profilesEnabled: true,
activeProfileId: 'alpha',
);
await provider.reloadProfileScopedState();
expect(provider.session('a1b2c3d4'), isNotNull);
});
test('ImageProvider reloads profile-scoped sessions', () async {
final provider = ImageProvider();
await provider.reloadProfileScopedState();
provider.registerEnvelope(
const ImageEnvelope(
sessionId: 'a1b2c3d4',
format: ImageFormat.avif,
total: 2,
width: 32,
height: 32,
sizeBytes: 8,
),
);
provider.addFragment(
ImagePacket(
sessionId: 'a1b2c3d4',
format: ImageFormat.avif,
index: 0,
total: 2,
data: Uint8List.fromList([1, 2, 3, 4]),
),
width: 32,
height: 32,
);
await Future<void>.delayed(const Duration(milliseconds: 50));
ProfileStorageScope.setScope(
profilesEnabled: true,
activeProfileId: 'beta',
);
await provider.reloadProfileScopedState();
expect(provider.session('a1b2c3d4'), isNull);
ProfileStorageScope.setScope(
profilesEnabled: true,
activeProfileId: 'alpha',
);
await provider.reloadProfileScopedState();
expect(provider.session('a1b2c3d4'), isNotNull);
});
}
class _FakeVoicePlayerService implements VoicePlayerService {
final StreamController<void> _events = StreamController<void>.broadcast();
bool _isPlaying = false;
@override
bool get isPlaying => _isPlaying;
@override
Duration get position => Duration.zero;
@override
Duration get duration => Duration.zero;
@override
Stream<void> get events => _events.stream;
@override
Future<void> play(Int16List pcmSamples, {required int sampleRateHz}) async {
_isPlaying = true;
_events.add(null);
}
@override
Future<void> stop() async {
_isPlaying = false;
_events.add(null);
}
@override
void dispose() {
_events.close();
}
@override
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}

View File

@@ -390,6 +390,38 @@ void main() {
);
});
test('incoming contact messages dedupe by sender handle and text', () {
final provider = MessagesProvider();
provider.addMessage(
Message(
id: 'handle-1',
messageType: MessageType.contact,
pathLen: 1,
textType: MessageTextType.plain,
senderTimestamp: 1700000800,
text: 'same payload',
senderName: 'Radio Alpha',
receivedAt: DateTime.now(),
),
);
provider.addMessage(
Message(
id: 'handle-2',
messageType: MessageType.contact,
pathLen: 2,
textType: MessageTextType.plain,
senderTimestamp: 1700000810,
text: 'same payload',
senderName: 'Radio Alpha',
receivedAt: DateTime.now(),
),
);
expect(provider.messages, hasLength(1));
expect(provider.messages.single.id, equals('handle-1'));
});
test('display list collapses stored duplicates and sums copy counts', () {
final provider = MessagesProvider();
final sender = Uint8List.fromList([5, 4, 3, 2, 1, 0]);

View File

@@ -6,6 +6,7 @@ import 'package:meshcore_sar_app/models/device_info.dart';
import 'package:meshcore_sar_app/providers/connection_provider.dart';
import 'package:meshcore_sar_app/providers/contacts_provider.dart';
import 'package:meshcore_sar_app/providers/sensors_provider.dart';
import 'package:meshcore_sar_app/services/cayenne_lpp_parser.dart';
import 'package:meshcore_sar_app/services/profiles_feature_service.dart';
import 'package:shared_preferences/shared_preferences.dart';
@@ -19,10 +20,17 @@ class _FakeContactsProvider extends ContactsProvider {
}
class _FakeConnectionProvider extends ConnectionProvider {
_FakeConnectionProvider({required bool isConnected})
: _isConnected = isConnected;
_FakeConnectionProvider({
required bool isConnected,
Uint8List? publicKey,
String? selfName,
}) : _isConnected = isConnected,
_publicKey = publicKey,
_selfName = selfName;
final bool _isConnected;
final Uint8List? _publicKey;
final String? _selfName;
int pingCalls = 0;
@@ -31,6 +39,8 @@ class _FakeConnectionProvider extends ConnectionProvider {
connectionState: _isConnected
? ConnectionState.connected
: ConnectionState.disconnected,
publicKey: _publicKey,
selfName: _selfName,
);
@override
@@ -65,9 +75,12 @@ void main() {
expect(provider.isLoaded, isTrue);
}
Contact buildSensorContact() {
Contact buildSensorContact({
int firstByte = 0x44,
String name = 'WX Station',
}) {
final publicKey = Uint8List(32);
publicKey[0] = 0x44;
publicKey[0] = firstByte;
return Contact(
publicKey: publicKey,
@@ -75,7 +88,7 @@ void main() {
flags: 0,
outPathLen: 0,
outPath: Uint8List(64),
advName: 'WX Station',
advName: name,
lastAdvert: DateTime.now().millisecondsSinceEpoch ~/ 1000,
advLat: 0,
advLon: 0,
@@ -264,6 +277,36 @@ void main() {
);
});
test('watched sensor order persists across reloads', () async {
SharedPreferences.setMockInitialValues({});
final first = buildSensorContact(firstByte: 0x44, name: 'First');
final second = buildSensorContact(firstByte: 0x45, name: 'Second');
final third = buildSensorContact(firstByte: 0x46, name: 'Third');
final provider = SensorsProvider();
await waitUntilLoaded(provider);
await provider.addSensor(first);
await provider.addSensor(second);
await provider.addSensor(third);
await provider.reorderSensors(2, 0);
expect(provider.watchedSensorKeys, <String>[
third.publicKeyHex,
first.publicKeyHex,
second.publicKeyHex,
]);
final reloadedProvider = SensorsProvider();
await waitUntilLoaded(reloadedProvider);
expect(reloadedProvider.watchedSensorKeys, <String>[
third.publicKeyHex,
first.publicKeyHex,
second.publicKeyHex,
]);
});
test(
'unsupported auto refresh minutes normalize to nearest option',
() async {
@@ -313,6 +356,43 @@ void main() {
expect(connectionProvider.pingCalls, 2);
});
test('refreshDueSensors refreshes self every minute', () async {
SharedPreferences.setMockInitialValues({});
final selfKey = Uint8List(32)..[0] = 0x66;
final contactsProvider = ContactsProvider();
await contactsProvider.initialize(devicePublicKey: selfKey);
final connectionProvider = _FakeConnectionProvider(
isConnected: true,
publicKey: selfKey,
selfName: 'My Device',
);
final start = DateTime(2026, 3, 22, 9, 0);
final provider = SensorsProvider();
await waitUntilLoaded(provider);
await provider.refreshDueSensors(
now: start,
contactsProvider: contactsProvider,
connectionProvider: connectionProvider,
);
expect(connectionProvider.pingCalls, 1);
await provider.refreshDueSensors(
now: start.add(const Duration(seconds: 30)),
contactsProvider: contactsProvider,
connectionProvider: connectionProvider,
);
expect(connectionProvider.pingCalls, 1);
await provider.refreshDueSensors(
now: start.add(const Duration(minutes: 1)),
contactsProvider: contactsProvider,
connectionProvider: connectionProvider,
);
expect(connectionProvider.pingCalls, 2);
});
test(
'addSensor includes available extra telemetry fields by default',
() async {
@@ -340,4 +420,60 @@ void main() {
);
},
);
test('selfContact includes stored self telemetry', () async {
SharedPreferences.setMockInitialValues({});
final selfKey = Uint8List(32)..[0] = 0x66;
final contactsProvider = ContactsProvider();
await contactsProvider.initialize(devicePublicKey: selfKey);
contactsProvider.updateTelemetry(
selfKey.sublist(0, 6),
CayenneLppParser.createTemperatureData(19.5, channel: 1),
);
final connectionProvider = _FakeConnectionProvider(
isConnected: true,
publicKey: selfKey,
selfName: 'My Device',
);
final provider = SensorsProvider();
await waitUntilLoaded(provider);
final selfContact = provider.selfContact(
contactsProvider,
connectionProvider,
);
expect(selfContact, isNotNull);
expect(selfContact!.telemetry, isNotNull);
expect(selfContact.telemetry!.temperature, closeTo(19.5, 0.1));
});
test(
'displaySelfKey still returns self when watched sensors exist',
() async {
SharedPreferences.setMockInitialValues({});
final selfKey = Uint8List(32)..[0] = 0x66;
final sensor = buildSensorContact(firstByte: 0x44, name: 'Weather');
final contactsProvider = ContactsProvider();
await contactsProvider.initialize(devicePublicKey: selfKey);
final connectionProvider = _FakeConnectionProvider(
isConnected: true,
publicKey: selfKey,
selfName: 'My Device',
);
final provider = SensorsProvider();
await waitUntilLoaded(provider);
await provider.addSensor(sensor);
expect(
provider.displaySelfKey(
contactsProvider: contactsProvider,
connectionProvider: connectionProvider,
),
selfKey.map((b) => b.toRadixString(16).padLeft(2, '0')).join(),
);
},
);
}

View File

@@ -0,0 +1,190 @@
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_sar_app/l10n/app_localizations.dart';
import 'package:meshcore_sar_app/models/device_info.dart' as device_info;
import 'package:meshcore_sar_app/providers/connection_provider.dart';
import 'package:meshcore_sar_app/providers/contacts_provider.dart';
import 'package:meshcore_sar_app/screens/discovery_screen.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
class _FakeConnectionProvider extends ConnectionProvider {
_FakeConnectionProvider({required bool isConnected})
: _isConnected = isConnected;
final bool _isConnected;
final List<int> discoveredAdvertTypes = <int>[];
@override
device_info.DeviceInfo get deviceInfo => device_info.DeviceInfo(
connectionState: _isConnected
? device_info.ConnectionState.connected
: device_info.ConnectionState.disconnected,
);
@override
Future<void> discoverNodeType({
required int advertType,
bool prefixOnly = false,
int since = 0,
}) async {
discoveredAdvertTypes.add(advertType);
}
}
Future<void> _pumpDiscoveryScreen(
WidgetTester tester, {
ContactsProvider? contactsProvider,
ConnectionProvider? connectionProvider,
}) async {
final resolvedContactsProvider = contactsProvider ?? ContactsProvider();
final resolvedConnectionProvider =
connectionProvider ?? _FakeConnectionProvider(isConnected: true);
await tester.pumpWidget(
MultiProvider(
providers: [
ChangeNotifierProvider<ContactsProvider>.value(
value: resolvedContactsProvider,
),
ChangeNotifierProvider<ConnectionProvider>.value(
value: resolvedConnectionProvider,
),
],
child: MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: const DiscoveryScreen(),
),
),
);
await tester.pumpAndSettle();
}
Uint8List _publicKey(int seed) {
final bytes = Uint8List(32);
bytes[0] = seed;
bytes[1] = seed + 1;
bytes[2] = seed + 2;
return bytes;
}
void main() {
setUp(() {
SharedPreferences.setMockInitialValues({});
});
testWidgets(
'discovery actions are shown in the summary card instead of overflow menu',
(tester) async {
tester.view.physicalSize = const Size(375, 812);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final connectionProvider = _FakeConnectionProvider(isConnected: true);
await _pumpDiscoveryScreen(
tester,
connectionProvider: connectionProvider,
);
expect(tester.takeException(), isNull);
expect(find.text('Discover repeaters'), findsOneWidget);
expect(find.text('Discover sensors'), findsOneWidget);
expect(find.text('Resolve all'), findsOneWidget);
expect(find.text('Clear all'), findsOneWidget);
expect(find.text('Search discovered nodes'), findsNothing);
expect(find.byIcon(Icons.more_vert), findsNothing);
expect(
find.text(
'Use the discovery actions above to find repeaters and sensors on the mesh.',
),
findsOneWidget,
);
await tester.tap(find.text('Discover repeaters'));
await tester.pump();
expect(connectionProvider.discoveredAdvertTypes, [2]);
expect(find.text('Repeater discovery sent'), findsOneWidget);
},
);
testWidgets('search and inline type filters narrow discovered nodes', (
tester,
) async {
tester.view.physicalSize = const Size(390, 1400);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final contactsProvider = ContactsProvider()
..addOrUpdatePendingAdvertMetadata(
publicKey: _publicKey(0x10),
typeValue: 2,
advName: 'Relay Alpha',
)
..addOrUpdatePendingAdvertMetadata(
publicKey: _publicKey(0x20),
typeValue: 4,
advName: 'WX Station',
)
..addOrUpdatePendingAdvertMetadata(
publicKey: _publicKey(0x30),
typeValue: 3,
advName: 'Ops Room',
);
await _pumpDiscoveryScreen(
tester,
contactsProvider: contactsProvider,
connectionProvider: _FakeConnectionProvider(isConnected: true),
);
expect(find.text('Search discovered nodes'), findsOneWidget);
expect(find.text('All'), findsOneWidget);
expect(find.text('Repeaters'), findsOneWidget);
expect(find.text('Sensors'), findsOneWidget);
expect(find.text('Others'), findsOneWidget);
expect(find.text('Relay Alpha'), findsOneWidget);
expect(find.text('WX Station'), findsOneWidget);
expect(find.text('Ops Room'), findsOneWidget);
await tester.tap(find.text('Sensors'));
await tester.pumpAndSettle();
expect(find.text('Relay Alpha'), findsNothing);
expect(find.text('WX Station'), findsOneWidget);
expect(find.text('Ops Room'), findsNothing);
expect(find.text('Discovered nodes (1/3)'), findsOneWidget);
await tester.tap(find.text('Others'));
await tester.pumpAndSettle();
expect(find.text('Relay Alpha'), findsNothing);
expect(find.text('WX Station'), findsNothing);
expect(find.text('Ops Room'), findsOneWidget);
await tester.enterText(find.byType(TextField), 'relay');
await tester.pumpAndSettle();
expect(find.text('No matches'), findsOneWidget);
await tester.tap(find.text('All'));
await tester.pumpAndSettle();
expect(find.text('Relay Alpha'), findsOneWidget);
expect(find.text('Ops Room'), findsNothing);
await tester.enterText(find.byType(TextField), 'ops');
await tester.pumpAndSettle();
expect(find.text('Relay Alpha'), findsNothing);
expect(find.text('WX Station'), findsNothing);
expect(find.text('Ops Room'), findsOneWidget);
expect(find.text('Discovered nodes (1/3)'), findsOneWidget);
});
}

View File

@@ -0,0 +1,84 @@
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_sar_app/models/contact.dart';
import 'package:meshcore_sar_app/services/bthome_met_history.dart';
void main() {
test('parses a valid BTHome MET history response', () {
final parsed = BTHomeMetHistoryParser.parse('1,0,4,11.2,11.8,12.1,12.3');
expect(parsed.measurement, BTHomeMetMeasurement.temperature);
expect(parsed.page, 0);
expect(parsed.values, <double>[11.2, 11.8, 12.1, 12.3]);
expect(parsed.latest, 12.3);
expect(parsed.minimum, 11.2);
expect(parsed.maximum, 12.3);
});
test('rejects malformed BTHome MET history counts', () {
expect(
() => BTHomeMetHistoryParser.parse('2,0,3,41,42'),
throwsA(isA<BTHomeMetHistoryFormatException>()),
);
});
test('detects available BTHome MET measurements from telemetry', () {
final contact = Contact(
publicKey: Uint8List(32),
type: ContactType.sensor,
flags: 0,
outPathLen: 0,
outPath: Uint8List(64),
advName: 'WX',
lastAdvert: 0,
advLat: 0,
advLon: 0,
lastMod: 0,
telemetry: ContactTelemetry(
temperature: 20.1,
humidity: 52,
extraSensorData: const {
'generic_sensor_1': 1,
'speed_2': 3.1,
'gust_2': 4.8,
'rain_2': 12.3,
},
timestamp: DateTime(2026, 3, 21, 12),
),
);
expect(bTHomeMetMeasurementsForContact(contact), <BTHomeMetMeasurement>[
BTHomeMetMeasurement.temperature,
BTHomeMetMeasurement.humidity,
BTHomeMetMeasurement.windSpeed,
BTHomeMetMeasurement.gust,
BTHomeMetMeasurement.rain,
]);
expect(supportsBTHomeMetHistory(contact), isTrue);
});
test('does not enable BTHome MET history without channel 1 capability', () {
final contact = Contact(
publicKey: Uint8List(32),
type: ContactType.sensor,
flags: 0,
outPathLen: 0,
outPath: Uint8List(64),
advName: 'WX',
lastAdvert: 0,
advLat: 0,
advLon: 0,
lastMod: 0,
telemetry: ContactTelemetry(
temperature: 20.1,
humidity: 52,
extraSensorData: const {'speed_2': 3.1, 'gust_2': 4.8, 'rain_2': 12.3},
timestamp: DateTime(2026, 3, 21, 12),
),
);
expect(bTHomeMetMeasurementsForContact(contact), isEmpty);
expect(supportsBTHomeMetHistory(contact), isFalse);
});
}

View File

@@ -488,6 +488,39 @@ void main() {
},
);
test('weather station payload keeps generic percentage and does not invent battery from ch1 voltage', () {
final payload = Uint8List.fromList([
0x01, 0x74, 0x00, 0x00,
0x02, 0x78, 0x64,
0x02, 0x73, 0x24, 0x32,
0x02, 0x65, 0x5A, 0x50,
0x02, 0x8A, 0xFF, 0xE4,
0x02, 0x74, 0x01, 0xE0,
0x02, 0x9D, 0x00,
0x02, 0x68, 0x76,
0x02, 0x81, 0x01, 0x4A,
0x02, 0x89, 0x01, 0xB8,
0x02, 0x67, 0x00, 0x2D,
0x02, 0xAD, 0x0A,
0x02, 0x84, 0x00, 0x56,
0x02, 0x8B, 0x00, 0xB3,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00
]);
final decoded = CayenneLppParser.parse(payload);
expect(decoded.batteryPercentage, isNull);
expect(decoded.batteryMilliVolts, isNull);
expect(decoded.temperature, closeTo(4.5, 0.1));
expect(decoded.humidity, closeTo(59.0, 0.1));
expect(decoded.pressure, closeTo(926.6, 0.1));
expect(decoded.extraSensorData!['voltage_1'], closeTo(0.0, 0.001));
expect(decoded.extraSensorData!['percentage_2'], equals(100.0));
expect(decoded.extraSensorData!['uv_2'], equals(1.0));
expect(decoded.extraSensorData!['rain_2'], closeTo(17.9, 0.1));
expect(decoded.extraSensorData!.containsKey('__source_channel:battery'), isFalse);
});
test('unknown sensor type is skipped gracefully', () {
final buffer = ByteData(5);
buffer.setUint8(0, 0);

View File

@@ -13,6 +13,8 @@ import 'package:meshcore_sar_app/providers/drawing_provider.dart';
import 'package:meshcore_sar_app/providers/map_provider.dart';
import 'package:meshcore_sar_app/providers/messages_provider.dart';
import 'package:meshcore_sar_app/providers/sensors_provider.dart';
import 'package:meshcore_sar_app/providers/voice_provider.dart';
import 'package:meshcore_sar_app/providers/image_provider.dart' as ip;
import 'package:meshcore_sar_app/services/app_config_snapshot_service.dart';
import 'package:meshcore_sar_app/services/contact_storage_service.dart';
import 'package:meshcore_sar_app/services/device_config_applicator.dart';
@@ -207,15 +209,21 @@ void main() {
final connectionProvider = _FakeConnectionProvider(
deviceInfo: DeviceInfo(publicKey: Uint8List.fromList([1, 2, 3, 4])),
);
final voiceProvider = _FakeVoiceProvider();
final imageProvider = _FakeImageProvider();
final coordinator = _buildCoordinator(
profileManager: manager,
connectionProvider: connectionProvider,
voiceProvider: voiceProvider,
imageProvider: imageProvider,
);
await coordinator.syncActiveProfileForCurrentDevice();
expect(manager.activeProfileId, alpha.id);
expect(connectionProvider.disconnectCallCount, 0);
expect(voiceProvider.reloadCallCount, 1);
expect(imageProvider.reloadCallCount, 1);
});
test(
@@ -257,6 +265,8 @@ void main() {
ProfileWorkspaceCoordinator _buildCoordinator({
required ProfileManager profileManager,
_FakeConnectionProvider? connectionProvider,
_FakeVoiceProvider? voiceProvider,
_FakeImageProvider? imageProvider,
}) {
return ProfileWorkspaceCoordinator(
profileManager: profileManager,
@@ -267,6 +277,8 @@ ProfileWorkspaceCoordinator _buildCoordinator({
mapProvider: _FakeMapProvider(),
drawingProvider: _FakeDrawingProvider(),
channelsProvider: _FakeChannelsProvider(),
voiceProvider: voiceProvider ?? _FakeVoiceProvider(),
imageProvider: imageProvider ?? _FakeImageProvider(),
appProvider: _FakeAppProvider(),
appConfigSnapshotService: _FakeAppConfigSnapshotService(),
mapWorkspaceSnapshotService: _FakeMapWorkspaceSnapshotService(),
@@ -332,9 +344,8 @@ class _FakeDeviceConfigApplicator extends DeviceConfigApplicator {
}
class _FakeConnectionProvider implements ConnectionProvider {
_FakeConnectionProvider({
DeviceInfo? deviceInfo,
}) : deviceInfo = deviceInfo ?? DeviceInfo();
_FakeConnectionProvider({DeviceInfo? deviceInfo})
: deviceInfo = deviceInfo ?? DeviceInfo();
int disconnectCallCount = 0;
@@ -407,6 +418,30 @@ class _FakeChannelsProvider implements ChannelsProvider {
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
class _FakeVoiceProvider implements VoiceProvider {
int reloadCallCount = 0;
@override
Future<void> reloadProfileScopedState() async {
reloadCallCount += 1;
}
@override
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
class _FakeImageProvider implements ip.ImageProvider {
int reloadCallCount = 0;
@override
Future<void> reloadProfileScopedState() async {
reloadCallCount += 1;
}
@override
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
class _FakeAppProvider implements AppProvider {
@override
Future<void> reloadProfileScopedSettings() async {}

View File

@@ -1,7 +1,6 @@
import 'dart:typed_data';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_sar_app/l10n/app_localizations.dart';
import 'package:meshcore_sar_app/models/message.dart';
@@ -22,8 +21,36 @@ import 'package:shared_preferences/shared_preferences.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final launchedUrls = <String>[];
setUp(() {
SharedPreferences.setMockInitialValues({});
launchedUrls.clear();
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
const MethodChannel('plugins.flutter.io/url_launcher'),
(call) async {
switch (call.method) {
case 'canLaunch':
return true;
case 'launch':
final arguments = Map<dynamic, dynamic>.from(
call.arguments as Map<dynamic, dynamic>,
);
launchedUrls.add(arguments['url'] as String);
return true;
}
return null;
},
);
});
tearDown(() {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(
const MethodChannel('plugins.flutter.io/url_launcher'),
null,
);
});
testWidgets('received bubbles show signal chips on double tap', (
@@ -153,6 +180,151 @@ void main() {
await _disposeHarness(tester, harness);
}
});
testWidgets('message bubble detects and opens links', (tester) async {
final harness = await _TestHarness.create();
try {
final message = Message(
id: 'message-link',
messageType: MessageType.contact,
senderPublicKeyPrefix: _prefix(31),
pathLen: 0,
textType: MessageTextType.plain,
senderTimestamp: 1700000000,
text: 'Check https://example.com/docs, then ping @[Rescue Team].',
receivedAt: DateTime.fromMillisecondsSinceEpoch(1700000000500),
deliveryStatus: MessageDeliveryStatus.received,
);
await tester.pumpWidget(_buildApp(harness, message));
await tester.pumpAndSettle();
final richText = tester
.widgetList<RichText>(find.byType(RichText))
.firstWhere(
(widget) =>
widget.text.toPlainText().contains('https://example.com/docs'),
);
final linkSpan = _findTextSpan(
richText.text,
(span) => span.text == 'https://example.com/docs',
);
expect(richText.text.toPlainText(), contains('https://example.com/docs'));
expect(find.text('@Rescue Team'), findsOneWidget);
expect(linkSpan, isNotNull);
final recognizer = linkSpan!.recognizer;
expect(recognizer, isA<TapGestureRecognizer>());
(recognizer! as TapGestureRecognizer).onTap!();
await tester.pump();
expect(launchedUrls, ['https://example.com/docs']);
} finally {
await _disposeHarness(tester, harness);
}
});
testWidgets('message bubble opens meshcore links in add contact screen', (
tester,
) async {
final harness = await _TestHarness.create();
try {
const payloadSegment = '00112233445566778899aabbccddeeff';
final advert =
'meshcore://'
'$payloadSegment'
'$payloadSegment'
'$payloadSegment'
'$payloadSegment'
'$payloadSegment'
'$payloadSegment'
'0011';
final message = Message(
id: 'message-meshcore-link',
messageType: MessageType.contact,
senderPublicKeyPrefix: _prefix(41),
pathLen: 0,
textType: MessageTextType.plain,
senderTimestamp: 1700000000,
text: 'Import $advert',
receivedAt: DateTime.fromMillisecondsSinceEpoch(1700000000500),
deliveryStatus: MessageDeliveryStatus.received,
);
await tester.pumpWidget(_buildApp(harness, message));
await tester.pumpAndSettle();
final richText = tester
.widgetList<RichText>(find.byType(RichText))
.firstWhere((widget) => widget.text.toPlainText().contains(advert));
final linkSpan = _findTextSpan(
richText.text,
(span) => span.text == advert,
);
expect(linkSpan, isNotNull);
final recognizer = linkSpan!.recognizer;
expect(recognizer, isA<TapGestureRecognizer>());
(recognizer! as TapGestureRecognizer).onTap!();
await tester.pumpAndSettle();
expect(find.text('Import a shared contact advert'), findsOneWidget);
expect(find.text(advert), findsOneWidget);
} finally {
await _disposeHarness(tester, harness);
}
});
testWidgets('message bubble linkifies raw meshcore adverts', (tester) async {
final harness = await _TestHarness.create();
try {
const advert =
'00112233445566778899aabbccddeeff'
'00112233445566778899aabbccddeeff'
'00112233445566778899aabbccddeeff'
'00112233445566778899aabbccddeeff'
'00112233445566778899aabbccddeeff'
'00112233445566778899aabbccddeeff'
'0011';
final message = Message(
id: 'message-meshcore-raw',
messageType: MessageType.contact,
senderPublicKeyPrefix: _prefix(51),
pathLen: 0,
textType: MessageTextType.plain,
senderTimestamp: 1700000000,
text: 'Import raw advert: $advert',
receivedAt: DateTime.fromMillisecondsSinceEpoch(1700000000500),
deliveryStatus: MessageDeliveryStatus.received,
);
await tester.pumpWidget(_buildApp(harness, message));
await tester.pumpAndSettle();
final richText = tester
.widgetList<RichText>(find.byType(RichText))
.firstWhere((widget) => widget.text.toPlainText().contains(advert));
final linkSpan = _findTextSpan(
richText.text,
(span) => span.text == advert,
);
expect(linkSpan, isNotNull);
final recognizer = linkSpan!.recognizer;
expect(recognizer, isA<TapGestureRecognizer>());
(recognizer! as TapGestureRecognizer).onTap!();
await tester.pumpAndSettle();
expect(find.text('Import a shared contact advert'), findsOneWidget);
expect(find.text(advert), findsOneWidget);
} finally {
await _disposeHarness(tester, harness);
}
});
}
Widget _buildApp(_TestHarness harness, Message message) {
@@ -242,3 +414,22 @@ Future<void> _doubleTap(WidgetTester tester, Finder finder) async {
await tester.tap(finder);
await tester.pump();
}
TextSpan? _findTextSpan(
InlineSpan span,
bool Function(TextSpan span) predicate,
) {
if (span is! TextSpan) {
return null;
}
if (predicate(span)) {
return span;
}
for (final child in span.children ?? const <InlineSpan>[]) {
final match = _findTextSpan(child, predicate);
if (match != null) {
return match;
}
}
return null;
}

View File

@@ -1,10 +1,10 @@
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_sar_app/l10n/app_localizations.dart';
import 'package:meshcore_sar_app/models/contact.dart';
import 'package:meshcore_sar_app/providers/sensors_provider.dart';
import 'package:meshcore_sar_app/services/cayenne_lpp_parser.dart';
import 'package:meshcore_sar_app/widgets/sensors/sensor_telemetry_card.dart';
void main() {
@@ -189,4 +189,257 @@ void main() {
expect(find.text('2°C'), findsOneWidget);
expect(find.text('12.3 mm'), findsOneWidget);
});
testWidgets('renders generic percentage separately from UV for weather payload', (tester) async {
tester.view.physicalSize = const Size(1600, 2600);
tester.view.devicePixelRatio = 1.0;
addTearDown(() {
tester.view.resetPhysicalSize();
tester.view.resetDevicePixelRatio();
});
final publicKey = Uint8List(32);
publicKey[0] = 0x49;
final payload = Uint8List.fromList([
0x01, 0x74, 0x00, 0x00,
0x02, 0x78, 0x64,
0x02, 0x73, 0x24, 0x31,
0x02, 0x65, 0x67, 0xDE,
0x02, 0x8A, 0xFF, 0xE6,
0x02, 0x74, 0x01, 0xE0,
0x02, 0x9D, 0x00,
0x02, 0x68, 0x76,
0x02, 0x81, 0x00, 0xDC,
0x02, 0x89, 0x01, 0x36,
0x02, 0x67, 0x00, 0x2F,
0x02, 0xAD, 0x0A,
0x02, 0x84, 0x00, 0x50,
0x02, 0x8B, 0x00, 0xB3,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00
]);
final contact = Contact(
publicKey: publicKey,
type: ContactType.sensor,
flags: 0,
outPathLen: 0,
outPath: Uint8List(64),
advName: 'WX Station',
lastAdvert: DateTime.now().millisecondsSinceEpoch ~/ 1000,
advLat: 0,
advLon: 0,
lastMod: DateTime.now().millisecondsSinceEpoch ~/ 1000,
telemetry: CayenneLppParser.parse(payload),
);
await tester.pumpWidget(
MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: Scaffold(
body: SingleChildScrollView(
child: SensorTelemetryCard(
contact: contact,
state: SensorRefreshState.idle,
visibleFields: const {
'temperature',
'humidity',
'pressure',
'extra:percentage_2',
'extra:dew_2',
'extra:speed_2',
'extra:gust_2',
'extra:uv_2',
'extra:direction_2',
'extra:rain_2',
},
fieldSpans: sensorFullWidthFieldSpans(const {
'temperature',
'humidity',
'pressure',
'extra:percentage_2',
'extra:dew_2',
'extra:speed_2',
'extra:gust_2',
'extra:uv_2',
'extra:direction_2',
'extra:rain_2',
}),
),
),
),
),
);
expect(find.byKey(const ValueKey('sensor_metric_extra:percentage_2')), findsOneWidget);
expect(find.byKey(const ValueKey('sensor_metric_extra:uv_2')), findsOneWidget);
expect(find.text('100%'), findsOneWidget);
expect(find.text('1%'), findsNothing);
expect(find.text('1'), findsOneWidget);
expect(find.text('80°'), findsOneWidget);
expect(find.text(''), findsNothing);
});
testWidgets('renders direction metric with compact compass layout', (
tester,
) async {
final publicKey = Uint8List(32);
publicKey[0] = 0x47;
final contact = Contact(
publicKey: publicKey,
type: ContactType.sensor,
flags: 0,
outPathLen: 0,
outPath: Uint8List(64),
advName: 'WX Station',
lastAdvert: DateTime.now().millisecondsSinceEpoch ~/ 1000,
advLat: 0,
advLon: 0,
lastMod: DateTime.now().millisecondsSinceEpoch ~/ 1000,
telemetry: ContactTelemetry(
timestamp: DateTime.now().subtract(const Duration(minutes: 1)),
extraSensorData: const {'direction_2': 111.0},
),
);
await tester.pumpWidget(
MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: Scaffold(
body: SensorTelemetryCard(
contact: contact,
state: SensorRefreshState.idle,
visibleFields: const {'extra:direction_2'},
fieldSpans: sensorFullWidthFieldSpans(const {'extra:direction_2'}),
),
),
),
);
expect(find.text('Direction'), findsOneWidget);
expect(find.text('111°'), findsOneWidget);
expect(find.text('E'), findsOneWidget);
expect(find.byIcon(Icons.navigation_rounded), findsOneWidget);
});
testWidgets('long pressing a telemetry bubble triggers refresh', (
tester,
) async {
final contact = buildContact();
var refreshCount = 0;
await tester.pumpWidget(
MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: Scaffold(
body: SensorTelemetryCard(
contact: contact,
state: SensorRefreshState.idle,
visibleFields: const {'temperature'},
fieldSpans: sensorFullWidthFieldSpans(const {'temperature'}),
onRefresh: () async {
refreshCount += 1;
},
),
),
),
);
await tester.longPress(
find.byKey(const ValueKey('sensor_metric_temperature')),
);
await tester.pumpAndSettle();
expect(refreshCount, 1);
});
testWidgets('overflow menu exposes move actions', (tester) async {
final contact = buildContact();
var moveUpCount = 0;
var moveDownCount = 0;
await tester.pumpWidget(
MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: Scaffold(
body: SensorTelemetryCard(
contact: contact,
state: SensorRefreshState.idle,
visibleFields: const {'temperature'},
fieldSpans: sensorFullWidthFieldSpans(const {'temperature'}),
onMoveUp: () async {
moveUpCount += 1;
},
onMoveDown: () async {
moveDownCount += 1;
},
),
),
),
);
await tester.tap(find.byIcon(Icons.more_vert));
await tester.pumpAndSettle();
expect(find.text('Move up'), findsOneWidget);
expect(find.text('Move down'), findsOneWidget);
await tester.tap(find.text('Move down'));
await tester.pumpAndSettle();
expect(moveUpCount, 0);
expect(moveDownCount, 1);
});
testWidgets('overflow menu copies raw response', (tester) async {
final publicKey = Uint8List(32);
publicKey[0] = 0x48;
final contact = Contact(
publicKey: publicKey,
type: ContactType.sensor,
flags: 0,
outPathLen: 0,
outPath: Uint8List(64),
advName: 'WX Station',
lastAdvert: DateTime.now().millisecondsSinceEpoch ~/ 1000,
advLat: 0,
advLon: 0,
lastMod: DateTime.now().millisecondsSinceEpoch ~/ 1000,
telemetry: ContactTelemetry(
temperature: 21.5,
timestamp: DateTime.now().subtract(const Duration(minutes: 1)),
extraSensorData: const {'__raw_lpp_hex': '01 67 00 d7'},
),
);
await tester.pumpWidget(
MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: Scaffold(
body: SensorTelemetryCard(
contact: contact,
state: SensorRefreshState.idle,
visibleFields: const {'temperature'},
fieldSpans: sensorFullWidthFieldSpans(const {'temperature'}),
),
),
),
);
await tester.tap(find.byIcon(Icons.more_vert));
await tester.pumpAndSettle();
expect(find.text('Copy raw response'), findsOneWidget);
await tester.tap(find.text('Copy raw response'));
await tester.pump();
final clipboardData = await Clipboard.getData(Clipboard.kTextPlain);
expect(clipboardData?.text, '01 67 00 d7');
expect(find.text('Raw response copied'), findsOneWidget);
});
}