mirror of
https://github.com/dz0ny/meshcore-sar.git
synced 2026-08-11 16:30:28 +00:00
Compare commits
19 Commits
v2026.0317
...
v2026.0319
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6145462555 | ||
|
|
721fb7e7a2 | ||
|
|
5a58e45e13 | ||
|
|
de4258c0a4 | ||
|
|
d8cb35c595 | ||
|
|
8da69705ee | ||
|
|
e474168ba8 | ||
|
|
03dba8b3ce | ||
|
|
bc9e37bd22 | ||
|
|
a32d5d2c85 | ||
|
|
e683ab933f | ||
|
|
f286b0afd1 | ||
|
|
68ec72534d | ||
|
|
6af8b62d9b | ||
|
|
01fbb7de6c | ||
|
|
9303d24b69 | ||
|
|
140088fe2f | ||
|
|
67d8e1c906 | ||
|
|
29b75a3155 |
18
.github/workflows/build-artifacts.yml
vendored
18
.github/workflows/build-artifacts.yml
vendored
@@ -40,6 +40,9 @@ jobs:
|
||||
flutter-version: ${{ env.FLUTTER_VERSION }}
|
||||
channel: stable
|
||||
cache: true
|
||||
pub-cache: true
|
||||
cache-key: flutter-${{ runner.os }}-stable-${{ env.FLUTTER_VERSION }}-${{ runner.arch }}
|
||||
pub-cache-key: flutter-pub-${{ runner.os }}-stable-${{ env.FLUTTER_VERSION }}-${{ runner.arch }}-${{ hashFiles('pubspec.lock') }}
|
||||
|
||||
- name: Cache Android NDK
|
||||
uses: actions/cache@v4
|
||||
@@ -95,6 +98,9 @@ jobs:
|
||||
flutter-version: ${{ env.FLUTTER_VERSION }}
|
||||
channel: stable
|
||||
cache: true
|
||||
pub-cache: true
|
||||
cache-key: flutter-${{ runner.os }}-stable-${{ env.FLUTTER_VERSION }}-${{ runner.arch }}
|
||||
pub-cache-key: flutter-pub-${{ runner.os }}-stable-${{ env.FLUTTER_VERSION }}-${{ runner.arch }}-${{ hashFiles('pubspec.lock') }}
|
||||
|
||||
- name: Enable Linux desktop
|
||||
run: flutter config --enable-linux-desktop
|
||||
@@ -132,6 +138,9 @@ jobs:
|
||||
flutter-version: ${{ env.FLUTTER_VERSION }}
|
||||
channel: stable
|
||||
cache: true
|
||||
pub-cache: true
|
||||
cache-key: flutter-${{ runner.os }}-stable-${{ env.FLUTTER_VERSION }}-${{ runner.arch }}
|
||||
pub-cache-key: flutter-pub-${{ runner.os }}-stable-${{ env.FLUTTER_VERSION }}-${{ runner.arch }}-${{ hashFiles('pubspec.lock') }}
|
||||
|
||||
- name: Enable Windows desktop
|
||||
shell: pwsh
|
||||
@@ -174,6 +183,9 @@ jobs:
|
||||
flutter-version: ${{ env.FLUTTER_VERSION }}
|
||||
channel: stable
|
||||
cache: true
|
||||
pub-cache: true
|
||||
cache-key: flutter-${{ runner.os }}-stable-${{ env.FLUTTER_VERSION }}-${{ runner.arch }}
|
||||
pub-cache-key: flutter-pub-${{ runner.os }}-stable-${{ env.FLUTTER_VERSION }}-${{ runner.arch }}-${{ hashFiles('pubspec.lock') }}
|
||||
|
||||
- name: Enable macOS desktop
|
||||
run: flutter config --enable-macos-desktop
|
||||
@@ -216,6 +228,9 @@ jobs:
|
||||
flutter-version: ${{ env.FLUTTER_VERSION }}
|
||||
channel: stable
|
||||
cache: true
|
||||
pub-cache: true
|
||||
cache-key: flutter-${{ runner.os }}-stable-${{ env.FLUTTER_VERSION }}-${{ runner.arch }}
|
||||
pub-cache-key: flutter-pub-${{ runner.os }}-stable-${{ env.FLUTTER_VERSION }}-${{ runner.arch }}-${{ hashFiles('pubspec.lock') }}
|
||||
|
||||
- name: Install dependencies
|
||||
run: flutter pub get
|
||||
@@ -272,6 +287,9 @@ jobs:
|
||||
flutter-version: ${{ env.FLUTTER_VERSION }}
|
||||
channel: stable
|
||||
cache: true
|
||||
pub-cache: true
|
||||
cache-key: flutter-${{ runner.os }}-stable-${{ env.FLUTTER_VERSION }}-${{ runner.arch }}
|
||||
pub-cache-key: flutter-pub-${{ runner.os }}-stable-${{ env.FLUTTER_VERSION }}-${{ runner.arch }}-${{ hashFiles('pubspec.lock') }}
|
||||
|
||||
- name: Enable web
|
||||
run: flutter config --enable-web
|
||||
|
||||
3
.github/workflows/build-multiplatform.yml
vendored
3
.github/workflows/build-multiplatform.yml
vendored
@@ -27,6 +27,9 @@ jobs:
|
||||
flutter-version: ${{ env.FLUTTER_VERSION }}
|
||||
channel: 'stable'
|
||||
cache: true
|
||||
pub-cache: true
|
||||
cache-key: flutter-${{ runner.os }}-stable-${{ env.FLUTTER_VERSION }}-${{ runner.arch }}
|
||||
pub-cache-key: flutter-pub-${{ runner.os }}-stable-${{ env.FLUTTER_VERSION }}-${{ runner.arch }}-${{ hashFiles('pubspec.lock') }}
|
||||
|
||||
- name: Install dependencies
|
||||
run: flutter pub get
|
||||
|
||||
@@ -489,7 +489,7 @@
|
||||
buildSettings = {
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CURRENT_PROJECT_VERSION = 119;
|
||||
CURRENT_PROJECT_VERSION = 122;
|
||||
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 = 119;
|
||||
CURRENT_PROJECT_VERSION = 122;
|
||||
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 = 119;
|
||||
CURRENT_PROJECT_VERSION = 122;
|
||||
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 = 119;
|
||||
CURRENT_PROJECT_VERSION = 122;
|
||||
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 = 119;
|
||||
CURRENT_PROJECT_VERSION = 122;
|
||||
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 = 119;
|
||||
CURRENT_PROJECT_VERSION = 122;
|
||||
DEVELOPMENT_TEAM = JND55328G8;
|
||||
ENABLE_BITCODE = NO;
|
||||
INFOPLIST_FILE = Runner/Info.plist;
|
||||
|
||||
@@ -43,7 +43,7 @@
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>119</string>
|
||||
<string>122</string>
|
||||
<key>LSRequiresIPhoneOS</key>
|
||||
<true/>
|
||||
<key>ITSAppUsesNonExemptEncryption</key>
|
||||
|
||||
@@ -5,22 +5,22 @@
|
||||
|
||||
|
||||
|
||||
<testcase classname="fastlane.lanes" name="0: default_platform" time="0.00024">
|
||||
<testcase classname="fastlane.lanes" name="0: default_platform" time="0.000814">
|
||||
|
||||
</testcase>
|
||||
|
||||
|
||||
<testcase classname="fastlane.lanes" name="1: increment_build_number" time="0.554978">
|
||||
<testcase classname="fastlane.lanes" name="1: increment_build_number" time="0.353323">
|
||||
|
||||
</testcase>
|
||||
|
||||
|
||||
<testcase classname="fastlane.lanes" name="2: build_app" time="100.17557">
|
||||
<testcase classname="fastlane.lanes" name="2: build_app" time="115.148883">
|
||||
|
||||
</testcase>
|
||||
|
||||
|
||||
<testcase classname="fastlane.lanes" name="3: upload_to_app_store" time="264.49426">
|
||||
<testcase classname="fastlane.lanes" name="3: upload_to_app_store" time="204.902574">
|
||||
|
||||
</testcase>
|
||||
|
||||
|
||||
@@ -57,9 +57,7 @@ class Channel {
|
||||
} else {
|
||||
// Normal channel: require explicit secret
|
||||
if (explicitSecret == null || explicitSecret.length != 16) {
|
||||
throw ArgumentError(
|
||||
'Normal channels require a 16-byte secret',
|
||||
);
|
||||
throw ArgumentError('Normal channels require a 16-byte secret');
|
||||
}
|
||||
return Channel(
|
||||
index: index,
|
||||
@@ -78,6 +76,18 @@ class Channel {
|
||||
return Uint8List.fromList(digest.bytes.sublist(0, 16));
|
||||
}
|
||||
|
||||
static bool isHashChannelName(String channelName) {
|
||||
return channelName.trim().startsWith('#');
|
||||
}
|
||||
|
||||
static String pskBase64ForHashChannelName(String channelName) {
|
||||
final normalized = channelName.trim();
|
||||
if (!isHashChannelName(normalized)) {
|
||||
throw ArgumentError('Only #channels can export derived psk_base64');
|
||||
}
|
||||
return base64.encode(_generateHashChannelSecret(normalized));
|
||||
}
|
||||
|
||||
/// Create the default public channel (channel 0)
|
||||
/// Uses the well-known pre-shared key from MeshCore
|
||||
factory Channel.publicChannel() {
|
||||
@@ -85,8 +95,22 @@ class Channel {
|
||||
index: 0,
|
||||
name: 'Public Channel',
|
||||
secret: Uint8List.fromList([
|
||||
0x8b, 0x33, 0x87, 0xe9, 0xc5, 0xcd, 0xea, 0x6a,
|
||||
0xc9, 0xe5, 0xed, 0xba, 0xa1, 0x15, 0xcd, 0x72,
|
||||
0x8b,
|
||||
0x33,
|
||||
0x87,
|
||||
0xe9,
|
||||
0xc5,
|
||||
0xcd,
|
||||
0xea,
|
||||
0x6a,
|
||||
0xc9,
|
||||
0xe5,
|
||||
0xed,
|
||||
0xba,
|
||||
0xa1,
|
||||
0x15,
|
||||
0xcd,
|
||||
0x72,
|
||||
]),
|
||||
flags: null,
|
||||
);
|
||||
@@ -95,6 +119,9 @@ class Channel {
|
||||
/// Check if this is a hash-based channel (name starts with '#')
|
||||
bool get isHashChannel => name.startsWith('#');
|
||||
|
||||
/// Base64-encoded PSK for sharing with firmware CLI and related tooling.
|
||||
String get pskBase64 => base64.encode(secret);
|
||||
|
||||
/// Display name for the channel
|
||||
/// Returns "Public" for channel 0, otherwise returns the custom name or "Channel N"
|
||||
String get displayName {
|
||||
@@ -131,12 +158,7 @@ class Channel {
|
||||
}
|
||||
|
||||
/// Create a copy with modified fields
|
||||
Channel copyWith({
|
||||
int? index,
|
||||
String? name,
|
||||
Uint8List? secret,
|
||||
int? flags,
|
||||
}) {
|
||||
Channel copyWith({int? index, String? name, Uint8List? secret, int? flags}) {
|
||||
return Channel(
|
||||
index: index ?? this.index,
|
||||
name: name ?? this.name,
|
||||
|
||||
@@ -29,7 +29,7 @@ extension ConnectionModeExtension on ConnectionMode {
|
||||
case ConnectionMode.tcp:
|
||||
return 'Direct (WiFi)';
|
||||
case ConnectionMode.usb:
|
||||
return 'Direct (USB)';
|
||||
return 'Direct (Serial)';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ extension ConnectionModeExtension on ConnectionMode {
|
||||
case ConnectionMode.tcp:
|
||||
return 'Direct WiFi/TCP connection to MeshCore device';
|
||||
case ConnectionMode.usb:
|
||||
return 'USB serial connection to MeshCore device';
|
||||
return 'Direct serial connection to MeshCore device';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -107,6 +107,15 @@ class _PendingRepeaterOwnerRequest {
|
||||
const _PendingRepeaterOwnerRequest({required this.publicKey});
|
||||
}
|
||||
|
||||
enum ContactsTabSection {
|
||||
favourites,
|
||||
teamMembers,
|
||||
repeaters,
|
||||
sensors,
|
||||
rooms,
|
||||
channels,
|
||||
}
|
||||
|
||||
/// Main App Provider - coordinates all other providers
|
||||
class AppProvider with ChangeNotifier {
|
||||
static const int _maxDirectPayloadHops = 3;
|
||||
@@ -162,6 +171,9 @@ class AppProvider with ChangeNotifier {
|
||||
bool get isContactsEnabled => _isContactsEnabled;
|
||||
bool _isSensorsEnabled = true;
|
||||
bool get isSensorsEnabled => _isSensorsEnabled;
|
||||
final Map<ContactsTabSection, bool> _contactsSectionVisibility = {
|
||||
for (final section in ContactsTabSection.values) section: true,
|
||||
};
|
||||
|
||||
bool _isVoiceSilenceTrimmingEnabled = true;
|
||||
bool get isVoiceSilenceTrimmingEnabled => _isVoiceSilenceTrimmingEnabled;
|
||||
@@ -238,6 +250,7 @@ class AppProvider with ChangeNotifier {
|
||||
_initializeLocationTracking();
|
||||
_loadMapEnabled();
|
||||
_loadContactsEnabled();
|
||||
_loadContactsSectionVisibility();
|
||||
_loadSensorsEnabled();
|
||||
_loadVoiceSilenceTrimmingEnabled();
|
||||
_loadVoiceBandPassFilterEnabled();
|
||||
@@ -259,6 +272,27 @@ class AppProvider with ChangeNotifier {
|
||||
return ProfileStorageScope.scopedKey(baseKey);
|
||||
}
|
||||
|
||||
bool isContactsSectionEnabled(ContactsTabSection section) {
|
||||
return _contactsSectionVisibility[section] ?? true;
|
||||
}
|
||||
|
||||
String _contactsSectionVisibilityKey(ContactsTabSection section) {
|
||||
switch (section) {
|
||||
case ContactsTabSection.favourites:
|
||||
return 'contacts_section_favourites_enabled';
|
||||
case ContactsTabSection.teamMembers:
|
||||
return 'contacts_section_team_members_enabled';
|
||||
case ContactsTabSection.repeaters:
|
||||
return 'contacts_section_repeaters_enabled';
|
||||
case ContactsTabSection.sensors:
|
||||
return 'contacts_section_sensors_enabled';
|
||||
case ContactsTabSection.rooms:
|
||||
return 'contacts_section_rooms_enabled';
|
||||
case ContactsTabSection.channels:
|
||||
return 'contacts_section_channels_enabled';
|
||||
}
|
||||
}
|
||||
|
||||
void _startPacketCapturePersistence() {
|
||||
_packetCaptureFlushTimer?.cancel();
|
||||
_packetCaptureFlushTimer = Timer.periodic(const Duration(seconds: 2), (_) {
|
||||
@@ -565,6 +599,37 @@ class AppProvider with ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _loadContactsSectionVisibility() async {
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
for (final section in ContactsTabSection.values) {
|
||||
_contactsSectionVisibility[section] =
|
||||
prefs.getBool(_scopedKey(_contactsSectionVisibilityKey(section))) ??
|
||||
true;
|
||||
}
|
||||
notifyListeners();
|
||||
} catch (e) {
|
||||
debugPrint('Error loading contacts section visibility settings: $e');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> setContactsSectionEnabled(
|
||||
ContactsTabSection section,
|
||||
bool enabled,
|
||||
) async {
|
||||
try {
|
||||
_contactsSectionVisibility[section] = enabled;
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setBool(
|
||||
_scopedKey(_contactsSectionVisibilityKey(section)),
|
||||
enabled,
|
||||
);
|
||||
notifyListeners();
|
||||
} catch (e) {
|
||||
debugPrint('Error saving contacts section visibility setting: $e');
|
||||
}
|
||||
}
|
||||
|
||||
/// Load sensors enabled setting from shared preferences
|
||||
Future<void> _loadSensorsEnabled() async {
|
||||
try {
|
||||
@@ -933,9 +998,7 @@ class AppProvider with ChangeNotifier {
|
||||
// we also import into firmware so subsequent getContact calls work.
|
||||
// Matches the official app which calls cmdGetAdvertPath for all adverts.
|
||||
if (source == ContactReceiveSource.advert) {
|
||||
unawaited(
|
||||
connectionProvider.importReceivedAdvert(contact.publicKey),
|
||||
);
|
||||
unawaited(connectionProvider.importReceivedAdvert(contact.publicKey));
|
||||
}
|
||||
final isNewPendingAdvert = contactsProvider
|
||||
.addOrUpdatePendingAdvertContact(
|
||||
@@ -1134,16 +1197,31 @@ class AppProvider with ChangeNotifier {
|
||||
return;
|
||||
}
|
||||
|
||||
// Enrich message with sender name from contacts first
|
||||
// Enrich message with sender name from contacts.
|
||||
// For room-forwarded messages, resolve the original poster's name
|
||||
// from roomPostAuthorPrefix instead of the room server's key.
|
||||
Message enrichedMessage = message;
|
||||
Contact? senderContact;
|
||||
if (message.senderPublicKeyPrefix != null && message.senderName == null) {
|
||||
final contact = contactsProvider.findContactByKey(
|
||||
message.senderPublicKeyPrefix!,
|
||||
);
|
||||
if (contact != null) {
|
||||
senderContact = contact;
|
||||
enrichedMessage = message.copyWith(senderName: contact.advName);
|
||||
if (message.senderName == null) {
|
||||
// Try room post author first (the actual person who posted)
|
||||
if (message.roomPostAuthorPrefix != null) {
|
||||
final author = contactsProvider.findContactByPrefix(
|
||||
message.roomPostAuthorPrefix!,
|
||||
);
|
||||
if (author != null) {
|
||||
senderContact = author;
|
||||
enrichedMessage = message.copyWith(senderName: author.advName);
|
||||
}
|
||||
}
|
||||
// Fall back to sender key (direct messages, or room with unknown author)
|
||||
if (senderContact == null && message.senderPublicKeyPrefix != null) {
|
||||
final contact = contactsProvider.findContactByKey(
|
||||
message.senderPublicKeyPrefix!,
|
||||
);
|
||||
if (contact != null) {
|
||||
senderContact = contact;
|
||||
enrichedMessage = message.copyWith(senderName: contact.advName);
|
||||
}
|
||||
}
|
||||
}
|
||||
senderContact ??= message.senderPublicKeyPrefix != null
|
||||
@@ -1337,12 +1415,13 @@ class AppProvider with ChangeNotifier {
|
||||
if (_handlePendingRepeaterOwnerResponse(tag, responseData)) {
|
||||
return;
|
||||
}
|
||||
debugPrint(
|
||||
'📊 [AppProvider] Binary response (0x8C) received - updating contact telemetry',
|
||||
);
|
||||
// Binary response tag 0 = telemetry data (Cayenne LPP format)
|
||||
// Other tags may be used for different data types in the future
|
||||
contactsProvider.updateTelemetry(publicKeyPrefix, responseData);
|
||||
debugPrint('📊 [AppProvider] Binary response (0x8C tag=$tag) received');
|
||||
// Binary responses carry Cayenne LPP telemetry data.
|
||||
// The data starts with a channel byte — valid LPP always has at least
|
||||
// 3 bytes (channel + type + value). Skip clearly non-telemetry payloads.
|
||||
if (responseData.length >= 3) {
|
||||
contactsProvider.updateTelemetry(publicKeyPrefix, responseData);
|
||||
}
|
||||
};
|
||||
|
||||
// When raw binary data is received (PUSH_CODE_RAW_DATA 0x84)
|
||||
@@ -2141,9 +2220,7 @@ class AppProvider with ChangeNotifier {
|
||||
// already added to pending adverts and showed notification.
|
||||
// Nothing else to do — the callback pipeline handles everything.
|
||||
if (wasKnown) {
|
||||
debugPrint(
|
||||
' [pushAdvert] Existing contact refreshed',
|
||||
);
|
||||
debugPrint(' [pushAdvert] Existing contact refreshed');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2703,6 +2780,7 @@ class AppProvider with ChangeNotifier {
|
||||
await Future.wait([
|
||||
_loadMapEnabled(),
|
||||
_loadContactsEnabled(),
|
||||
_loadContactsSectionVisibility(),
|
||||
_loadSensorsEnabled(),
|
||||
_loadVoiceSilenceTrimmingEnabled(),
|
||||
_loadVoiceBandPassFilterEnabled(),
|
||||
|
||||
@@ -73,6 +73,7 @@ class ConnectionProvider with ChangeNotifier {
|
||||
final MeshCoreBleService _bleService = MeshCoreBleService();
|
||||
MeshCoreTcpService? _tcpService;
|
||||
MeshCoreSerialService? _serialService;
|
||||
Future<void> Function()? _serialDisconnectTransport;
|
||||
|
||||
/// Expose BLE service for background location tracking
|
||||
MeshCoreBleService get bleService => _bleService;
|
||||
@@ -224,6 +225,87 @@ class ConnectionProvider with ChangeNotifier {
|
||||
_wireServiceCallbacks(_bleService);
|
||||
}
|
||||
|
||||
Future<void> _prepareForConnectionSwitch(ConnectionMode nextMode) async {
|
||||
if (_isScanning) {
|
||||
debugPrint('🔵 [Provider] Stopping active scan before connect()');
|
||||
await stopScan();
|
||||
}
|
||||
|
||||
await _disconnectInactiveTransports(nextMode);
|
||||
_error = null;
|
||||
_supportsAutoaddConfig = null;
|
||||
_resetSyncState();
|
||||
}
|
||||
|
||||
Future<void> _disconnectInactiveTransports(ConnectionMode activeMode) async {
|
||||
if (activeMode != ConnectionMode.ble && _bleService.isConnected) {
|
||||
await _bleService.disconnect();
|
||||
}
|
||||
|
||||
if (activeMode != ConnectionMode.tcp && _tcpService != null) {
|
||||
await _disposeTcpService();
|
||||
}
|
||||
|
||||
if (activeMode != ConnectionMode.usb && _serialService != null) {
|
||||
await _disposeSerialService();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _disposeTcpService() async {
|
||||
final service = _tcpService;
|
||||
if (service == null) {
|
||||
return;
|
||||
}
|
||||
_tcpService = null;
|
||||
await service.disconnect();
|
||||
service.dispose();
|
||||
}
|
||||
|
||||
Future<void> _disposeSerialService() async {
|
||||
final service = _serialService;
|
||||
final disconnectTransport = _serialDisconnectTransport;
|
||||
_serialService = null;
|
||||
_serialDisconnectTransport = null;
|
||||
if (service == null) {
|
||||
return;
|
||||
}
|
||||
service.markDisconnected();
|
||||
service.writeRaw = null;
|
||||
if (disconnectTransport != null) {
|
||||
await disconnectTransport();
|
||||
}
|
||||
service.dispose();
|
||||
}
|
||||
|
||||
void _beginConnectionAttempt({
|
||||
required ConnectionMode mode,
|
||||
required String deviceId,
|
||||
required String deviceName,
|
||||
String? tcpHost,
|
||||
}) {
|
||||
_connectionMode = mode;
|
||||
_tcpHost = mode == ConnectionMode.tcp ? tcpHost : null;
|
||||
_deviceInfo = _deviceInfo.copyWith(
|
||||
deviceId: deviceId,
|
||||
deviceName: deviceName,
|
||||
connectionState: ConnectionState.connecting,
|
||||
);
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void _resetConnectionSession({ConnectionMode nextMode = ConnectionMode.ble}) {
|
||||
_tcpHost = nextMode == ConnectionMode.tcp ? _tcpHost : null;
|
||||
_connectionMode = nextMode;
|
||||
_supportsAutoaddConfig = null;
|
||||
_resetSyncState();
|
||||
_deviceInfo = DeviceInfo(connectionState: ConnectionState.disconnected);
|
||||
_roomLoginManager.clearRoomLoginStates();
|
||||
_pingTracker.clearAll();
|
||||
_pendingSendOperations.clear();
|
||||
_messageDeliveryTracker.clearTracking();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
/// Wire all shared event callbacks onto [service].
|
||||
/// Called for both BLE and TCP services so the provider handles events
|
||||
/// identically regardless of transport.
|
||||
@@ -564,6 +646,13 @@ class ConnectionProvider with ChangeNotifier {
|
||||
debugPrint('✅ [Provider] Scan state initialized, notifying listeners');
|
||||
|
||||
try {
|
||||
final adapterError = await _awaitBleAdapterReady();
|
||||
if (adapterError != null) {
|
||||
debugPrint('⚠️ [Provider] BLE adapter not ready: $adapterError');
|
||||
_error = adapterError;
|
||||
return;
|
||||
}
|
||||
|
||||
await for (final scanResult in _bleService.scanForDevices(
|
||||
timeout: const Duration(seconds: 10),
|
||||
)) {
|
||||
@@ -605,6 +694,53 @@ class ConnectionProvider with ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
Future<String?> _awaitBleAdapterReady({
|
||||
Duration timeout = const Duration(seconds: 4),
|
||||
}) async {
|
||||
if (!await FlutterBluePlus.isSupported) {
|
||||
return 'Bluetooth is not supported on this device.';
|
||||
}
|
||||
|
||||
var state = await FlutterBluePlus.adapterState.first;
|
||||
debugPrint('🔵 [Provider] Initial BLE adapter state: $state');
|
||||
|
||||
if (state == BluetoothAdapterState.unknown ||
|
||||
state == BluetoothAdapterState.turningOn) {
|
||||
debugPrint('⏳ [Provider] Waiting for BLE adapter to finish initializing');
|
||||
try {
|
||||
state = await FlutterBluePlus.adapterState
|
||||
.where(
|
||||
(candidate) =>
|
||||
candidate != BluetoothAdapterState.unknown &&
|
||||
candidate != BluetoothAdapterState.turningOn,
|
||||
)
|
||||
.first
|
||||
.timeout(timeout);
|
||||
} on TimeoutException {
|
||||
state = FlutterBluePlus.adapterStateNow;
|
||||
}
|
||||
debugPrint('🔵 [Provider] BLE adapter state after wait: $state');
|
||||
}
|
||||
|
||||
if (state == BluetoothAdapterState.on) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return switch (state) {
|
||||
BluetoothAdapterState.off =>
|
||||
'Bluetooth is turned off. Turn it on and try again.',
|
||||
BluetoothAdapterState.turningOff =>
|
||||
'Bluetooth is turning off. Turn it back on and try again.',
|
||||
BluetoothAdapterState.unauthorized =>
|
||||
'Bluetooth access is not allowed. Check app permissions in System Settings and try again.',
|
||||
BluetoothAdapterState.unavailable =>
|
||||
'Bluetooth hardware is unavailable. On macOS, verify Bluetooth access is enabled for this app target.',
|
||||
BluetoothAdapterState.unknown || BluetoothAdapterState.turningOn =>
|
||||
'Bluetooth is still initializing. Please try again in a moment.',
|
||||
BluetoothAdapterState.on => null,
|
||||
};
|
||||
}
|
||||
|
||||
/// Stop scanning
|
||||
Future<void> stopScan() async {
|
||||
await FlutterBluePlus.stopScan();
|
||||
@@ -629,27 +765,15 @@ class ConnectionProvider with ChangeNotifier {
|
||||
debugPrint(
|
||||
'🔵 [Provider] connect() called for device: ${device.platformName}',
|
||||
);
|
||||
|
||||
if (_isScanning) {
|
||||
debugPrint('🔵 [Provider] Stopping active scan before connect()');
|
||||
await stopScan();
|
||||
}
|
||||
|
||||
// Ensure we route commands to BLE, not a stale TCP service.
|
||||
_connectionMode = ConnectionMode.ble;
|
||||
|
||||
_deviceInfo = _deviceInfo.copyWith(
|
||||
await _prepareForConnectionSwitch(ConnectionMode.ble);
|
||||
_beginConnectionAttempt(
|
||||
mode: ConnectionMode.ble,
|
||||
deviceId: device.remoteId.toString(),
|
||||
deviceName: device.platformName.isNotEmpty
|
||||
? device.platformName
|
||||
: 'Unknown',
|
||||
connectionState: ConnectionState.connecting,
|
||||
);
|
||||
_error = null;
|
||||
_supportsAutoaddConfig = null;
|
||||
_resetSyncState();
|
||||
debugPrint('✅ [Provider] Device info updated to connecting state');
|
||||
notifyListeners();
|
||||
|
||||
debugPrint('🔵 [Provider] Calling BLE service connect()...');
|
||||
final success = await _bleService.connect(device);
|
||||
@@ -669,23 +793,18 @@ class ConnectionProvider with ChangeNotifier {
|
||||
/// Connect to a MeshCore device over TCP/WiFi (port 5000)
|
||||
Future<bool> connectTcp(String host, int port) async {
|
||||
debugPrint('🌐 [Provider] connectTcp() $host:$port');
|
||||
|
||||
_tcpHost = host;
|
||||
_deviceInfo = _deviceInfo.copyWith(
|
||||
deviceId: '$host:$port',
|
||||
deviceName: host,
|
||||
connectionState: ConnectionState.connecting,
|
||||
);
|
||||
_error = null;
|
||||
_supportsAutoaddConfig = null;
|
||||
notifyListeners();
|
||||
await _prepareForConnectionSwitch(ConnectionMode.tcp);
|
||||
|
||||
// Create fresh TCP service and wire its callbacks
|
||||
_tcpService?.dispose();
|
||||
await _disposeTcpService();
|
||||
_tcpService = MeshCoreTcpService();
|
||||
_wireServiceCallbacks(_tcpService!);
|
||||
|
||||
_connectionMode = ConnectionMode.tcp;
|
||||
_beginConnectionAttempt(
|
||||
mode: ConnectionMode.tcp,
|
||||
deviceId: '$host:$port',
|
||||
deviceName: host,
|
||||
tcpHost: host,
|
||||
);
|
||||
|
||||
final success = await _tcpService!.connect(host, port);
|
||||
if (!success) {
|
||||
@@ -699,21 +818,8 @@ class ConnectionProvider with ChangeNotifier {
|
||||
|
||||
/// Disconnect from TCP/WiFi device
|
||||
Future<void> disconnectTcp() async {
|
||||
if (_tcpService != null) {
|
||||
await _tcpService!.disconnect();
|
||||
_tcpService!.dispose();
|
||||
_tcpService = null;
|
||||
}
|
||||
_tcpHost = null;
|
||||
_connectionMode = ConnectionMode.ble;
|
||||
_supportsAutoaddConfig = null;
|
||||
_resetSyncState();
|
||||
_deviceInfo = DeviceInfo(connectionState: ConnectionState.disconnected);
|
||||
_roomLoginManager.clearRoomLoginStates();
|
||||
_pingTracker.clearAll();
|
||||
_pendingSendOperations.clear();
|
||||
_messageDeliveryTracker.clearTracking();
|
||||
notifyListeners();
|
||||
await _disposeTcpService();
|
||||
_resetConnectionSession();
|
||||
}
|
||||
|
||||
/// Connect via USB serial using a pre-configured [MeshCoreSerialService].
|
||||
@@ -721,22 +827,23 @@ class ConnectionProvider with ChangeNotifier {
|
||||
/// The caller is responsible for opening the serial port and wiring
|
||||
/// [service.writeRaw] + [service.feedRawBytes] before calling this.
|
||||
/// After this call succeeds, [service.markConnected()] has already run.
|
||||
Future<bool> connectSerial(MeshCoreSerialService service) async {
|
||||
Future<bool> connectSerial({
|
||||
required MeshCoreSerialService service,
|
||||
required Future<void> Function() disconnectTransport,
|
||||
required String deviceId,
|
||||
required String deviceName,
|
||||
}) async {
|
||||
debugPrint('🔌 [Provider] connectSerial()');
|
||||
|
||||
_deviceInfo = _deviceInfo.copyWith(
|
||||
deviceId: 'usb',
|
||||
deviceName: 'USB Companion',
|
||||
connectionState: ConnectionState.connecting,
|
||||
);
|
||||
_error = null;
|
||||
_supportsAutoaddConfig = null;
|
||||
notifyListeners();
|
||||
|
||||
_serialService?.dispose();
|
||||
await _prepareForConnectionSwitch(ConnectionMode.usb);
|
||||
await _disposeSerialService();
|
||||
_serialService = service;
|
||||
_serialDisconnectTransport = disconnectTransport;
|
||||
_wireServiceCallbacks(_serialService!);
|
||||
_connectionMode = ConnectionMode.usb;
|
||||
_beginConnectionAttempt(
|
||||
mode: ConnectionMode.usb,
|
||||
deviceId: deviceId,
|
||||
deviceName: deviceName,
|
||||
);
|
||||
|
||||
// markConnected() should already have been called by the transport.
|
||||
// If it hasn't, the service won't be connected yet.
|
||||
@@ -744,6 +851,7 @@ class ConnectionProvider with ChangeNotifier {
|
||||
_deviceInfo = _deviceInfo.copyWith(
|
||||
connectionState: ConnectionState.error,
|
||||
);
|
||||
await _disposeSerialService();
|
||||
notifyListeners();
|
||||
return false;
|
||||
}
|
||||
@@ -752,18 +860,8 @@ class ConnectionProvider with ChangeNotifier {
|
||||
|
||||
/// Disconnect from USB serial device.
|
||||
Future<void> disconnectSerial() async {
|
||||
_serialService?.markDisconnected();
|
||||
_serialService?.dispose();
|
||||
_serialService = null;
|
||||
_connectionMode = ConnectionMode.ble;
|
||||
_supportsAutoaddConfig = null;
|
||||
_resetSyncState();
|
||||
_deviceInfo = DeviceInfo(connectionState: ConnectionState.disconnected);
|
||||
_roomLoginManager.clearRoomLoginStates();
|
||||
_pingTracker.clearAll();
|
||||
_pendingSendOperations.clear();
|
||||
_messageDeliveryTracker.clearTracking();
|
||||
notifyListeners();
|
||||
await _disposeSerialService();
|
||||
_resetConnectionSession();
|
||||
}
|
||||
|
||||
/// Disconnect from device
|
||||
@@ -783,15 +881,7 @@ class ConnectionProvider with ChangeNotifier {
|
||||
}
|
||||
|
||||
await _bleService.disconnect();
|
||||
|
||||
_supportsAutoaddConfig = null;
|
||||
_resetSyncState();
|
||||
_deviceInfo = DeviceInfo(connectionState: ConnectionState.disconnected);
|
||||
_roomLoginManager.clearRoomLoginStates();
|
||||
_pingTracker.clearAll();
|
||||
_pendingSendOperations.clear();
|
||||
_messageDeliveryTracker.clearTracking();
|
||||
notifyListeners();
|
||||
_resetConnectionSession();
|
||||
}
|
||||
|
||||
/// Reset message sync state so the next connect/reconnect can sync cleanly.
|
||||
@@ -2267,9 +2357,7 @@ class ConnectionProvider with ChangeNotifier {
|
||||
if (!_activeService.isConnected) return null;
|
||||
try {
|
||||
final frame = await _activeService.exportContact(publicKey);
|
||||
final hex = frame
|
||||
.map((b) => b.toRadixString(16).padLeft(2, '0'))
|
||||
.join();
|
||||
final hex = frame.map((b) => b.toRadixString(16).padLeft(2, '0')).join();
|
||||
return 'meshcore://$hex';
|
||||
} catch (e) {
|
||||
debugPrint('⚠️ [Provider] exportContact failed: $e');
|
||||
@@ -2347,6 +2435,24 @@ class ConnectionProvider with ChangeNotifier {
|
||||
/// - Total storage in KB (if available)
|
||||
///
|
||||
/// Results arrive via onBatteryAndStorage callback and update deviceInfo.
|
||||
/// Request the companion device's own telemetry (GPS, temp, sensors).
|
||||
/// The response arrives via onTelemetryReceived with the device's own key.
|
||||
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,
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('⚠️ [Provider] requestSelfTelemetry failed: $e');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> getBatteryAndStorage() async {
|
||||
if (!_activeService.isConnected) {
|
||||
_error = 'Not connected to device';
|
||||
@@ -2737,6 +2843,12 @@ class ConnectionProvider with ChangeNotifier {
|
||||
_rxActivityTimer?.cancel();
|
||||
_txActivityTimer?.cancel();
|
||||
_stopAckCleanupTimer();
|
||||
final disconnectTransport = _serialDisconnectTransport;
|
||||
if (disconnectTransport != null) {
|
||||
unawaited(disconnectTransport());
|
||||
_serialDisconnectTransport = null;
|
||||
}
|
||||
_serialService?.dispose();
|
||||
_bleService.dispose();
|
||||
_tcpService?.dispose();
|
||||
super.dispose();
|
||||
|
||||
@@ -926,6 +926,10 @@ class ContactsProvider with ChangeNotifier {
|
||||
}
|
||||
|
||||
/// Update contact telemetry
|
||||
// Dedup: track last telemetry data hash per contact to avoid processing
|
||||
// the same payload twice (0x8B + 0x8C can both fire for the same data).
|
||||
final Map<String, (int, DateTime)> _lastTelemetryHash = {};
|
||||
|
||||
void updateTelemetry(Uint8List publicKeyPrefix, Uint8List lppData) {
|
||||
debugPrint('📊 [ContactsProvider] updateTelemetry() called');
|
||||
debugPrint(
|
||||
@@ -933,6 +937,21 @@ class ContactsProvider with ChangeNotifier {
|
||||
);
|
||||
debugPrint(' LPP data size: ${lppData.length} bytes');
|
||||
|
||||
// Deduplicate: same data for same contact within 2 seconds = skip
|
||||
final prefixHex = publicKeyPrefix
|
||||
.map((b) => b.toRadixString(16).padLeft(2, '0'))
|
||||
.join();
|
||||
final dataHash = lppData.fold<int>(0, (h, b) => h * 31 + b);
|
||||
final now = DateTime.now();
|
||||
final last = _lastTelemetryHash[prefixHex];
|
||||
if (last != null &&
|
||||
last.$1 == dataHash &&
|
||||
now.difference(last.$2).inSeconds < 2) {
|
||||
debugPrint(' ⏭️ Duplicate telemetry payload, skipping');
|
||||
return;
|
||||
}
|
||||
_lastTelemetryHash[prefixHex] = (dataHash, now);
|
||||
|
||||
// Find contact by public key prefix
|
||||
final contact = _findContactByPrefix(publicKeyPrefix);
|
||||
if (contact == null) {
|
||||
@@ -1176,10 +1195,11 @@ class ContactsProvider with ChangeNotifier {
|
||||
|
||||
/// Find contact by public key prefix (6 bytes)
|
||||
Contact? _findContactByPrefix(Uint8List prefix) {
|
||||
if (prefix.length < 6) return null;
|
||||
if (prefix.isEmpty) return null;
|
||||
|
||||
final takeLen = prefix.length < 6 ? prefix.length : 6;
|
||||
final prefixHex = prefix
|
||||
.sublist(0, 6)
|
||||
.sublist(0, takeLen)
|
||||
.map((b) => b.toRadixString(16).padLeft(2, '0'))
|
||||
.join('');
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -729,9 +729,9 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
setState(() => _gpsLoading = false);
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('Failed to set GPS mode: $e')),
|
||||
);
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(SnackBar(content: Text('Failed to set GPS mode: $e')));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -893,7 +893,9 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
|
||||
.toList();
|
||||
if (contacts.isEmpty) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text(AppLocalizations.of(context)!.noDeviceContactsToClear)),
|
||||
SnackBar(
|
||||
content: Text(AppLocalizations.of(context)!.noDeviceContactsToClear),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
@@ -988,7 +990,9 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
|
||||
.toList();
|
||||
if (channels.isEmpty) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text(AppLocalizations.of(context)!.noCustomChannelsToClear)),
|
||||
SnackBar(
|
||||
content: Text(AppLocalizations.of(context)!.noCustomChannelsToClear),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
@@ -1095,19 +1099,8 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: Text(AppLocalizations.of(context)!.settings)),
|
||||
body: Container(
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
colors: [
|
||||
colorScheme.primaryContainer.withValues(alpha: 0.55),
|
||||
colorScheme.surface,
|
||||
colorScheme.surface,
|
||||
],
|
||||
begin: Alignment.topCenter,
|
||||
end: Alignment.bottomCenter,
|
||||
stops: const [0.0, 0.22, 1.0],
|
||||
),
|
||||
),
|
||||
body: ColoredBox(
|
||||
color: colorScheme.surface,
|
||||
child: SafeArea(
|
||||
child: ListView(
|
||||
padding: const EdgeInsets.fromLTRB(16, 12, 16, 24),
|
||||
@@ -1146,7 +1139,9 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
|
||||
SizedBox(height: 20),
|
||||
_ConfigSectionCard(
|
||||
title: AppLocalizations.of(context)!.storage,
|
||||
subtitle: AppLocalizations.of(context)!.availableSpaceOnThisDevice,
|
||||
subtitle: AppLocalizations.of(
|
||||
context,
|
||||
)!.availableSpaceOnThisDevice,
|
||||
icon: Icons.storage_rounded,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
@@ -1190,7 +1185,9 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
|
||||
icon: _autoAddDiscoveredContactsEnabled
|
||||
? Icons.person_add_alt_1
|
||||
: Icons.person_add_disabled,
|
||||
title: AppLocalizations.of(context)!.enableAutomaticAdding,
|
||||
title: AppLocalizations.of(
|
||||
context,
|
||||
)!.enableAutomaticAdding,
|
||||
description:
|
||||
'Turn this off to keep discoveries manual-only on the radio.',
|
||||
accentColor: _autoAddDiscoveredContactsEnabled
|
||||
@@ -1293,7 +1290,9 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
|
||||
SizedBox(height: 14),
|
||||
_SettingHighlightCard(
|
||||
icon: Icons.history_toggle_off_rounded,
|
||||
title: AppLocalizations.of(context)!.overwriteOldestWhenFull,
|
||||
title: AppLocalizations.of(
|
||||
context,
|
||||
)!.overwriteOldestWhenFull,
|
||||
description:
|
||||
'Allow the radio to replace the oldest contact when storage is full.',
|
||||
accentColor: _overwriteOldestAutoAddEnabled
|
||||
@@ -1329,7 +1328,9 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
|
||||
: _saveAutoDiscoverySettings,
|
||||
isSaving: _isSavingAutoDiscoverySettings,
|
||||
isSaved: _autoDiscoverySettingsSaved,
|
||||
label: AppLocalizations.of(context)!.saveDiscoverySettings,
|
||||
label: AppLocalizations.of(
|
||||
context,
|
||||
)!.saveDiscoverySettings,
|
||||
),
|
||||
),
|
||||
],
|
||||
@@ -1338,7 +1339,9 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
|
||||
SizedBox(height: 20),
|
||||
_ConfigSectionCard(
|
||||
title: AppLocalizations.of(context)!.publicInfo,
|
||||
subtitle: AppLocalizations.of(context)!.chooseTheNameAndLocationThisDeviceShares,
|
||||
subtitle: AppLocalizations.of(
|
||||
context,
|
||||
)!.chooseTheNameAndLocationThisDeviceShares,
|
||||
icon: Icons.public_rounded,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
@@ -1368,9 +1371,7 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
|
||||
if (_gpsEnabled != null) ...[
|
||||
const SizedBox(height: 12),
|
||||
_SettingHighlightCard(
|
||||
icon: _gpsEnabled!
|
||||
? Icons.gps_fixed
|
||||
: Icons.gps_off,
|
||||
icon: _gpsEnabled! ? Icons.gps_fixed : Icons.gps_off,
|
||||
title: AppLocalizations.of(context)!.gpsModule,
|
||||
description:
|
||||
'Enable or disable the onboard GPS hardware.',
|
||||
@@ -1411,13 +1412,9 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
|
||||
Container(
|
||||
padding: const EdgeInsets.all(14),
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.surface.withValues(alpha: 0.65),
|
||||
color: colorScheme.surfaceContainerLow,
|
||||
borderRadius: BorderRadius.circular(22),
|
||||
border: Border.all(
|
||||
color: colorScheme.outlineVariant.withValues(
|
||||
alpha: 0.7,
|
||||
),
|
||||
),
|
||||
border: Border.all(color: colorScheme.outlineVariant),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
@@ -1492,7 +1489,9 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
|
||||
SizedBox(height: 20),
|
||||
_ConfigSectionCard(
|
||||
title: AppLocalizations.of(context)!.radioSettings,
|
||||
subtitle: AppLocalizations.of(context)!.chooseAPresetOrFinetuneCustomRadioSettings,
|
||||
subtitle: AppLocalizations.of(
|
||||
context,
|
||||
)!.chooseAPresetOrFinetuneCustomRadioSettings,
|
||||
icon: Icons.settings_input_antenna_rounded,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
@@ -1716,7 +1715,9 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
|
||||
SizedBox(height: 16),
|
||||
_SettingHighlightCard(
|
||||
icon: Icons.repeat_rounded,
|
||||
title: AppLocalizations.of(context)!.repeatNearbyTraffic,
|
||||
title: AppLocalizations.of(
|
||||
context,
|
||||
)!.repeatNearbyTraffic,
|
||||
description:
|
||||
deviceInfo.allowedRepeatFreqRanges != null &&
|
||||
deviceInfo.allowedRepeatFreqRanges!.isNotEmpty
|
||||
@@ -1762,7 +1763,9 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
|
||||
SizedBox(height: 20),
|
||||
_ConfigSectionCard(
|
||||
title: AppLocalizations.of(context)!.dangerZone,
|
||||
subtitle: AppLocalizations.of(context)!.destructiveDeviceActions,
|
||||
subtitle: AppLocalizations.of(
|
||||
context,
|
||||
)!.destructiveDeviceActions,
|
||||
icon: Icons.warning_amber_rounded,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
@@ -1770,13 +1773,9 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
|
||||
Container(
|
||||
padding: const EdgeInsets.all(14),
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.errorContainer.withValues(
|
||||
alpha: 0.55,
|
||||
),
|
||||
color: colorScheme.surfaceContainerLow,
|
||||
borderRadius: BorderRadius.circular(22),
|
||||
border: Border.all(
|
||||
color: colorScheme.error.withValues(alpha: 0.28),
|
||||
),
|
||||
border: Border.all(color: colorScheme.error),
|
||||
),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
@@ -1794,14 +1793,14 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
|
||||
'Wipe data on device',
|
||||
style: theme.textTheme.titleSmall?.copyWith(
|
||||
fontWeight: FontWeight.w800,
|
||||
color: colorScheme.onErrorContainer,
|
||||
color: colorScheme.onSurface,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'Erase contacts, keys, and radio settings from the connected MeshCore device and return it to factory defaults.',
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: colorScheme.onErrorContainer,
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
@@ -1831,7 +1830,9 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
|
||||
),
|
||||
)
|
||||
: Icon(Icons.people_alt_outlined),
|
||||
label: Text(AppLocalizations.of(context)!.clearAllContacts),
|
||||
label: Text(
|
||||
AppLocalizations.of(context)!.clearAllContacts,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
@@ -1855,7 +1856,9 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
|
||||
),
|
||||
)
|
||||
: Icon(Icons.forum_outlined),
|
||||
label: Text(AppLocalizations.of(context)!.clearAllChannels),
|
||||
label: Text(
|
||||
AppLocalizations.of(context)!.clearAllChannels,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
@@ -1871,7 +1874,9 @@ class _DeviceConfigScreenState extends State<DeviceConfigScreen> {
|
||||
minimumSize: const Size.fromHeight(52),
|
||||
),
|
||||
icon: Icon(Icons.delete_forever_rounded),
|
||||
label: Text(AppLocalizations.of(context)!.wipeDeviceData),
|
||||
label: Text(
|
||||
AppLocalizations.of(context)!.wipeDeviceData,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
@@ -1930,26 +1935,9 @@ class _ConfigHeroCard extends StatelessWidget {
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(22),
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
colors: [
|
||||
colorScheme.primaryContainer,
|
||||
colorScheme.primary.withValues(alpha: 0.14),
|
||||
colorScheme.surfaceContainerHighest,
|
||||
],
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
),
|
||||
color: colorScheme.surfaceContainerLow,
|
||||
borderRadius: BorderRadius.circular(28),
|
||||
border: Border.all(
|
||||
color: colorScheme.onPrimaryContainer.withValues(alpha: 0.08),
|
||||
),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: colorScheme.primary.withValues(alpha: 0.10),
|
||||
blurRadius: 26,
|
||||
offset: const Offset(0, 12),
|
||||
),
|
||||
],
|
||||
border: Border.all(color: colorScheme.outlineVariant),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
@@ -1960,13 +1948,10 @@ class _ConfigHeroCard extends StatelessWidget {
|
||||
width: 56,
|
||||
height: 56,
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.onPrimaryContainer.withValues(alpha: 0.12),
|
||||
color: colorScheme.surfaceContainerHighest,
|
||||
borderRadius: BorderRadius.circular(18),
|
||||
),
|
||||
child: Icon(
|
||||
Icons.tune_rounded,
|
||||
color: colorScheme.onPrimaryContainer,
|
||||
),
|
||||
child: Icon(Icons.tune_rounded, color: colorScheme.primary),
|
||||
),
|
||||
const SizedBox(width: 14),
|
||||
Expanded(
|
||||
@@ -1979,15 +1964,13 @@ class _ConfigHeroCard extends StatelessWidget {
|
||||
vertical: 6,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.onPrimaryContainer.withValues(
|
||||
alpha: 0.10,
|
||||
),
|
||||
color: colorScheme.surfaceContainerHighest,
|
||||
borderRadius: BorderRadius.circular(999),
|
||||
),
|
||||
child: Text(
|
||||
'Device settings',
|
||||
style: theme.textTheme.labelMedium?.copyWith(
|
||||
color: colorScheme.onPrimaryContainer,
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
@@ -1997,16 +1980,14 @@ class _ConfigHeroCard extends StatelessWidget {
|
||||
title,
|
||||
style: theme.textTheme.headlineSmall?.copyWith(
|
||||
fontWeight: FontWeight.w800,
|
||||
color: colorScheme.onPrimaryContainer,
|
||||
color: colorScheme.onSurface,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
subtitle,
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
color: colorScheme.onPrimaryContainer.withValues(
|
||||
alpha: 0.82,
|
||||
),
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
height: 1.35,
|
||||
),
|
||||
),
|
||||
@@ -2050,23 +2031,24 @@ class _HeroStat extends StatelessWidget {
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final colorScheme = theme.colorScheme;
|
||||
final background = data.emphasized
|
||||
? colorScheme.primary.withValues(alpha: 0.18)
|
||||
: colorScheme.onPrimaryContainer.withValues(alpha: 0.10);
|
||||
final iconColor = data.emphasized
|
||||
? colorScheme.primary
|
||||
: colorScheme.onSurfaceVariant;
|
||||
final borderColor = data.emphasized
|
||||
? colorScheme.primary
|
||||
: colorScheme.outlineVariant;
|
||||
|
||||
return Container(
|
||||
constraints: const BoxConstraints(minWidth: 140),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
|
||||
decoration: BoxDecoration(
|
||||
color: background,
|
||||
color: colorScheme.surfaceContainerHighest,
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
border: Border.all(
|
||||
color: colorScheme.onPrimaryContainer.withValues(alpha: 0.08),
|
||||
),
|
||||
border: Border.all(color: borderColor),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(data.icon, size: 18, color: colorScheme.onPrimaryContainer),
|
||||
Icon(data.icon, size: 18, color: iconColor),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Column(
|
||||
@@ -2075,9 +2057,7 @@ class _HeroStat extends StatelessWidget {
|
||||
Text(
|
||||
data.label,
|
||||
style: theme.textTheme.labelMedium?.copyWith(
|
||||
color: colorScheme.onPrimaryContainer.withValues(
|
||||
alpha: 0.76,
|
||||
),
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
@@ -2086,7 +2066,7 @@ class _HeroStat extends StatelessWidget {
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: theme.textTheme.titleSmall?.copyWith(
|
||||
color: colorScheme.onPrimaryContainer,
|
||||
color: colorScheme.onSurface,
|
||||
fontWeight: FontWeight.w800,
|
||||
),
|
||||
),
|
||||
@@ -2118,7 +2098,9 @@ class _ConfigSectionCard extends StatelessWidget {
|
||||
final colorScheme = theme.colorScheme;
|
||||
|
||||
return Card(
|
||||
color: colorScheme.surfaceContainerLow,
|
||||
elevation: 0,
|
||||
surfaceTintColor: Colors.transparent,
|
||||
clipBehavior: Clip.antiAlias,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(28)),
|
||||
child: Padding(
|
||||
@@ -2133,7 +2115,7 @@ class _ConfigSectionCard extends StatelessWidget {
|
||||
width: 42,
|
||||
height: 42,
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.primary.withValues(alpha: 0.10),
|
||||
color: colorScheme.surfaceContainerHighest,
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
),
|
||||
child: Icon(icon, color: colorScheme.primary),
|
||||
@@ -2259,14 +2241,7 @@ class _StorageUsageMeter extends StatelessWidget {
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(14),
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
colors: [
|
||||
colorScheme.surfaceContainerHighest.withValues(alpha: 0.65),
|
||||
colorScheme.surfaceContainer,
|
||||
],
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
),
|
||||
color: colorScheme.surfaceContainerLow,
|
||||
borderRadius: BorderRadius.circular(18),
|
||||
border: Border.all(color: colorScheme.outlineVariant),
|
||||
),
|
||||
@@ -2321,9 +2296,9 @@ class _SelectedPresetCard extends StatelessWidget {
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.all(14),
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.primaryContainer.withValues(alpha: 0.55),
|
||||
color: colorScheme.surfaceContainerLow,
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
border: Border.all(color: colorScheme.primary.withValues(alpha: 0.18)),
|
||||
border: Border.all(color: colorScheme.outlineVariant),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
@@ -2418,16 +2393,9 @@ class _SettingHighlightCard extends StatelessWidget {
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
colors: [
|
||||
accentColor.withValues(alpha: 0.14),
|
||||
colorScheme.surfaceContainerHigh.withValues(alpha: 0.85),
|
||||
],
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
),
|
||||
color: colorScheme.surfaceContainerLow,
|
||||
borderRadius: BorderRadius.circular(22),
|
||||
border: Border.all(color: accentColor.withValues(alpha: 0.18)),
|
||||
border: Border.all(color: colorScheme.outlineVariant),
|
||||
),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
@@ -2436,7 +2404,7 @@ class _SettingHighlightCard extends StatelessWidget {
|
||||
width: 42,
|
||||
height: 42,
|
||||
decoration: BoxDecoration(
|
||||
color: accentColor.withValues(alpha: 0.16),
|
||||
color: colorScheme.surfaceContainerHighest,
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
),
|
||||
child: Icon(icon, color: accentColor),
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
@@ -6,7 +8,8 @@ import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:vibration/vibration.dart';
|
||||
import '../providers/connection_provider.dart';
|
||||
import '../providers/app_provider.dart';
|
||||
import '../models/device_info.dart' show ConnectionMode;
|
||||
import '../models/contact.dart';
|
||||
import '../models/device_info.dart' show ConnectionMode, DeviceInfo;
|
||||
import '../providers/messages_provider.dart';
|
||||
import '../providers/contacts_provider.dart';
|
||||
import '../theme/app_theme.dart';
|
||||
@@ -29,7 +32,9 @@ import '../widgets/connection_dialog.dart';
|
||||
import '../utils/battery_display_helper.dart';
|
||||
import '../services/developer_mode_service.dart';
|
||||
import '../services/mesh_map_nodes_service.dart';
|
||||
import '../services/profile_device_key_resolver.dart';
|
||||
import '../services/profile_manager.dart';
|
||||
import '../services/profile_workspace_coordinator.dart';
|
||||
import '../services/profiles_feature_service.dart';
|
||||
|
||||
enum _HomeTab { messages, contacts, sensors, map }
|
||||
@@ -60,6 +65,7 @@ class _HomeScreenState extends State<HomeScreen>
|
||||
with TickerProviderStateMixin, WidgetsBindingObserver {
|
||||
late TabController _tabController;
|
||||
late final AppProvider _appProvider;
|
||||
late final ConnectionProvider _connectionProvider;
|
||||
int _currentIndex = 0;
|
||||
bool _isMapFullscreen = false;
|
||||
bool _showRxTxIndicators = true;
|
||||
@@ -68,6 +74,7 @@ class _HomeScreenState extends State<HomeScreen>
|
||||
bool _isContactsEnabled = true;
|
||||
bool _isSensorsEnabled = false;
|
||||
AppLifecycleState _lifecycleState = AppLifecycleState.resumed;
|
||||
String? _lastProfileDeviceKey;
|
||||
|
||||
List<_HomeTab> get _enabledTabs {
|
||||
return [
|
||||
@@ -91,6 +98,8 @@ class _HomeScreenState extends State<HomeScreen>
|
||||
super.initState();
|
||||
WidgetsBinding.instance.addObserver(this);
|
||||
_appProvider = context.read<AppProvider>();
|
||||
_connectionProvider = context.read<ConnectionProvider>();
|
||||
_connectionProvider.addListener(_handleConnectionProviderChanged);
|
||||
_isMapEnabled = _appProvider.isMapEnabled;
|
||||
_isContactsEnabled = _appProvider.isContactsEnabled;
|
||||
_isSensorsEnabled = _appProvider.isSensorsEnabled;
|
||||
@@ -108,6 +117,10 @@ class _HomeScreenState extends State<HomeScreen>
|
||||
_showPermissionDialog();
|
||||
});
|
||||
}
|
||||
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
_handleConnectionProviderChanged();
|
||||
});
|
||||
}
|
||||
|
||||
void _initTabController() {
|
||||
@@ -223,6 +236,36 @@ class _HomeScreenState extends State<HomeScreen>
|
||||
);
|
||||
}
|
||||
|
||||
void _handleConnectionProviderChanged() {
|
||||
final deviceKey = ProfileDeviceKeyResolver.resolve(
|
||||
deviceInfo: _connectionProvider.deviceInfo,
|
||||
connectionMode: _connectionProvider.connectionMode,
|
||||
);
|
||||
if (_lastProfileDeviceKey == deviceKey) {
|
||||
return;
|
||||
}
|
||||
_lastProfileDeviceKey = deviceKey;
|
||||
if (deviceKey == null || !mounted) {
|
||||
return;
|
||||
}
|
||||
unawaited(
|
||||
context
|
||||
.read<ProfileWorkspaceCoordinator>()
|
||||
.syncActiveProfileForCurrentDevice(),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_connectionProvider.removeListener(_handleConnectionProviderChanged);
|
||||
WidgetsBinding.instance.removeObserver(this);
|
||||
_appProvider.setFastLocationUiActive(false);
|
||||
_appProvider.removeListener(_handleAppProviderChanged);
|
||||
_tabController.removeListener(_onTabChanged);
|
||||
_tabController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _openLiveTraffic(ConnectionProvider provider) {
|
||||
openLiveTrafficScreen(context, provider);
|
||||
}
|
||||
@@ -257,16 +300,6 @@ class _HomeScreenState extends State<HomeScreen>
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
WidgetsBinding.instance.removeObserver(this);
|
||||
_appProvider.setFastLocationUiActive(false);
|
||||
_appProvider.removeListener(_handleAppProviderChanged);
|
||||
_tabController.removeListener(_onTabChanged);
|
||||
_tabController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _showPermissionDialog() {
|
||||
if (!mounted) return;
|
||||
|
||||
@@ -402,10 +435,168 @@ class _HomeScreenState extends State<HomeScreen>
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildMiniSignalBars({
|
||||
required int activeBars,
|
||||
required Color color,
|
||||
}) {
|
||||
void _showDeviceInfoSheet(BuildContext context, DeviceInfo deviceInfo) {
|
||||
// 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),
|
||||
),
|
||||
),
|
||||
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)}',
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _deviceInfoRow(
|
||||
BuildContext context,
|
||||
IconData icon,
|
||||
String label,
|
||||
String value,
|
||||
) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 6),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(icon, size: 18, color: Theme.of(context).colorScheme.primary),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(label, style: Theme.of(context).textTheme.bodyMedium),
|
||||
),
|
||||
Text(
|
||||
value,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildMiniSignalBars({required int activeBars, required Color color}) {
|
||||
final inactive = Colors.grey.withValues(alpha: 0.3);
|
||||
return Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
@@ -914,19 +1105,35 @@ class _HomeScreenState extends State<HomeScreen>
|
||||
final isTcpConnected = provider.connectionMode == ConnectionMode.tcp;
|
||||
|
||||
if (!isConnected) {
|
||||
// Disconnected state: show connect button
|
||||
final buttonLabel = provider.isReconnecting
|
||||
? '${provider.reconnectionAttempt}/${provider.maxReconnectionAttempts}'
|
||||
: AppLocalizations.of(context)!.connect;
|
||||
return Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
AppLocalizations.of(context)!.appTitle,
|
||||
style: const TextStyle(
|
||||
fontSize: 20,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
AppLocalizations.of(context)!.appTitle,
|
||||
style: const TextStyle(
|
||||
fontSize: 20,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
provider.isReconnecting
|
||||
? 'Restoring previous link'
|
||||
: 'No device connected',
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
ElevatedButton.icon(
|
||||
FilledButton.icon(
|
||||
onPressed: provider.isReconnecting
|
||||
? null
|
||||
: () => _showConnectionDialog(context),
|
||||
@@ -937,22 +1144,19 @@ class _HomeScreenState extends State<HomeScreen>
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
valueColor: AlwaysStoppedAnimation<Color>(
|
||||
Colors.black54,
|
||||
Colors.white70,
|
||||
),
|
||||
),
|
||||
)
|
||||
: Icon(Icons.bluetooth, size: 18),
|
||||
label: Text(
|
||||
provider.isReconnecting
|
||||
? '${provider.reconnectionAttempt}/${provider.maxReconnectionAttempts}'
|
||||
: AppLocalizations.of(context)!.connect,
|
||||
),
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: Colors.white,
|
||||
foregroundColor: Colors.black87,
|
||||
elevation: 0,
|
||||
: const Icon(Icons.add_link_rounded, size: 18),
|
||||
label: Text(buttonLabel),
|
||||
style: FilledButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 16,
|
||||
vertical: 12,
|
||||
),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -1019,7 +1223,12 @@ class _HomeScreenState extends State<HomeScreen>
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Row(
|
||||
GestureDetector(
|
||||
onTap: () => _showDeviceInfoSheet(
|
||||
context,
|
||||
deviceInfo,
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
@@ -1033,9 +1242,10 @@ class _HomeScreenState extends State<HomeScreen>
|
||||
deviceInfo.signalRssi != null) ...[
|
||||
const SizedBox(width: 4),
|
||||
_buildMiniSignalBars(
|
||||
activeBars: BatteryDisplayHelper.getSignalBars(
|
||||
deviceInfo.signalRssi!,
|
||||
),
|
||||
activeBars:
|
||||
BatteryDisplayHelper.getSignalBars(
|
||||
deviceInfo.signalRssi!,
|
||||
),
|
||||
color: signalColor,
|
||||
),
|
||||
],
|
||||
@@ -1066,6 +1276,7 @@ class _HomeScreenState extends State<HomeScreen>
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
@@ -1162,9 +1373,9 @@ class _HomeScreenState extends State<HomeScreen>
|
||||
);
|
||||
},
|
||||
child: _buildCompactActivityIndicator(
|
||||
rxActive: provider.rxActivity,
|
||||
txActive: provider.txActivity,
|
||||
),
|
||||
rxActive: provider.rxActivity,
|
||||
txActive: provider.txActivity,
|
||||
),
|
||||
)
|
||||
else
|
||||
const SizedBox(width: 24),
|
||||
|
||||
@@ -27,7 +27,6 @@ T? _maybeProvider<T>(BuildContext context) {
|
||||
|
||||
class LiveTrafficScreen extends StatefulWidget {
|
||||
final List<BlePacketLog> Function() logReader;
|
||||
final int Function()? rxCountReader;
|
||||
final Listenable? refreshListenable;
|
||||
final DateTime Function() now;
|
||||
final VoidCallback? openPacketLogs;
|
||||
@@ -35,7 +34,6 @@ class LiveTrafficScreen extends StatefulWidget {
|
||||
const LiveTrafficScreen({
|
||||
super.key,
|
||||
required this.logReader,
|
||||
this.rxCountReader,
|
||||
this.refreshListenable,
|
||||
DateTime Function()? now,
|
||||
this.openPacketLogs,
|
||||
@@ -49,7 +47,6 @@ class LiveTrafficScreen extends StatefulWidget {
|
||||
return LiveTrafficScreen(
|
||||
key: key,
|
||||
logReader: () => provider.bleService.packetLogs,
|
||||
rxCountReader: () => provider.rxPacketCount,
|
||||
refreshListenable: provider,
|
||||
openPacketLogs: openPacketLogs,
|
||||
);
|
||||
@@ -118,15 +115,17 @@ class _LiveTrafficScreenState extends State<LiveTrafficScreen> {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final logs = widget.logReader();
|
||||
final totalRxDataCount = LiveTrafficSummary.countRxDataLogs(logs);
|
||||
final unfilteredSnapshot = LiveTrafficSummary.fromLogs(
|
||||
widget.logReader(),
|
||||
logs,
|
||||
now: widget.now(),
|
||||
clearedAt: _clearedAt,
|
||||
preferredHashSize: _preferredHashSize,
|
||||
window: _selectedWindow,
|
||||
);
|
||||
final snapshot = LiveTrafficSummary.fromLogs(
|
||||
widget.logReader(),
|
||||
logs,
|
||||
now: widget.now(),
|
||||
clearedAt: _clearedAt,
|
||||
preferredHashSize: _preferredHashSize,
|
||||
@@ -177,7 +176,7 @@ class _LiveTrafficScreenState extends State<LiveTrafficScreen> {
|
||||
children: [
|
||||
_SummaryPanel(
|
||||
snapshot: snapshot,
|
||||
totalRxCount: widget.rxCountReader?.call(),
|
||||
totalRxCount: totalRxDataCount,
|
||||
routeHashCounts: routeHashCounts,
|
||||
onWindowTap: () => _showWindowPicker(context),
|
||||
),
|
||||
@@ -306,8 +305,48 @@ class _SummaryPanel extends StatelessWidget {
|
||||
LiveTrafficBusyness.active => 'Active',
|
||||
LiveTrafficBusyness.busy => 'Busy',
|
||||
};
|
||||
final metrics = [
|
||||
_MetricTile(
|
||||
tileKey: const ValueKey('liveTrafficMetric:rxPackets'),
|
||||
label: AppLocalizations.of(context)!.rxPackets,
|
||||
value: '${snapshot.rxCount}',
|
||||
subtitle: totalRxCount == null
|
||||
? _windowSummaryLabel(snapshot.windowDuration)
|
||||
: 'Device total $totalRxCount',
|
||||
),
|
||||
_MetricTile(
|
||||
tileKey: const ValueKey('liveTrafficMetric:rssi'),
|
||||
label: AppLocalizations.of(context)!.rssi,
|
||||
value: snapshot.latestRssiDbm == null
|
||||
? 'No RX data'
|
||||
: '${snapshot.latestRssiDbm} dBm',
|
||||
subtitle: snapshot.avgRssiDbm == null
|
||||
? 'No average yet'
|
||||
: 'Avg ${snapshot.avgRssiDbm!.toStringAsFixed(1)} dBm',
|
||||
),
|
||||
_MetricTile(
|
||||
tileKey: const ValueKey('liveTrafficMetric:snr'),
|
||||
label: AppLocalizations.of(context)!.snr,
|
||||
value: snapshot.latestSnrDb == null
|
||||
? 'No RX data'
|
||||
: '${snapshot.latestSnrDb!.toStringAsFixed(1)} dB',
|
||||
subtitle: snapshot.avgSnrDb == null
|
||||
? 'No average yet'
|
||||
: 'Avg ${snapshot.avgSnrDb!.toStringAsFixed(1)} dB',
|
||||
),
|
||||
_MetricTile(
|
||||
tileKey: const ValueKey('liveTrafficMetric:multihop'),
|
||||
label: AppLocalizations.of(context)!.multihop,
|
||||
value: '${snapshot.multiHopCount}',
|
||||
subtitle: routeHashCounts.summaryLabel,
|
||||
footer: snapshot.avgHopCount == null
|
||||
? 'No routes yet'
|
||||
: 'Avg ${snapshot.avgHopCount!.toStringAsFixed(1)} hops',
|
||||
),
|
||||
];
|
||||
|
||||
return Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
@@ -346,44 +385,26 @@ class _SummaryPanel extends StatelessWidget {
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
Wrap(
|
||||
spacing: 10,
|
||||
runSpacing: 10,
|
||||
children: [
|
||||
_MetricTile(
|
||||
label: AppLocalizations.of(context)!.rxPackets,
|
||||
value: '${snapshot.rxCount}',
|
||||
subtitle: totalRxCount == null
|
||||
? _windowSummaryLabel(snapshot.windowDuration)
|
||||
: 'Device total $totalRxCount',
|
||||
),
|
||||
_MetricTile(
|
||||
label: AppLocalizations.of(context)!.rssi,
|
||||
value: snapshot.latestRssiDbm == null
|
||||
? 'No RX data'
|
||||
: '${snapshot.latestRssiDbm} dBm',
|
||||
subtitle: snapshot.avgRssiDbm == null
|
||||
? 'No average yet'
|
||||
: 'Avg ${snapshot.avgRssiDbm!.toStringAsFixed(1)} dBm',
|
||||
),
|
||||
_MetricTile(
|
||||
label: AppLocalizations.of(context)!.snr,
|
||||
value: snapshot.latestSnrDb == null
|
||||
? 'No RX data'
|
||||
: '${snapshot.latestSnrDb!.toStringAsFixed(1)} dB',
|
||||
subtitle: snapshot.avgSnrDb == null
|
||||
? 'No average yet'
|
||||
: 'Avg ${snapshot.avgSnrDb!.toStringAsFixed(1)} dB',
|
||||
),
|
||||
_MetricTile(
|
||||
label: AppLocalizations.of(context)!.multihop,
|
||||
value: '${snapshot.multiHopCount}',
|
||||
subtitle: routeHashCounts.summaryLabel,
|
||||
footer: snapshot.avgHopCount == null
|
||||
? 'No routes yet'
|
||||
: 'Avg ${snapshot.avgHopCount!.toStringAsFixed(1)} hops',
|
||||
),
|
||||
],
|
||||
LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
const spacing = 10.0;
|
||||
const minTileWidth = 150.0;
|
||||
final columns =
|
||||
((constraints.maxWidth + spacing) / (minTileWidth + spacing))
|
||||
.floor()
|
||||
.clamp(1, metrics.length);
|
||||
final tileWidth =
|
||||
(constraints.maxWidth - (spacing * (columns - 1))) / columns;
|
||||
|
||||
return Wrap(
|
||||
spacing: spacing,
|
||||
runSpacing: spacing,
|
||||
children: [
|
||||
for (final metric in metrics)
|
||||
SizedBox(width: tileWidth, child: metric),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
@@ -525,12 +546,14 @@ String _windowSummaryLabel(Duration duration) {
|
||||
}
|
||||
|
||||
class _MetricTile extends StatelessWidget {
|
||||
final Key? tileKey;
|
||||
final String label;
|
||||
final String value;
|
||||
final String subtitle;
|
||||
final String? footer;
|
||||
|
||||
const _MetricTile({
|
||||
this.tileKey,
|
||||
required this.label,
|
||||
required this.value,
|
||||
required this.subtitle,
|
||||
@@ -540,7 +563,7 @@ class _MetricTile extends StatelessWidget {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
width: 160,
|
||||
key: tileKey,
|
||||
height: 136,
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
@@ -949,7 +972,6 @@ class _LiveTrafficCard extends StatelessWidget {
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class _LiveTrafficPacketDetails {
|
||||
@@ -1105,7 +1127,6 @@ class _PacketInfoLine extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class _GeoPoint {
|
||||
final double latitude;
|
||||
final double longitude;
|
||||
|
||||
@@ -28,6 +28,7 @@ import '../services/voice_recorder_service.dart';
|
||||
import '../services/voice_codec_service.dart';
|
||||
import '../utils/toast_logger.dart';
|
||||
import '../utils/key_comparison.dart';
|
||||
import '../utils/contact_sorting.dart';
|
||||
import '../utils/voice_message_parser.dart';
|
||||
import '../utils/image_message_parser.dart';
|
||||
import '../utils/tictactoe_message_parser.dart';
|
||||
@@ -299,27 +300,27 @@ class _MessagesTabState extends State<MessagesTab> {
|
||||
final contactsProvider = context.read<ContactsProvider>();
|
||||
final normalizedQuery = query.trim().toLowerCase();
|
||||
final contacts =
|
||||
contactsProvider.contacts
|
||||
.where((contact) => contact.type == ContactType.chat)
|
||||
.where((contact) {
|
||||
if (normalizedQuery.isEmpty) return true;
|
||||
return contact.displayName.toLowerCase().contains(
|
||||
normalizedQuery,
|
||||
);
|
||||
})
|
||||
.toList()
|
||||
..sort((a, b) {
|
||||
final aName = a.displayName.toLowerCase();
|
||||
final bName = b.displayName.toLowerCase();
|
||||
final aStarts =
|
||||
normalizedQuery.isNotEmpty && aName.startsWith(normalizedQuery);
|
||||
final bStarts =
|
||||
normalizedQuery.isNotEmpty && bName.startsWith(normalizedQuery);
|
||||
if (aStarts != bStarts) {
|
||||
return aStarts ? -1 : 1;
|
||||
}
|
||||
return aName.compareTo(bName);
|
||||
});
|
||||
contactsProvider.chatContacts.where((contact) {
|
||||
if (normalizedQuery.isEmpty) return true;
|
||||
return contact.displayName.toLowerCase().contains(normalizedQuery);
|
||||
}).toList()..sort((a, b) {
|
||||
final primary = compareContactsByFavouriteThenLastSeen(a, b);
|
||||
if (primary != 0) {
|
||||
return primary;
|
||||
}
|
||||
|
||||
final aName = a.displayName.toLowerCase();
|
||||
final bName = b.displayName.toLowerCase();
|
||||
final aStarts =
|
||||
normalizedQuery.isNotEmpty && aName.startsWith(normalizedQuery);
|
||||
final bStarts =
|
||||
normalizedQuery.isNotEmpty && bName.startsWith(normalizedQuery);
|
||||
if (aStarts != bStarts) {
|
||||
return aStarts ? -1 : 1;
|
||||
}
|
||||
|
||||
return compareContactsByDisplayName(a, b);
|
||||
});
|
||||
|
||||
return contacts.take(8).toList(growable: false);
|
||||
}
|
||||
@@ -408,16 +409,33 @@ class _MessagesTabState extends State<MessagesTab> {
|
||||
final contactsProvider = context.read<ContactsProvider>();
|
||||
final messagesProvider = context.read<MessagesProvider>();
|
||||
|
||||
// Filter contacts by type
|
||||
final contacts = contactsProvider.contacts
|
||||
.where((c) => c.type == ContactType.chat)
|
||||
.toList();
|
||||
final rooms = contactsProvider.contacts
|
||||
.where((c) => c.type == ContactType.room)
|
||||
.toList();
|
||||
final channels = contactsProvider.contacts
|
||||
.where((c) => c.type == ContactType.channel)
|
||||
.toList();
|
||||
final contacts = List<Contact>.from(contactsProvider.chatContacts)
|
||||
..sort((a, b) {
|
||||
final primary = compareContactsByFavouriteThenLastSeen(a, b);
|
||||
if (primary != 0) {
|
||||
return primary;
|
||||
}
|
||||
|
||||
return compareContactsByDisplayName(a, b);
|
||||
});
|
||||
final rooms = List<Contact>.from(contactsProvider.rooms)
|
||||
..sort((a, b) {
|
||||
final primary = compareContactsByLastSeen(a, b);
|
||||
if (primary != 0) {
|
||||
return primary;
|
||||
}
|
||||
|
||||
return compareContactsByDisplayName(a, b);
|
||||
});
|
||||
final channels = List<Contact>.from(contactsProvider.channels)
|
||||
..sort((a, b) {
|
||||
final primary = compareContactsByLastSeen(a, b);
|
||||
if (primary != 0) {
|
||||
return primary;
|
||||
}
|
||||
|
||||
return compareContactsByDisplayName(a, b);
|
||||
});
|
||||
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
@@ -534,7 +552,10 @@ class _MessagesTabState extends State<MessagesTab> {
|
||||
}).firstOrNull;
|
||||
|
||||
if (recipient == null) {
|
||||
ToastLogger.error(context, AppLocalizations.of(context)!.cannotReplyContactNotFound);
|
||||
ToastLogger.error(
|
||||
context,
|
||||
AppLocalizations.of(context)!.cannotReplyContactNotFound,
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -563,13 +584,19 @@ class _MessagesTabState extends State<MessagesTab> {
|
||||
} else {
|
||||
final senderPrefix = message.senderPublicKeyPrefix;
|
||||
if (senderPrefix == null || senderPrefix.length < 6) {
|
||||
ToastLogger.error(context, AppLocalizations.of(context)!.cannotReplySenderMissing);
|
||||
ToastLogger.error(
|
||||
context,
|
||||
AppLocalizations.of(context)!.cannotReplySenderMissing,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
recipient = contactsProvider.findContactByPrefix(senderPrefix);
|
||||
if (recipient == null) {
|
||||
ToastLogger.error(context, AppLocalizations.of(context)!.cannotReplyContactNotFound);
|
||||
ToastLogger.error(
|
||||
context,
|
||||
AppLocalizations.of(context)!.cannotReplyContactNotFound,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -190,9 +190,11 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
_isDeveloperModeEnabled = false;
|
||||
_versionTapCount = 0;
|
||||
});
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(SnackBar(content: Text(AppLocalizations.of(context)!.developerModeDisabled)));
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(AppLocalizations.of(context)!.developerModeDisabled),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -204,9 +206,11 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
_isDeveloperModeEnabled = true;
|
||||
_versionTapCount = 0;
|
||||
});
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(SnackBar(content: Text(AppLocalizations.of(context)!.developerModeEnabled)));
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(AppLocalizations.of(context)!.developerModeEnabled),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -559,7 +563,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(AppLocalizations.of(context)!.updateCheckIsOnlyAvailableOnAndroid),
|
||||
content: Text(
|
||||
AppLocalizations.of(context)!.updateCheckIsOnlyAvailableOnAndroid,
|
||||
),
|
||||
backgroundColor: Colors.orange,
|
||||
),
|
||||
);
|
||||
@@ -584,7 +590,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
if (!updateInfo.isAvailable) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(AppLocalizations.of(context)!.youAreRunningTheLatestVersion),
|
||||
content: Text(
|
||||
AppLocalizations.of(context)!.youAreRunningTheLatestVersion,
|
||||
),
|
||||
backgroundColor: Colors.green,
|
||||
),
|
||||
);
|
||||
@@ -594,7 +602,11 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
if (updateInfo.downloadUrl == null) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(AppLocalizations.of(context)!.updateAvailableButDownloadUrlNotFound),
|
||||
content: Text(
|
||||
AppLocalizations.of(
|
||||
context,
|
||||
)!.updateAvailableButDownloadUrlNotFound,
|
||||
),
|
||||
backgroundColor: Colors.orange,
|
||||
),
|
||||
);
|
||||
@@ -1178,6 +1190,100 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
),
|
||||
]),
|
||||
|
||||
_buildSectionHeader(AppLocalizations.of(context)!.contacts),
|
||||
Consumer<AppProvider>(
|
||||
builder: (context, appProvider, child) => _buildSettingsCard([
|
||||
SwitchListTile(
|
||||
secondary: const Icon(Icons.star_outline_rounded),
|
||||
title: Text(AppLocalizations.of(context)!.favourites),
|
||||
subtitle: const Text(
|
||||
'Show the favourites section in the contacts tab',
|
||||
),
|
||||
value: appProvider.isContactsSectionEnabled(
|
||||
ContactsTabSection.favourites,
|
||||
),
|
||||
onChanged: (value) async {
|
||||
await appProvider.setContactsSectionEnabled(
|
||||
ContactsTabSection.favourites,
|
||||
value,
|
||||
);
|
||||
},
|
||||
),
|
||||
SwitchListTile(
|
||||
secondary: const Icon(Icons.people_alt_outlined),
|
||||
title: Text(AppLocalizations.of(context)!.teamMembers),
|
||||
subtitle: const Text(
|
||||
'Show direct team contacts in the contacts tab',
|
||||
),
|
||||
value: appProvider.isContactsSectionEnabled(
|
||||
ContactsTabSection.teamMembers,
|
||||
),
|
||||
onChanged: (value) async {
|
||||
await appProvider.setContactsSectionEnabled(
|
||||
ContactsTabSection.teamMembers,
|
||||
value,
|
||||
);
|
||||
},
|
||||
),
|
||||
SwitchListTile(
|
||||
secondary: const Icon(Icons.router_outlined),
|
||||
title: Text(AppLocalizations.of(context)!.repeaters),
|
||||
subtitle: const Text('Show repeater nodes in the contacts tab'),
|
||||
value: appProvider.isContactsSectionEnabled(
|
||||
ContactsTabSection.repeaters,
|
||||
),
|
||||
onChanged: (value) async {
|
||||
await appProvider.setContactsSectionEnabled(
|
||||
ContactsTabSection.repeaters,
|
||||
value,
|
||||
);
|
||||
},
|
||||
),
|
||||
SwitchListTile(
|
||||
secondary: const Icon(Icons.sensors_outlined),
|
||||
title: Text(AppLocalizations.of(context)!.sensors),
|
||||
subtitle: const Text('Show sensor nodes in the contacts tab'),
|
||||
value: appProvider.isContactsSectionEnabled(
|
||||
ContactsTabSection.sensors,
|
||||
),
|
||||
onChanged: (value) async {
|
||||
await appProvider.setContactsSectionEnabled(
|
||||
ContactsTabSection.sensors,
|
||||
value,
|
||||
);
|
||||
},
|
||||
),
|
||||
SwitchListTile(
|
||||
secondary: const Icon(Icons.meeting_room_outlined),
|
||||
title: Text(AppLocalizations.of(context)!.rooms),
|
||||
subtitle: const Text('Show rooms in the contacts tab'),
|
||||
value: appProvider.isContactsSectionEnabled(
|
||||
ContactsTabSection.rooms,
|
||||
),
|
||||
onChanged: (value) async {
|
||||
await appProvider.setContactsSectionEnabled(
|
||||
ContactsTabSection.rooms,
|
||||
value,
|
||||
);
|
||||
},
|
||||
),
|
||||
SwitchListTile(
|
||||
secondary: const Icon(Icons.broadcast_on_personal_outlined),
|
||||
title: Text(AppLocalizations.of(context)!.channels),
|
||||
subtitle: const Text('Show channels in the contacts tab'),
|
||||
value: appProvider.isContactsSectionEnabled(
|
||||
ContactsTabSection.channels,
|
||||
),
|
||||
onChanged: (value) async {
|
||||
await appProvider.setContactsSectionEnabled(
|
||||
ContactsTabSection.channels,
|
||||
value,
|
||||
);
|
||||
},
|
||||
),
|
||||
]),
|
||||
),
|
||||
|
||||
_buildSectionHeader('Messaging'),
|
||||
_buildSettingsCard([
|
||||
ListTile(
|
||||
@@ -1205,7 +1311,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
Consumer<AppProvider>(
|
||||
builder: (context, appProvider, child) => SwitchListTile(
|
||||
secondary: Icon(Icons.route),
|
||||
title: Text(AppLocalizations.of(context)!.nearestRepeaterFallback),
|
||||
title: Text(
|
||||
AppLocalizations.of(context)!.nearestRepeaterFallback,
|
||||
),
|
||||
subtitle: const Text(
|
||||
'After normal retries fail, try one final resend through the nearest repeater',
|
||||
),
|
||||
@@ -1234,7 +1342,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
'Clear Messages',
|
||||
style: TextStyle(color: Colors.red),
|
||||
),
|
||||
subtitle: Text(AppLocalizations.of(context)!.deleteAllStoredMessageHistory),
|
||||
subtitle: Text(
|
||||
AppLocalizations.of(context)!.deleteAllStoredMessageHistory,
|
||||
),
|
||||
onTap: _clearMessages,
|
||||
),
|
||||
Consumer<AppProvider>(
|
||||
@@ -1344,7 +1454,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
builder: (context, drawingProvider, child) => SwitchListTile(
|
||||
secondary: Icon(Icons.fmd_good_outlined),
|
||||
title: Text(AppLocalizations.of(context)!.showSarMarkersLabel),
|
||||
subtitle: Text(AppLocalizations.of(context)!.displaySarMarkersOnTheMainMap),
|
||||
subtitle: Text(
|
||||
AppLocalizations.of(context)!.displaySarMarkersOnTheMainMap,
|
||||
),
|
||||
value: drawingProvider.showSarMarkers,
|
||||
onChanged: (value) {
|
||||
drawingProvider.toggleSarMarkers();
|
||||
@@ -1354,7 +1466,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
Consumer<MapProvider>(
|
||||
builder: (context, mapProvider, child) => SwitchListTile(
|
||||
secondary: Icon(Icons.timeline),
|
||||
title: Text(AppLocalizations.of(context)!.showAllContactTrailsLabel),
|
||||
title: Text(
|
||||
AppLocalizations.of(context)!.showAllContactTrailsLabel,
|
||||
),
|
||||
subtitle: const Text(
|
||||
'Display location trails for all contacts that have history',
|
||||
),
|
||||
@@ -1420,7 +1534,11 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
builder: (context, appProvider, child) => SwitchListTile(
|
||||
secondary: Icon(Icons.compress),
|
||||
title: Text(AppLocalizations.of(context)!.voiceCompressor),
|
||||
subtitle: Text(AppLocalizations.of(context)!.balancesQuietAndLoudSpeechLevels),
|
||||
subtitle: Text(
|
||||
AppLocalizations.of(
|
||||
context,
|
||||
)!.balancesQuietAndLoudSpeechLevels,
|
||||
),
|
||||
value: appProvider.isVoiceCompressorEnabled,
|
||||
onChanged: (value) async {
|
||||
await appProvider.toggleVoiceCompressorEnabled(value);
|
||||
@@ -1431,7 +1549,11 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
builder: (context, appProvider, child) => SwitchListTile(
|
||||
secondary: Icon(Icons.speed),
|
||||
title: Text(AppLocalizations.of(context)!.voiceLimiter),
|
||||
subtitle: Text(AppLocalizations.of(context)!.preventsClippingPeaksBeforeEncoding),
|
||||
subtitle: Text(
|
||||
AppLocalizations.of(
|
||||
context,
|
||||
)!.preventsClippingPeaksBeforeEncoding,
|
||||
),
|
||||
value: appProvider.isVoiceLimiterEnabled,
|
||||
onChanged: (value) async {
|
||||
await appProvider.toggleVoiceLimiterEnabled(value);
|
||||
@@ -1442,7 +1564,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
builder: (context, appProvider, child) => SwitchListTile(
|
||||
secondary: Icon(Icons.auto_fix_high),
|
||||
title: Text(AppLocalizations.of(context)!.micAutoGain),
|
||||
subtitle: Text(AppLocalizations.of(context)!.letsTheRecorderAdjustInputLevel),
|
||||
subtitle: Text(
|
||||
AppLocalizations.of(context)!.letsTheRecorderAdjustInputLevel,
|
||||
),
|
||||
value: appProvider.isVoiceAutoGainEnabled,
|
||||
onChanged: (value) async {
|
||||
await appProvider.toggleVoiceAutoGainEnabled(value);
|
||||
@@ -1478,7 +1602,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
Consumer<AppProvider>(
|
||||
builder: (context, appProvider, child) => SwitchListTile(
|
||||
secondary: Icon(Icons.content_cut),
|
||||
title: Text(AppLocalizations.of(context)!.trimSilenceInVoiceMessages),
|
||||
title: Text(
|
||||
AppLocalizations.of(context)!.trimSilenceInVoiceMessages,
|
||||
),
|
||||
subtitle: const Text(
|
||||
'Removes long silent parts before sending voice',
|
||||
),
|
||||
@@ -1648,7 +1774,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
),
|
||||
ListTile(
|
||||
leading: Icon(Icons.timer),
|
||||
title: Text(AppLocalizations.of(context)!.activeuseUpdateInterval),
|
||||
title: Text(
|
||||
AppLocalizations.of(context)!.activeuseUpdateInterval,
|
||||
),
|
||||
subtitle: Text('$_fastLocationActiveCadenceSeconds s'),
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
onTap: _editFastLocationActiveCadence,
|
||||
|
||||
@@ -141,6 +141,18 @@ class LiveTrafficSummary {
|
||||
|
||||
const LiveTrafficSummary._();
|
||||
|
||||
static bool isRxDataLog(BlePacketLog log) {
|
||||
return log.direction == PacketDirection.rx &&
|
||||
log.responseCode == logRxDataResponseCode;
|
||||
}
|
||||
|
||||
static int countRxDataLogs(Iterable<BlePacketLog> logs, {DateTime? since}) {
|
||||
return logs.where((log) {
|
||||
return isRxDataLog(log) &&
|
||||
(since == null || !log.timestamp.isBefore(since));
|
||||
}).length;
|
||||
}
|
||||
|
||||
static LiveTrafficSnapshot fromLogs(
|
||||
Iterable<BlePacketLog> logs, {
|
||||
required DateTime now,
|
||||
@@ -154,15 +166,14 @@ class LiveTrafficSummary {
|
||||
? clearedAt
|
||||
: windowStart;
|
||||
|
||||
final recentLogs = logs
|
||||
.where(
|
||||
(log) =>
|
||||
log.direction == PacketDirection.rx &&
|
||||
log.responseCode == logRxDataResponseCode &&
|
||||
!log.timestamp.isBefore(effectiveStart),
|
||||
)
|
||||
.toList()
|
||||
..sort((a, b) => a.timestamp.compareTo(b.timestamp));
|
||||
final recentLogs =
|
||||
logs
|
||||
.where(
|
||||
(log) =>
|
||||
isRxDataLog(log) && !log.timestamp.isBefore(effectiveStart),
|
||||
)
|
||||
.toList()
|
||||
..sort((a, b) => a.timestamp.compareTo(b.timestamp));
|
||||
|
||||
final entries = <LiveTrafficEntry>[];
|
||||
for (final log in recentLogs) {
|
||||
@@ -215,7 +226,9 @@ class LiveTrafficSummary {
|
||||
}
|
||||
}
|
||||
|
||||
final visibleEntries = filteredEntries.reversed.take(maxVisibleEntries).toList();
|
||||
final visibleEntries = filteredEntries.reversed
|
||||
.take(maxVisibleEntries)
|
||||
.toList();
|
||||
const txCount = 0;
|
||||
final totalCount = rxCount;
|
||||
final packetsPerMinute =
|
||||
@@ -233,7 +246,9 @@ class LiveTrafficSummary {
|
||||
avgRssiDbm: rssiCount == 0 ? null : rssiSum / rssiCount,
|
||||
latestRssiDbm: latestRssiDbm,
|
||||
multiHopCount: multiHopCount,
|
||||
avgHopCount: hopCountSamples == 0 ? null : hopCountTotal / hopCountSamples,
|
||||
avgHopCount: hopCountSamples == 0
|
||||
? null
|
||||
: hopCountTotal / hopCountSamples,
|
||||
visibleEntries: visibleEntries,
|
||||
busyness: _busynessForPacketsPerMinute(packetsPerMinute),
|
||||
);
|
||||
|
||||
21
lib/services/profile_device_key_resolver.dart
Normal file
21
lib/services/profile_device_key_resolver.dart
Normal file
@@ -0,0 +1,21 @@
|
||||
import '../models/device_info.dart';
|
||||
|
||||
class ProfileDeviceKeyResolver {
|
||||
static String? resolve({
|
||||
required DeviceInfo deviceInfo,
|
||||
required ConnectionMode connectionMode,
|
||||
}) {
|
||||
// Always prefer the public key — it's the only truly stable identifier.
|
||||
// Don't fall back to deviceId to avoid creating duplicate profiles when
|
||||
// publicKey arrives late (after initial connection but before DeviceInfo).
|
||||
final publicKey = deviceInfo.publicKey;
|
||||
if (publicKey == null || publicKey.isEmpty) {
|
||||
return null; // Wait until publicKey is available
|
||||
}
|
||||
|
||||
final hex = publicKey
|
||||
.map((byte) => byte.toRadixString(16).padLeft(2, '0'))
|
||||
.join();
|
||||
return hex.isNotEmpty ? 'pk:$hex' : null;
|
||||
}
|
||||
}
|
||||
@@ -9,11 +9,14 @@ import 'profiles_feature_service.dart';
|
||||
class ProfileManager with ChangeNotifier {
|
||||
static const String _profilesKey = 'profiles_library';
|
||||
static const String activeProfileIdKey = 'profiles_active_profile_id';
|
||||
static const String _deviceProfileDefaultsKey =
|
||||
'profiles_device_active_profile_ids';
|
||||
static const String _transferHistoryKey = 'profiles_transfer_history';
|
||||
|
||||
final List<ConfigProfile> _customProfiles = <ConfigProfile>[];
|
||||
final List<ProfileTransferRecord> _transferHistory =
|
||||
<ProfileTransferRecord>[];
|
||||
final Map<String, String> _deviceProfileDefaults = <String, String>{};
|
||||
bool _isInitialized = false;
|
||||
bool _profilesEnabled = false;
|
||||
String _activeProfileId = ConfigProfile.defaultProfileId;
|
||||
@@ -37,6 +40,19 @@ class ProfileManager with ChangeNotifier {
|
||||
_activeProfileId =
|
||||
prefs.getString(activeProfileIdKey) ?? ConfigProfile.defaultProfileId;
|
||||
|
||||
final deviceDefaultsJson = prefs.getString(_deviceProfileDefaultsKey);
|
||||
if (deviceDefaultsJson != null && deviceDefaultsJson.isNotEmpty) {
|
||||
final decoded = jsonDecode(deviceDefaultsJson);
|
||||
if (decoded is Map<String, dynamic>) {
|
||||
_deviceProfileDefaults
|
||||
..clear()
|
||||
..addAll(
|
||||
decoded.map((key, value) => MapEntry(key, value?.toString() ?? ''))
|
||||
..removeWhere((key, value) => value.isEmpty),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
final profilesJson = prefs.getString(_profilesKey);
|
||||
if (profilesJson != null && profilesJson.isNotEmpty) {
|
||||
final decoded = jsonDecode(profilesJson) as List<dynamic>;
|
||||
@@ -90,9 +106,37 @@ class ProfileManager with ChangeNotifier {
|
||||
}
|
||||
|
||||
Future<void> setActiveProfileId(String id) async {
|
||||
await setActiveProfileIdForDevice(id);
|
||||
}
|
||||
|
||||
String profileIdForDevice(String? deviceKey) {
|
||||
if (deviceKey == null || deviceKey.isEmpty) {
|
||||
return _activeProfileId;
|
||||
}
|
||||
return _deviceProfileDefaults[deviceKey] ?? ConfigProfile.defaultProfileId;
|
||||
}
|
||||
|
||||
bool hasProfileForDevice(String? deviceKey) {
|
||||
if (deviceKey == null || deviceKey.isEmpty) {
|
||||
return false;
|
||||
}
|
||||
return _deviceProfileDefaults.containsKey(deviceKey);
|
||||
}
|
||||
|
||||
Future<void> setActiveProfileIdForDevice(
|
||||
String id, {
|
||||
String? deviceKey,
|
||||
}) async {
|
||||
_activeProfileId = id;
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(activeProfileIdKey, id);
|
||||
if (deviceKey != null && deviceKey.isNotEmpty) {
|
||||
_deviceProfileDefaults[deviceKey] = id;
|
||||
await prefs.setString(
|
||||
_deviceProfileDefaultsKey,
|
||||
jsonEncode(_deviceProfileDefaults),
|
||||
);
|
||||
}
|
||||
ProfileStorageScope.setScope(
|
||||
profilesEnabled: _profilesEnabled,
|
||||
activeProfileId: _activeProfileId,
|
||||
|
||||
@@ -19,6 +19,7 @@ import 'contact_storage_service.dart';
|
||||
import 'device_config_applicator.dart';
|
||||
import 'message_storage_service.dart';
|
||||
import 'profile_manager.dart';
|
||||
import 'profile_device_key_resolver.dart';
|
||||
import 'profiles_feature_service.dart';
|
||||
import 'map_workspace_snapshot_service.dart';
|
||||
|
||||
@@ -63,6 +64,7 @@ class ProfileWorkspaceCoordinator {
|
||||
final DeviceConfigApplicator _deviceConfigApplicator;
|
||||
final MessageStorageService _messageStorageService;
|
||||
final ContactStorageService _contactStorageService;
|
||||
bool _isSyncingDeviceProfile = false;
|
||||
|
||||
Future<void> setProfilesEnabled(bool enabled) async {
|
||||
final wasEnabled = profileManager.profilesEnabled;
|
||||
@@ -77,6 +79,7 @@ class ProfileWorkspaceCoordinator {
|
||||
activeProfileId: enabled ? profileManager.activeProfileId : 'default',
|
||||
);
|
||||
if (enabled) {
|
||||
await _ensureProfileForCurrentDevice();
|
||||
if (wasEnabled) {
|
||||
await openProfile(profileManager.activeProfileId);
|
||||
} else {
|
||||
@@ -181,9 +184,13 @@ class ProfileWorkspaceCoordinator {
|
||||
}
|
||||
|
||||
Future<void> openProfile(String profileId) async {
|
||||
final deviceKey = _currentDeviceProfileKey;
|
||||
await _saveActiveCustomProfileSnapshot();
|
||||
await connectionProvider.disconnect();
|
||||
await profileManager.setActiveProfileId(profileId);
|
||||
await profileManager.setActiveProfileIdForDevice(
|
||||
profileId,
|
||||
deviceKey: deviceKey,
|
||||
);
|
||||
await _switchRuntimeScope(profileId);
|
||||
|
||||
final profile = await resolveProfile(profileId);
|
||||
@@ -271,6 +278,99 @@ class ProfileWorkspaceCoordinator {
|
||||
return imported;
|
||||
}
|
||||
|
||||
Future<void> syncActiveProfileForCurrentDevice() async {
|
||||
if (!profileManager.profilesEnabled || _isSyncingDeviceProfile) {
|
||||
return;
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
Future<ConfigProfile> _ensureProfileForCurrentDevice() async {
|
||||
final deviceKey = _currentDeviceProfileKey;
|
||||
final targetProfileId = profileManager.profileIdForDevice(deviceKey);
|
||||
final existingProfile = profileManager.getProfile(targetProfileId);
|
||||
if (profileManager.hasProfileForDevice(deviceKey) &&
|
||||
existingProfile != null) {
|
||||
return existingProfile;
|
||||
}
|
||||
if (profileManager.hasProfileForDevice(deviceKey) &&
|
||||
targetProfileId == ConfigProfile.defaultProfileId) {
|
||||
return ConfigProfile.defaultProfile();
|
||||
}
|
||||
if (deviceKey == null) {
|
||||
return await resolveProfile(profileManager.activeProfileId);
|
||||
}
|
||||
|
||||
final profile = await createProfileFromCurrent(
|
||||
name: _buildDeviceProfileName(),
|
||||
);
|
||||
await profileManager.setActiveProfileIdForDevice(
|
||||
profile.id,
|
||||
deviceKey: deviceKey,
|
||||
);
|
||||
return profile;
|
||||
}
|
||||
|
||||
String _buildDeviceProfileName() {
|
||||
final deviceInfo = connectionProvider.deviceInfo;
|
||||
final name = deviceInfo.selfName?.trim();
|
||||
if (name != null && name.isNotEmpty) {
|
||||
return 'Device ${_sanitizeProfileLabel(name)}';
|
||||
}
|
||||
|
||||
final displayName = deviceInfo.displayName?.trim();
|
||||
if (displayName != null && displayName.isNotEmpty) {
|
||||
return 'Device ${_sanitizeProfileLabel(displayName)}';
|
||||
}
|
||||
|
||||
final deviceId = deviceInfo.deviceId?.trim();
|
||||
if (deviceId != null && deviceId.isNotEmpty) {
|
||||
return 'Device ${_sanitizeProfileLabel(deviceId)}';
|
||||
}
|
||||
|
||||
return 'Device Profile';
|
||||
}
|
||||
|
||||
String _sanitizeProfileLabel(String value) {
|
||||
return value.replaceAll(RegExp(r'\s+'), ' ').trim();
|
||||
}
|
||||
|
||||
String? get _currentDeviceProfileKey => ProfileDeviceKeyResolver.resolve(
|
||||
deviceInfo: connectionProvider.deviceInfo,
|
||||
connectionMode: connectionProvider.connectionMode,
|
||||
);
|
||||
|
||||
Future<void> _switchRuntimeScope(String profileId) async {
|
||||
final runtimeProfilesEnabled = profileManager.profilesEnabled;
|
||||
ProfileStorageScope.setScope(
|
||||
|
||||
@@ -5,7 +5,7 @@ class ProfilesFeatureService {
|
||||
|
||||
static Future<bool> isEnabled() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
return prefs.getBool(enabledKey) ?? false;
|
||||
return prefs.getBool(enabledKey) ?? true;
|
||||
}
|
||||
|
||||
static Future<void> setEnabled(bool enabled) async {
|
||||
@@ -15,7 +15,7 @@ class ProfilesFeatureService {
|
||||
}
|
||||
|
||||
class ProfileStorageScope {
|
||||
static bool _profilesEnabled = false;
|
||||
static bool _profilesEnabled = true;
|
||||
static String _activeProfileId = 'default';
|
||||
|
||||
static Future<void> bootstrap({
|
||||
|
||||
50
lib/services/serial/serial_transport.dart
Normal file
50
lib/services/serial/serial_transport.dart
Normal file
@@ -0,0 +1,50 @@
|
||||
import 'package:meshcore_client/meshcore_client.dart';
|
||||
|
||||
import 'serial_transport_stub.dart'
|
||||
if (dart.library.io) 'serial_transport_io.dart'
|
||||
if (dart.library.js_interop) 'serial_transport_web.dart';
|
||||
|
||||
const int kSerialBaudRate = 115200;
|
||||
|
||||
class SerialDeviceInfo {
|
||||
final String id;
|
||||
final String title;
|
||||
final String subtitle;
|
||||
final Object handle;
|
||||
|
||||
const SerialDeviceInfo({
|
||||
required this.id,
|
||||
required this.title,
|
||||
required this.subtitle,
|
||||
required this.handle,
|
||||
});
|
||||
}
|
||||
|
||||
class SerialConnection {
|
||||
final MeshCoreSerialService service;
|
||||
final String deviceId;
|
||||
final String deviceName;
|
||||
final Future<void> Function() disconnect;
|
||||
|
||||
const SerialConnection({
|
||||
required this.service,
|
||||
required this.deviceId,
|
||||
required this.deviceName,
|
||||
required this.disconnect,
|
||||
});
|
||||
}
|
||||
|
||||
abstract class SerialTransport {
|
||||
bool get isSupported;
|
||||
bool get canRequestDevice;
|
||||
String get actionLabel;
|
||||
String get emptyStateTitle;
|
||||
String get unsupportedMessage;
|
||||
|
||||
Future<List<SerialDeviceInfo>> listDevices();
|
||||
Future<SerialDeviceInfo?> requestDevice();
|
||||
Future<SerialConnection> connect(SerialDeviceInfo device);
|
||||
void dispose();
|
||||
}
|
||||
|
||||
SerialTransport createSerialTransport() => createSerialTransportImpl();
|
||||
283
lib/services/serial/serial_transport_io.dart
Normal file
283
lib/services/serial/serial_transport_io.dart
Normal file
@@ -0,0 +1,283 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_libserialport/flutter_libserialport.dart';
|
||||
import 'package:meshcore_client/meshcore_client.dart';
|
||||
import 'package:usb_serial/usb_serial.dart';
|
||||
|
||||
import 'serial_transport.dart';
|
||||
|
||||
class _IoSerialTransport implements SerialTransport {
|
||||
@override
|
||||
bool get isSupported =>
|
||||
Platform.isAndroid || Platform.isMacOS || Platform.isWindows;
|
||||
|
||||
@override
|
||||
bool get canRequestDevice => false;
|
||||
|
||||
@override
|
||||
String get actionLabel =>
|
||||
Platform.isAndroid ? 'Scan USB devices' : 'Scan serial ports';
|
||||
|
||||
@override
|
||||
String get emptyStateTitle => Platform.isAndroid
|
||||
? 'No USB serial devices found.\nConnect a MeshCore device via OTG cable.'
|
||||
: 'No serial ports found.\nConnect a MeshCore device over USB serial.';
|
||||
|
||||
@override
|
||||
String get unsupportedMessage =>
|
||||
'Serial is supported on Android, macOS, Windows, and compatible web browsers.';
|
||||
|
||||
@override
|
||||
Future<List<SerialDeviceInfo>> listDevices() async {
|
||||
if (Platform.isAndroid) {
|
||||
final devices = await UsbSerial.listDevices();
|
||||
return devices.map(_androidDeviceInfo).toList(growable: false);
|
||||
}
|
||||
if (Platform.isMacOS || Platform.isWindows) {
|
||||
return _desktopSerialDevices();
|
||||
}
|
||||
return const [];
|
||||
}
|
||||
|
||||
@override
|
||||
Future<SerialDeviceInfo?> requestDevice() async => null;
|
||||
|
||||
@override
|
||||
Future<SerialConnection> connect(SerialDeviceInfo device) async {
|
||||
if (Platform.isAndroid) {
|
||||
return _connectAndroid(device);
|
||||
}
|
||||
if (Platform.isMacOS || Platform.isWindows) {
|
||||
return _connectDesktop(device);
|
||||
}
|
||||
throw UnsupportedError(unsupportedMessage);
|
||||
}
|
||||
|
||||
SerialDeviceInfo _androidDeviceInfo(UsbDevice device) {
|
||||
final title = _firstNonEmpty([
|
||||
device.productName,
|
||||
device.manufacturerName,
|
||||
'USB Serial Device',
|
||||
]);
|
||||
final subtitleParts = <String>[
|
||||
if ((device.manufacturerName ?? '').trim().isNotEmpty)
|
||||
device.manufacturerName!.trim(),
|
||||
if (device.vid != null && device.pid != null)
|
||||
'VID:${_hex(device.vid!)} PID:${_hex(device.pid!)}',
|
||||
];
|
||||
|
||||
return SerialDeviceInfo(
|
||||
id: '${device.deviceId}:${device.vid ?? 'na'}:${device.pid ?? 'na'}:${device.productName ?? 'usb'}',
|
||||
title: title,
|
||||
subtitle: subtitleParts.isEmpty
|
||||
? 'Ready over OTG serial'
|
||||
: subtitleParts.join(' • '),
|
||||
handle: device,
|
||||
);
|
||||
}
|
||||
|
||||
Future<List<SerialDeviceInfo>> _desktopSerialDevices() async {
|
||||
final ports = <SerialDeviceInfo>[];
|
||||
for (final address in SerialPort.availablePorts) {
|
||||
final port = SerialPort(address);
|
||||
try {
|
||||
final title = _firstNonEmpty([
|
||||
port.productName,
|
||||
port.description,
|
||||
address,
|
||||
]);
|
||||
final subtitleParts = <String>[
|
||||
address,
|
||||
if ((port.manufacturer ?? '').trim().isNotEmpty)
|
||||
port.manufacturer!.trim(),
|
||||
if (port.vendorId != null && port.productId != null)
|
||||
'VID:${_hex(port.vendorId!)} PID:${_hex(port.productId!)}',
|
||||
];
|
||||
ports.add(
|
||||
SerialDeviceInfo(
|
||||
id: address,
|
||||
title: title,
|
||||
subtitle: subtitleParts.join(' • '),
|
||||
handle: address,
|
||||
),
|
||||
);
|
||||
} finally {
|
||||
port.dispose();
|
||||
}
|
||||
}
|
||||
return ports;
|
||||
}
|
||||
|
||||
Future<SerialConnection> _connectAndroid(SerialDeviceInfo device) async {
|
||||
final usbDevice = device.handle as UsbDevice;
|
||||
final service = MeshCoreSerialService(appName: 'MeshCore SAR');
|
||||
StreamSubscription<Uint8List>? inputSubscription;
|
||||
UsbPort? port;
|
||||
|
||||
try {
|
||||
port = await usbDevice.create();
|
||||
if (port == null) {
|
||||
throw Exception('Failed to create USB port');
|
||||
}
|
||||
final opened = await port.open();
|
||||
if (!opened) {
|
||||
throw Exception('Failed to open USB port');
|
||||
}
|
||||
|
||||
await port.setDTR(true);
|
||||
await port.setRTS(true);
|
||||
await port.setPortParameters(
|
||||
kSerialBaudRate,
|
||||
UsbPort.DATABITS_8,
|
||||
UsbPort.STOPBITS_1,
|
||||
UsbPort.PARITY_NONE,
|
||||
);
|
||||
|
||||
service.writeRaw = (data) async {
|
||||
await port!.write(data);
|
||||
};
|
||||
|
||||
inputSubscription = port.inputStream?.listen(
|
||||
(data) => service.feedRawBytes(data),
|
||||
onError: (error) {
|
||||
debugPrint('❌ [Serial/Android] Read error: $error');
|
||||
service.markDisconnected();
|
||||
},
|
||||
onDone: () {
|
||||
debugPrint('⚠️ [Serial/Android] Port closed');
|
||||
service.markDisconnected();
|
||||
},
|
||||
);
|
||||
|
||||
final connected = await service.markConnected();
|
||||
if (!connected) {
|
||||
throw Exception('Serial session initialization failed');
|
||||
}
|
||||
|
||||
return SerialConnection(
|
||||
service: service,
|
||||
deviceId:
|
||||
'${usbDevice.deviceId}:${usbDevice.vid ?? 'na'}:${usbDevice.pid ?? 'na'}',
|
||||
deviceName: device.title,
|
||||
disconnect: () async {
|
||||
await inputSubscription?.cancel();
|
||||
inputSubscription = null;
|
||||
service.writeRaw = null;
|
||||
await port?.close();
|
||||
port = null;
|
||||
},
|
||||
);
|
||||
} catch (_) {
|
||||
await inputSubscription?.cancel();
|
||||
service.writeRaw = null;
|
||||
await port?.close();
|
||||
service.dispose();
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
Future<SerialConnection> _connectDesktop(SerialDeviceInfo device) async {
|
||||
final portName = device.handle as String;
|
||||
final port = SerialPort(portName);
|
||||
final config = SerialPortConfig();
|
||||
final service = MeshCoreSerialService(appName: 'MeshCore SAR');
|
||||
SerialPortReader? reader;
|
||||
StreamSubscription<Uint8List>? inputSubscription;
|
||||
|
||||
try {
|
||||
if (!port.openReadWrite()) {
|
||||
throw Exception(
|
||||
SerialPort.lastError?.message ?? 'Failed to open serial port',
|
||||
);
|
||||
}
|
||||
|
||||
config.baudRate = kSerialBaudRate;
|
||||
config.bits = 8;
|
||||
config.stopBits = 1;
|
||||
config.parity = SerialPortParity.none;
|
||||
config.setFlowControl(SerialPortFlowControl.none);
|
||||
config.dtr = SerialPortDtr.on;
|
||||
config.rts = SerialPortRts.on;
|
||||
port.config = config;
|
||||
|
||||
service.writeRaw = (data) async {
|
||||
var offset = 0;
|
||||
while (offset < data.length) {
|
||||
final written = port.write(data.sublist(offset));
|
||||
if (written <= 0) {
|
||||
throw Exception(
|
||||
SerialPort.lastError?.message ?? 'Failed to write to serial port',
|
||||
);
|
||||
}
|
||||
offset += written;
|
||||
}
|
||||
};
|
||||
|
||||
reader = SerialPortReader(port);
|
||||
inputSubscription = reader.stream.listen(
|
||||
(data) => service.feedRawBytes(data),
|
||||
onError: (error) {
|
||||
debugPrint('❌ [Serial/Desktop] Read error: $error');
|
||||
service.markDisconnected();
|
||||
},
|
||||
onDone: () {
|
||||
debugPrint('⚠️ [Serial/Desktop] Reader closed');
|
||||
service.markDisconnected();
|
||||
},
|
||||
);
|
||||
|
||||
final connected = await service.markConnected();
|
||||
if (!connected) {
|
||||
throw Exception('Serial session initialization failed');
|
||||
}
|
||||
|
||||
return SerialConnection(
|
||||
service: service,
|
||||
deviceId: portName,
|
||||
deviceName: device.title,
|
||||
disconnect: () async {
|
||||
await inputSubscription?.cancel();
|
||||
inputSubscription = null;
|
||||
reader?.close();
|
||||
reader = null;
|
||||
service.writeRaw = null;
|
||||
if (port.isOpen) {
|
||||
port.close();
|
||||
}
|
||||
port.dispose();
|
||||
config.dispose();
|
||||
},
|
||||
);
|
||||
} catch (_) {
|
||||
await inputSubscription?.cancel();
|
||||
reader?.close();
|
||||
service.writeRaw = null;
|
||||
if (port.isOpen) {
|
||||
port.close();
|
||||
}
|
||||
port.dispose();
|
||||
config.dispose();
|
||||
service.dispose();
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {}
|
||||
}
|
||||
|
||||
String _firstNonEmpty(List<String?> values) {
|
||||
for (final value in values) {
|
||||
final trimmed = value?.trim();
|
||||
if (trimmed != null && trimmed.isNotEmpty) {
|
||||
return trimmed;
|
||||
}
|
||||
}
|
||||
return 'Serial Device';
|
||||
}
|
||||
|
||||
String _hex(int value) => value.toRadixString(16).padLeft(4, '0');
|
||||
|
||||
SerialTransport createSerialTransportImpl() => _IoSerialTransport();
|
||||
35
lib/services/serial/serial_transport_stub.dart
Normal file
35
lib/services/serial/serial_transport_stub.dart
Normal file
@@ -0,0 +1,35 @@
|
||||
import 'serial_transport.dart';
|
||||
|
||||
class _UnsupportedSerialTransport implements SerialTransport {
|
||||
@override
|
||||
bool get isSupported => false;
|
||||
|
||||
@override
|
||||
bool get canRequestDevice => false;
|
||||
|
||||
@override
|
||||
String get actionLabel => 'Serial unsupported';
|
||||
|
||||
@override
|
||||
String get emptyStateTitle => 'Serial is unavailable on this platform.';
|
||||
|
||||
@override
|
||||
String get unsupportedMessage =>
|
||||
'Serial is supported on Android, macOS, Windows, and compatible web browsers.';
|
||||
|
||||
@override
|
||||
Future<List<SerialDeviceInfo>> listDevices() async => const [];
|
||||
|
||||
@override
|
||||
Future<SerialDeviceInfo?> requestDevice() async => null;
|
||||
|
||||
@override
|
||||
Future<SerialConnection> connect(SerialDeviceInfo device) async {
|
||||
throw UnsupportedError(unsupportedMessage);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {}
|
||||
}
|
||||
|
||||
SerialTransport createSerialTransportImpl() => _UnsupportedSerialTransport();
|
||||
209
lib/services/serial/serial_transport_web.dart
Normal file
209
lib/services/serial/serial_transport_web.dart
Normal file
@@ -0,0 +1,209 @@
|
||||
import 'dart:async';
|
||||
import 'dart:js_interop';
|
||||
import 'dart:js_interop_unsafe';
|
||||
|
||||
import 'package:meshcore_client/meshcore_client.dart';
|
||||
import 'package:web/web.dart' as web;
|
||||
import 'package:webserial/webserial.dart';
|
||||
|
||||
import 'serial_transport.dart';
|
||||
|
||||
class _WebSerialTransport implements SerialTransport {
|
||||
@override
|
||||
bool get isSupported =>
|
||||
web.window.navigator.hasProperty('serial'.toJS).toDart;
|
||||
|
||||
@override
|
||||
bool get canRequestDevice => true;
|
||||
|
||||
@override
|
||||
String get actionLabel => 'Choose serial device';
|
||||
|
||||
@override
|
||||
String get emptyStateTitle =>
|
||||
'No serial devices granted yet.\nChoose a device and approve access in your browser.';
|
||||
|
||||
@override
|
||||
String get unsupportedMessage =>
|
||||
'Web Serial requires a compatible browser such as Chrome or Edge and a secure context (HTTPS or localhost).';
|
||||
|
||||
@override
|
||||
Future<List<SerialDeviceInfo>> listDevices() async {
|
||||
if (!isSupported) {
|
||||
return const [];
|
||||
}
|
||||
final ports = await serial.getPorts().toDart;
|
||||
return ports
|
||||
.toDart
|
||||
.whereType<JSSerialPort>()
|
||||
.map(_deviceInfoForPort)
|
||||
.toList(growable: false);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<SerialDeviceInfo?> requestDevice() async {
|
||||
if (!isSupported) {
|
||||
return null;
|
||||
}
|
||||
final port = await requestWebSerialPort(null);
|
||||
if (port == null) {
|
||||
return null;
|
||||
}
|
||||
return _deviceInfoForPort(port);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<SerialConnection> connect(SerialDeviceInfo device) async {
|
||||
final port = device.handle as JSSerialPort;
|
||||
final service = MeshCoreSerialService(appName: 'MeshCore SAR');
|
||||
web.ReadableStreamDefaultReader? reader;
|
||||
bool keepReading = false;
|
||||
|
||||
try {
|
||||
await port
|
||||
.open(
|
||||
JSSerialOptions(
|
||||
baudRate: kSerialBaudRate,
|
||||
dataBits: 8,
|
||||
stopBits: 1,
|
||||
parity: 'none',
|
||||
bufferSize: 1024,
|
||||
flowControl: 'none',
|
||||
),
|
||||
)
|
||||
.toDart;
|
||||
|
||||
await port
|
||||
.setSignals(
|
||||
JSSerialOutputSignals(
|
||||
dataTerminalReady: true,
|
||||
requestToSend: true,
|
||||
),
|
||||
)
|
||||
.toDart;
|
||||
|
||||
service.writeRaw = (data) async {
|
||||
final writable = port.writable;
|
||||
if (writable == null) {
|
||||
throw Exception('Serial port is not writable');
|
||||
}
|
||||
final writer =
|
||||
writable.getWriter() as web.WritableStreamDefaultWriter?;
|
||||
if (writer == null) {
|
||||
throw Exception('Failed to acquire serial writer');
|
||||
}
|
||||
try {
|
||||
await writer.write(data.toJS).toDart;
|
||||
} finally {
|
||||
writer.releaseLock();
|
||||
}
|
||||
};
|
||||
|
||||
final readable = port.readable;
|
||||
if (readable == null) {
|
||||
throw Exception('Serial port is not readable');
|
||||
}
|
||||
|
||||
reader = readable.getReader() as web.ReadableStreamDefaultReader?;
|
||||
if (reader == null) {
|
||||
throw Exception('Failed to acquire serial reader');
|
||||
}
|
||||
|
||||
keepReading = true;
|
||||
unawaited(_readLoop(reader, service, () => keepReading));
|
||||
|
||||
final connected = await service.markConnected();
|
||||
if (!connected) {
|
||||
throw Exception('Serial session initialization failed');
|
||||
}
|
||||
|
||||
return SerialConnection(
|
||||
service: service,
|
||||
deviceId: device.id,
|
||||
deviceName: device.title,
|
||||
disconnect: () async {
|
||||
keepReading = false;
|
||||
try {
|
||||
await reader?.cancel().toDart;
|
||||
} catch (_) {}
|
||||
try {
|
||||
reader?.releaseLock();
|
||||
} catch (_) {}
|
||||
reader = null;
|
||||
service.writeRaw = null;
|
||||
try {
|
||||
await port.close().toDart;
|
||||
} catch (_) {}
|
||||
},
|
||||
);
|
||||
} catch (_) {
|
||||
keepReading = false;
|
||||
try {
|
||||
await reader?.cancel().toDart;
|
||||
} catch (_) {}
|
||||
try {
|
||||
reader?.releaseLock();
|
||||
} catch (_) {}
|
||||
service.writeRaw = null;
|
||||
try {
|
||||
await port.close().toDart;
|
||||
} catch (_) {}
|
||||
service.dispose();
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _readLoop(
|
||||
web.ReadableStreamDefaultReader reader,
|
||||
MeshCoreSerialService service,
|
||||
bool Function() shouldContinue,
|
||||
) async {
|
||||
while (shouldContinue()) {
|
||||
try {
|
||||
final result = await reader.read().toDart;
|
||||
if (result.done) {
|
||||
break;
|
||||
}
|
||||
final value = result.value;
|
||||
if (value == null) {
|
||||
continue;
|
||||
}
|
||||
service.feedRawBytes((value as JSUint8Array).toDart);
|
||||
} catch (_) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
service.markDisconnected();
|
||||
try {
|
||||
reader.releaseLock();
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
SerialDeviceInfo _deviceInfoForPort(JSSerialPort port) {
|
||||
final info = port.getInfo();
|
||||
final vendorId = info.usbVendorId;
|
||||
final productId = info.usbProductId;
|
||||
final title = (vendorId != 0 || productId != 0)
|
||||
? 'USB ${_hex(vendorId)}:${_hex(productId)}'
|
||||
: 'Granted serial device';
|
||||
final subtitle = [
|
||||
if (vendorId != 0 || productId != 0)
|
||||
'VID:${_hex(vendorId)} PID:${_hex(productId)}',
|
||||
'Web Serial',
|
||||
].join(' • ');
|
||||
|
||||
return SerialDeviceInfo(
|
||||
id: '$title::$subtitle',
|
||||
title: title,
|
||||
subtitle: subtitle,
|
||||
handle: port,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {}
|
||||
}
|
||||
|
||||
String _hex(int value) => value.toRadixString(16).padLeft(4, '0');
|
||||
|
||||
SerialTransport createSerialTransportImpl() => _WebSerialTransport();
|
||||
24
lib/utils/contact_sorting.dart
Normal file
24
lib/utils/contact_sorting.dart
Normal file
@@ -0,0 +1,24 @@
|
||||
import '../models/contact.dart';
|
||||
|
||||
int compareContactsByLastSeen(Contact a, Contact b) {
|
||||
return b.lastSeenTime.compareTo(a.lastSeenTime);
|
||||
}
|
||||
|
||||
int compareContactsByFavouriteThenLastSeen(Contact a, Contact b) {
|
||||
if (a.isFavourite != b.isFavourite) {
|
||||
return a.isFavourite ? -1 : 1;
|
||||
}
|
||||
|
||||
return compareContactsByLastSeen(a, b);
|
||||
}
|
||||
|
||||
int compareContactsByDisplayName(Contact a, Contact b) {
|
||||
final nameCompare = a.displayName.toLowerCase().compareTo(
|
||||
b.displayName.toLowerCase(),
|
||||
);
|
||||
if (nameCompare != 0) {
|
||||
return nameCompare;
|
||||
}
|
||||
|
||||
return a.publicKeyHex.compareTo(b.publicKeyHex);
|
||||
}
|
||||
54
lib/utils/link_quality.dart
Normal file
54
lib/utils/link_quality.dart
Normal file
@@ -0,0 +1,54 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
int rssiScore(int rssiDbm) {
|
||||
if (rssiDbm >= -60) return 5;
|
||||
if (rssiDbm >= -70) return 4;
|
||||
if (rssiDbm >= -80) return 3;
|
||||
if (rssiDbm >= -90) return 2;
|
||||
if (rssiDbm >= -100) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int snrScore(double snrDb) {
|
||||
if (snrDb >= 10) return 5;
|
||||
if (snrDb >= 5) return 4;
|
||||
if (snrDb >= 0) return 3;
|
||||
if (snrDb >= -5) return 2;
|
||||
if (snrDb >= -10) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
String linkQualityLabel(int? rssiDbm, double? snrDb) {
|
||||
var totalScore = 0;
|
||||
var metricCount = 0;
|
||||
|
||||
if (rssiDbm != null) {
|
||||
totalScore += rssiScore(rssiDbm);
|
||||
metricCount += 1;
|
||||
}
|
||||
if (snrDb != null) {
|
||||
totalScore += snrScore(snrDb);
|
||||
metricCount += 1;
|
||||
}
|
||||
|
||||
if (metricCount == 0) return 'Weak';
|
||||
|
||||
final averageScore = totalScore / metricCount;
|
||||
if (averageScore >= 4.5) return 'Excellent';
|
||||
if (averageScore >= 3.5) return 'Good';
|
||||
if (averageScore >= 2.5) return 'Fair';
|
||||
return 'Weak';
|
||||
}
|
||||
|
||||
Color linkQualityColor(String quality) {
|
||||
switch (quality) {
|
||||
case 'Excellent':
|
||||
return Colors.green;
|
||||
case 'Good':
|
||||
return Colors.lightGreen;
|
||||
case 'Fair':
|
||||
return Colors.orange;
|
||||
default:
|
||||
return Colors.redAccent;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,4 +1,5 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_map/flutter_map.dart' as flutter_map;
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:geolocator/geolocator.dart';
|
||||
@@ -16,6 +17,8 @@ import 'contact_trace_sheet.dart';
|
||||
import 'room_login_sheet.dart';
|
||||
import '../common/contact_avatar.dart';
|
||||
import '../sensors/sensor_telemetry_card.dart';
|
||||
import '../../utils/link_quality.dart';
|
||||
import '../../utils/time_ago_extensions.dart';
|
||||
import '../../utils/toast_logger.dart';
|
||||
import '../../l10n/app_localizations.dart';
|
||||
|
||||
@@ -51,6 +54,14 @@ class ContactTile extends StatelessWidget {
|
||||
return l10n.daysAgo(diff.inDays);
|
||||
}
|
||||
|
||||
String _threeBytePrefix() {
|
||||
final bytes = contact.publicKey.take(3);
|
||||
return bytes
|
||||
.map((byte) => byte.toRadixString(16).padLeft(2, '0'))
|
||||
.join()
|
||||
.toUpperCase();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final isChannel = contact.type == ContactType.channel;
|
||||
@@ -174,14 +185,7 @@ class ContactTile extends StatelessWidget {
|
||||
margin: const EdgeInsets.only(bottom: 8),
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(18),
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
colors: [
|
||||
colorScheme.surfaceContainerLow,
|
||||
colorScheme.surfaceContainerHighest.withValues(alpha: 0.9),
|
||||
],
|
||||
),
|
||||
color: colorScheme.surfaceContainerLow,
|
||||
border: Border.all(
|
||||
color: colorScheme.outlineVariant.withValues(alpha: 0.35),
|
||||
),
|
||||
@@ -202,46 +206,73 @@ class ContactTile extends StatelessWidget {
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Stack(
|
||||
clipBehavior: Clip.none,
|
||||
children: [
|
||||
ContactAvatar(contact: contact, radius: 24),
|
||||
if (contact.isNew)
|
||||
Positioned(
|
||||
top: -2,
|
||||
right: -2,
|
||||
child: Container(
|
||||
width: 14,
|
||||
height: 14,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.blue,
|
||||
shape: BoxShape.circle,
|
||||
border: Border.all(color: Colors.white, width: 2),
|
||||
),
|
||||
SizedBox(
|
||||
width: 58,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Stack(
|
||||
clipBehavior: Clip.none,
|
||||
children: [
|
||||
ContactAvatar(contact: contact, radius: 24),
|
||||
if (contact.isNew)
|
||||
Positioned(
|
||||
top: -2,
|
||||
right: -2,
|
||||
child: Container(
|
||||
width: 14,
|
||||
height: 14,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.blue,
|
||||
shape: BoxShape.circle,
|
||||
border: Border.all(
|
||||
color: Colors.white,
|
||||
width: 2,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
if (contact.type == ContactType.room &&
|
||||
roomLoginState != null)
|
||||
Positioned(
|
||||
bottom: -2,
|
||||
right: -2,
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(3),
|
||||
decoration: BoxDecoration(
|
||||
color: _getRoomStatusColor(roomLoginState),
|
||||
shape: BoxShape.circle,
|
||||
border: Border.all(
|
||||
color: Colors.white,
|
||||
width: 2,
|
||||
),
|
||||
),
|
||||
child: Icon(
|
||||
_getRoomStatusIcon(roomLoginState),
|
||||
size: 11,
|
||||
color: Colors.white,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
_threeBytePrefix(),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.labelSmall?.copyWith(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
fontFamily: 'monospace',
|
||||
fontWeight: FontWeight.w700,
|
||||
letterSpacing: 0.6,
|
||||
),
|
||||
),
|
||||
if (contact.type == ContactType.room &&
|
||||
roomLoginState != null)
|
||||
Positioned(
|
||||
bottom: -2,
|
||||
right: -2,
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(3),
|
||||
decoration: BoxDecoration(
|
||||
color: _getRoomStatusColor(roomLoginState),
|
||||
shape: BoxShape.circle,
|
||||
border: Border.all(color: Colors.white, width: 2),
|
||||
),
|
||||
child: Icon(
|
||||
_getRoomStatusIcon(roomLoginState),
|
||||
size: 11,
|
||||
color: Colors.white,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
@@ -1259,6 +1290,7 @@ class _NeighboursSheetState extends State<_NeighboursSheet> {
|
||||
|
||||
Future<void> _fetchNeighbours() async {
|
||||
final connectionProvider = context.read<ConnectionProvider>();
|
||||
final previousOnMessageReceived = connectionProvider.onMessageReceived;
|
||||
|
||||
String? responseText;
|
||||
void onMessage(message) {
|
||||
@@ -1270,9 +1302,12 @@ class _NeighboursSheetState extends State<_NeighboursSheet> {
|
||||
}
|
||||
}
|
||||
|
||||
connectionProvider.onMessageReceived = (message) {
|
||||
void sheetListener(message) {
|
||||
previousOnMessageReceived?.call(message);
|
||||
onMessage(message);
|
||||
};
|
||||
}
|
||||
|
||||
connectionProvider.onMessageReceived = sheetListener;
|
||||
|
||||
try {
|
||||
await connectionProvider.sendTextMessage(
|
||||
@@ -1343,32 +1378,321 @@ class _NeighboursSheetState extends State<_NeighboursSheet> {
|
||||
_loading = false;
|
||||
_error = 'Failed: $e';
|
||||
});
|
||||
} finally {
|
||||
if (identical(connectionProvider.onMessageReceived, sheetListener)) {
|
||||
connectionProvider.onMessageReceived = previousOnMessageReceived;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
String _resolveNeighbourName(String keyHex) {
|
||||
Contact? _resolveNeighbourContact(String keyHex) {
|
||||
final contactsProvider = context.read<ContactsProvider>();
|
||||
for (final contact in contactsProvider.contacts) {
|
||||
if (contact.publicKeyHex.toLowerCase().startsWith(keyHex.toLowerCase())) {
|
||||
return contact.displayName;
|
||||
return contact;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
String _resolveNeighbourName(String keyHex) {
|
||||
final contact = _resolveNeighbourContact(keyHex);
|
||||
if (contact != null) {
|
||||
return contact.displayName;
|
||||
}
|
||||
return keyHex.length > 12 ? '${keyHex.substring(0, 12)}...' : keyHex;
|
||||
}
|
||||
|
||||
String _formatAge(DateTime when) {
|
||||
final diff = DateTime.now().difference(when);
|
||||
if (diff.inMinutes < 1) return 'just now';
|
||||
if (diff.inMinutes < 60) return '${diff.inMinutes}m ago';
|
||||
if (diff.inHours < 24) return '${diff.inHours}h ago';
|
||||
return '${diff.inDays}d ago';
|
||||
String _formatAge(BuildContext context, _Neighbour neighbour) {
|
||||
if (neighbour.lastSeenAt != null) {
|
||||
return DateTime.now()
|
||||
.difference(neighbour.lastSeenAt!)
|
||||
.toLocalizedTimeAgoWithSeconds(context);
|
||||
}
|
||||
if (neighbour.lastSeenMs != null) {
|
||||
if (neighbour.lastSeenMs! < 1000) {
|
||||
return AppLocalizations.of(context)!.justNow;
|
||||
}
|
||||
return Duration(
|
||||
milliseconds: neighbour.lastSeenMs!,
|
||||
).toLocalizedTimeAgoWithSeconds(context);
|
||||
}
|
||||
return AppLocalizations.of(context)!.justNow;
|
||||
}
|
||||
|
||||
List<_MappedNeighbour> _mappedNeighbours() {
|
||||
return _neighbours
|
||||
.map((neighbour) {
|
||||
final contact = _resolveNeighbourContact(neighbour.publicKeyHex);
|
||||
final location = contact?.displayLocation;
|
||||
if (contact == null || location == null) {
|
||||
return null;
|
||||
}
|
||||
return _MappedNeighbour(
|
||||
neighbour: neighbour,
|
||||
contact: contact,
|
||||
location: LatLng(location.latitude, location.longitude),
|
||||
);
|
||||
})
|
||||
.whereType<_MappedNeighbour>()
|
||||
.toList();
|
||||
}
|
||||
|
||||
Widget _buildSummaryChip(
|
||||
BuildContext context, {
|
||||
required IconData icon,
|
||||
required String label,
|
||||
}) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.surfaceContainerHighest,
|
||||
borderRadius: BorderRadius.circular(999),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(icon, size: 14, color: colorScheme.onSurfaceVariant),
|
||||
const SizedBox(width: 6),
|
||||
Text(
|
||||
label,
|
||||
style: Theme.of(context).textTheme.labelMedium?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildRepeaterMarker(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Container(
|
||||
constraints: const BoxConstraints(maxWidth: 132),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.black.withValues(alpha: 0.78),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Text(
|
||||
widget.contact.displayName,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontWeight: FontWeight.w700,
|
||||
fontSize: 11,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Container(
|
||||
width: 34,
|
||||
height: 34,
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.primary,
|
||||
shape: BoxShape.circle,
|
||||
border: Border.all(color: Colors.white, width: 2),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withValues(alpha: 0.2),
|
||||
blurRadius: 6,
|
||||
offset: const Offset(0, 2),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: const Icon(Icons.hub_outlined, color: Colors.white, size: 18),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildNeighbourMarker(BuildContext context, _MappedNeighbour mapped) {
|
||||
final quality = linkQualityLabel(null, mapped.neighbour.snrDb);
|
||||
final qualityColor = linkQualityColor(quality);
|
||||
final ageLabel = _formatAge(context, mapped.neighbour);
|
||||
final signalLabel = mapped.neighbour.snrDb == null
|
||||
? quality
|
||||
: '$quality • ${mapped.neighbour.snrDb!.toStringAsFixed(1)} dB';
|
||||
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Container(
|
||||
constraints: const BoxConstraints(maxWidth: 146),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: qualityColor.withValues(alpha: 0.92),
|
||||
borderRadius: BorderRadius.circular(999),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withValues(alpha: 0.12),
|
||||
blurRadius: 4,
|
||||
offset: const Offset(0, 2),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Text(
|
||||
signalLabel,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontWeight: FontWeight.w700,
|
||||
fontSize: 10,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Container(
|
||||
width: 30,
|
||||
height: 30,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
shape: BoxShape.circle,
|
||||
border: Border.all(color: qualityColor, width: 2),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withValues(alpha: 0.18),
|
||||
blurRadius: 6,
|
||||
offset: const Offset(0, 2),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Icon(
|
||||
mapped.contact.isRepeater
|
||||
? Icons.router_outlined
|
||||
: Icons.location_on_outlined,
|
||||
color: qualityColor,
|
||||
size: 16,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Container(
|
||||
constraints: const BoxConstraints(maxWidth: 148),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.black.withValues(alpha: 0.78),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
mapped.contact.displayName,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontWeight: FontWeight.w700,
|
||||
fontSize: 11,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Text(
|
||||
ageLabel,
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(
|
||||
color: Colors.white70,
|
||||
fontWeight: FontWeight.w600,
|
||||
fontSize: 10,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildRouteMap(
|
||||
BuildContext context, {
|
||||
required LatLng repeaterLocation,
|
||||
required List<_MappedNeighbour> mappedNeighbours,
|
||||
}) {
|
||||
final points = <LatLng>[
|
||||
repeaterLocation,
|
||||
...mappedNeighbours.map((mapped) => mapped.location),
|
||||
];
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
|
||||
return ClipRRect(
|
||||
borderRadius: BorderRadius.circular(18),
|
||||
child: DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
border: Border.all(color: colorScheme.outlineVariant),
|
||||
),
|
||||
child: flutter_map.FlutterMap(
|
||||
options: flutter_map.MapOptions(
|
||||
initialCameraFit: flutter_map.CameraFit.bounds(
|
||||
bounds: flutter_map.LatLngBounds.fromPoints(points),
|
||||
padding: const EdgeInsets.all(42),
|
||||
),
|
||||
),
|
||||
children: [
|
||||
flutter_map.TileLayer(
|
||||
urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
|
||||
userAgentPackageName: 'com.meshcore.sar',
|
||||
),
|
||||
flutter_map.PolylineLayer(
|
||||
polylines: mappedNeighbours.map((mapped) {
|
||||
final quality = linkQualityLabel(null, mapped.neighbour.snrDb);
|
||||
final qualityColor = linkQualityColor(quality);
|
||||
return flutter_map.Polyline(
|
||||
points: [repeaterLocation, mapped.location],
|
||||
color: qualityColor.withValues(alpha: 0.9),
|
||||
strokeWidth: 4,
|
||||
borderColor: Colors.white.withValues(alpha: 0.7),
|
||||
borderStrokeWidth: 1.5,
|
||||
);
|
||||
}).toList(),
|
||||
),
|
||||
flutter_map.MarkerLayer(
|
||||
markers: [
|
||||
flutter_map.Marker(
|
||||
point: repeaterLocation,
|
||||
width: 150,
|
||||
height: 74,
|
||||
child: _buildRepeaterMarker(context),
|
||||
),
|
||||
...mappedNeighbours.map(
|
||||
(mapped) => flutter_map.Marker(
|
||||
point: mapped.location,
|
||||
width: 164,
|
||||
height: 112,
|
||||
child: _buildNeighbourMarker(context, mapped),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final repeaterDisplayLocation = widget.contact.displayLocation;
|
||||
final repeaterLocation = repeaterDisplayLocation == null
|
||||
? null
|
||||
: LatLng(
|
||||
repeaterDisplayLocation.latitude,
|
||||
repeaterDisplayLocation.longitude,
|
||||
);
|
||||
final mappedNeighbours = _mappedNeighbours();
|
||||
final missingLocations = _neighbours.length - mappedNeighbours.length;
|
||||
|
||||
return SafeArea(
|
||||
child: SizedBox(
|
||||
height: MediaQuery.of(context).size.height * 0.55,
|
||||
height: MediaQuery.of(context).size.height * 0.72,
|
||||
child: Column(
|
||||
children: [
|
||||
const SizedBox(height: 12),
|
||||
@@ -1410,26 +1734,68 @@ class _NeighboursSheetState extends State<_NeighboursSheet> {
|
||||
)
|
||||
: _neighbours.isEmpty
|
||||
? const Center(child: Text('No neighbours found'))
|
||||
: ListView.builder(
|
||||
padding: const EdgeInsets.only(bottom: 16),
|
||||
itemCount: _neighbours.length,
|
||||
itemBuilder: (context, index) {
|
||||
final n = _neighbours[index];
|
||||
final name = _resolveNeighbourName(n.publicKeyHex);
|
||||
final parts = <String>[
|
||||
if (n.snrDb != null)
|
||||
'SNR ${n.snrDb!.toStringAsFixed(1)} dB',
|
||||
if (n.lastSeenAt != null) _formatAge(n.lastSeenAt!),
|
||||
if (n.lastSeenMs != null) '${n.lastSeenMs}ms ago',
|
||||
];
|
||||
return ListTile(
|
||||
leading: const Icon(Icons.router_outlined),
|
||||
title: Text(name),
|
||||
subtitle: parts.isNotEmpty
|
||||
? Text(parts.join(' • '))
|
||||
: null,
|
||||
);
|
||||
},
|
||||
: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 4, 16, 16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
_buildSummaryChip(
|
||||
context,
|
||||
icon: Icons.route_outlined,
|
||||
label:
|
||||
'${_neighbours.length} neighbour${_neighbours.length == 1 ? '' : 's'}',
|
||||
),
|
||||
_buildSummaryChip(
|
||||
context,
|
||||
icon: Icons.map_outlined,
|
||||
label: '${mappedNeighbours.length} on map',
|
||||
),
|
||||
if (missingLocations > 0)
|
||||
_buildSummaryChip(
|
||||
context,
|
||||
icon: Icons.location_off_outlined,
|
||||
label: '$missingLocations without GPS',
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Expanded(
|
||||
child: repeaterLocation == null
|
||||
? Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 24,
|
||||
),
|
||||
child: Text(
|
||||
'${widget.contact.displayName} has no saved location, so neighbour routes cannot be drawn on the map yet.',
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
)
|
||||
: mappedNeighbours.isEmpty
|
||||
? Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 24,
|
||||
),
|
||||
child: Text(
|
||||
'Neighbours responded, but no geolocated contacts matched saved nodes to plot. Recent neighbour: ${_resolveNeighbourName(_neighbours.first.publicKeyHex)} • ${_formatAge(context, _neighbours.first)}',
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
)
|
||||
: _buildRouteMap(
|
||||
context,
|
||||
repeaterLocation: repeaterLocation,
|
||||
mappedNeighbours: mappedNeighbours,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
@@ -1452,3 +1818,15 @@ class _Neighbour {
|
||||
this.snrDb,
|
||||
});
|
||||
}
|
||||
|
||||
class _MappedNeighbour {
|
||||
final _Neighbour neighbour;
|
||||
final Contact contact;
|
||||
final LatLng location;
|
||||
|
||||
const _MappedNeighbour({
|
||||
required this.neighbour,
|
||||
required this.contact,
|
||||
required this.location,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -106,7 +106,10 @@ class SpectrumScanPanel extends StatelessWidget {
|
||||
color: theme.colorScheme.primary,
|
||||
label: AppLocalizations.of(context)!.quiet,
|
||||
),
|
||||
_LegendChip(color: Colors.orange, label: AppLocalizations.of(context)!.moderate),
|
||||
_LegendChip(
|
||||
color: Colors.orange,
|
||||
label: AppLocalizations.of(context)!.moderate,
|
||||
),
|
||||
_LegendChip(
|
||||
color: theme.colorScheme.error,
|
||||
label: AppLocalizations.of(context)!.busy,
|
||||
@@ -147,7 +150,7 @@ class SpectrumScanPanel extends StatelessWidget {
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surface.withValues(alpha: 0.7),
|
||||
color: theme.colorScheme.surfaceContainerLow,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: theme.colorScheme.outlineVariant),
|
||||
),
|
||||
@@ -303,12 +306,7 @@ class _FrequencyRangePreview extends StatelessWidget {
|
||||
height: 108,
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
gradient: LinearGradient(
|
||||
colors: [
|
||||
scheme.surface,
|
||||
scheme.surfaceContainerHighest.withValues(alpha: 0.9),
|
||||
],
|
||||
),
|
||||
color: scheme.surfaceContainerLow,
|
||||
border: Border.all(color: scheme.outlineVariant),
|
||||
),
|
||||
child: Stack(
|
||||
@@ -322,13 +320,7 @@ class _FrequencyRangePreview extends StatelessWidget {
|
||||
child: DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
gradient: LinearGradient(
|
||||
colors: [
|
||||
scheme.primary.withValues(alpha: 0.12),
|
||||
scheme.tertiary.withValues(alpha: 0.08),
|
||||
scheme.primary.withValues(alpha: 0.12),
|
||||
],
|
||||
),
|
||||
color: scheme.surfaceContainerHigh,
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -341,7 +333,7 @@ class _FrequencyRangePreview extends StatelessWidget {
|
||||
child: DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
color: scheme.primary.withValues(alpha: 0.20),
|
||||
color: scheme.primaryContainer,
|
||||
border: Border.all(color: scheme.primary),
|
||||
),
|
||||
),
|
||||
@@ -355,7 +347,7 @@ class _FrequencyRangePreview extends StatelessWidget {
|
||||
child: DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(999),
|
||||
color: scheme.tertiary.withValues(alpha: 0.32),
|
||||
color: scheme.tertiaryContainer,
|
||||
border: Border.all(color: scheme.tertiary),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -6,6 +6,7 @@ import 'package:latlong2/latlong.dart';
|
||||
import '../../../l10n/app_localizations.dart';
|
||||
import '../../../models/contact.dart';
|
||||
import '../../../models/sar_marker.dart';
|
||||
import 'compass_math.dart';
|
||||
|
||||
/// Header component for the compass dialog showing compass rose,
|
||||
/// heading, elevation, accuracy, and current location in multiple formats.
|
||||
@@ -76,7 +77,11 @@ class CompassHeader extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildInfoRow(BuildContext context, double? heading, Position? position) {
|
||||
Widget _buildInfoRow(
|
||||
BuildContext context,
|
||||
double? heading,
|
||||
Position? position,
|
||||
) {
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
return Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceAround,
|
||||
@@ -90,17 +95,13 @@ class CompassHeader extends StatelessWidget {
|
||||
_buildInfoCard(
|
||||
context,
|
||||
l10n.elevation,
|
||||
position?.altitude != null
|
||||
? '${position!.altitude.round()}m'
|
||||
: '--',
|
||||
position?.altitude != null ? '${position!.altitude.round()}m' : '--',
|
||||
Icons.terrain,
|
||||
),
|
||||
_buildInfoCard(
|
||||
context,
|
||||
l10n.accuracy,
|
||||
position?.accuracy != null
|
||||
? '±${position!.accuracy.round()}m'
|
||||
: '--',
|
||||
position?.accuracy != null ? '±${position!.accuracy.round()}m' : '--',
|
||||
Icons.gps_fixed,
|
||||
),
|
||||
],
|
||||
@@ -108,21 +109,22 @@ class CompassHeader extends StatelessWidget {
|
||||
}
|
||||
|
||||
Widget _buildInfoCard(
|
||||
BuildContext context, String label, String value, IconData icon) {
|
||||
BuildContext context,
|
||||
String label,
|
||||
String value,
|
||||
IconData icon,
|
||||
) {
|
||||
return Column(
|
||||
children: [
|
||||
Icon(icon, size: 20, color: Theme.of(context).colorScheme.primary),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
value,
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
label,
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
style: Theme.of(
|
||||
context,
|
||||
).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
|
||||
),
|
||||
Text(label, style: Theme.of(context).textTheme.bodySmall),
|
||||
],
|
||||
);
|
||||
}
|
||||
@@ -193,11 +195,16 @@ class _LargeCompassPainter extends CustomPainter {
|
||||
|
||||
// Draw degree markers
|
||||
for (int i = 0; i < 360; i += 10) {
|
||||
final angle = i * pi / 180 - pi / 2 + heading * pi / 180;
|
||||
final angle = compassDialAngleRadians(
|
||||
markerDegrees: i.toDouble(),
|
||||
headingDegrees: heading,
|
||||
);
|
||||
final isCardinal = i % 90 == 0;
|
||||
final isMajor = i % 30 == 0;
|
||||
|
||||
final startRadius = isCardinal ? radius - 25 : (isMajor ? radius - 15 : radius - 10);
|
||||
final startRadius = isCardinal
|
||||
? radius - 25
|
||||
: (isMajor ? radius - 15 : radius - 10);
|
||||
final start = Offset(
|
||||
center.dx + startRadius * cos(angle),
|
||||
center.dy + startRadius * sin(angle),
|
||||
@@ -218,7 +225,10 @@ class _LargeCompassPainter extends CustomPainter {
|
||||
final textPainter = TextPainter(textDirection: TextDirection.ltr);
|
||||
final directions = ['N', 'E', 'S', 'W'];
|
||||
for (int i = 0; i < 4; i++) {
|
||||
final angle = i * pi / 2 - pi / 2 + heading * pi / 180;
|
||||
final angle = compassDialAngleRadians(
|
||||
markerDegrees: (i * 90).toDouble(),
|
||||
headingDegrees: heading,
|
||||
);
|
||||
final x = center.dx + (radius - 35) * cos(angle);
|
||||
final y = center.dy + (radius - 35) * sin(angle);
|
||||
|
||||
@@ -243,20 +253,25 @@ class _LargeCompassPainter extends CustomPainter {
|
||||
final contactsWithDistance = contacts
|
||||
.where((c) => c.displayLocation != null)
|
||||
.map((contact) {
|
||||
final bearing = _calculateBearing(
|
||||
currentPosition!.latitude,
|
||||
currentPosition!.longitude,
|
||||
contact.displayLocation!.latitude,
|
||||
contact.displayLocation!.longitude,
|
||||
);
|
||||
final distance = _calculateDistance(
|
||||
currentPosition!.latitude,
|
||||
currentPosition!.longitude,
|
||||
contact.displayLocation!.latitude,
|
||||
contact.displayLocation!.longitude,
|
||||
);
|
||||
return {'contact': contact, 'bearing': bearing, 'distance': distance};
|
||||
}).toList();
|
||||
final bearing = _calculateBearing(
|
||||
currentPosition!.latitude,
|
||||
currentPosition!.longitude,
|
||||
contact.displayLocation!.latitude,
|
||||
contact.displayLocation!.longitude,
|
||||
);
|
||||
final distance = _calculateDistance(
|
||||
currentPosition!.latitude,
|
||||
currentPosition!.longitude,
|
||||
contact.displayLocation!.latitude,
|
||||
contact.displayLocation!.longitude,
|
||||
);
|
||||
return {
|
||||
'contact': contact,
|
||||
'bearing': bearing,
|
||||
'distance': distance,
|
||||
};
|
||||
})
|
||||
.toList();
|
||||
|
||||
if (contactsWithDistance.isEmpty) return;
|
||||
|
||||
@@ -277,7 +292,8 @@ class _LargeCompassPainter extends CustomPainter {
|
||||
double normalizedDistance = (distance / baseDistance).clamp(0.0, 1.0);
|
||||
|
||||
// Calculate contact position radius (from center to rim based on distance)
|
||||
final contactRadius = radius * normalizedDistance * 0.85; // 0.85 to keep inside rim
|
||||
final contactRadius =
|
||||
radius * normalizedDistance * 0.85; // 0.85 to keep inside rim
|
||||
|
||||
// Position of contact dot
|
||||
final dotX = center.dx + contactRadius * cos(angle);
|
||||
@@ -288,11 +304,7 @@ class _LargeCompassPainter extends CustomPainter {
|
||||
..color = Colors.lightBlue.withValues(alpha: 0.3)
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 1.5;
|
||||
canvas.drawLine(
|
||||
center,
|
||||
Offset(dotX, dotY),
|
||||
linePaint,
|
||||
);
|
||||
canvas.drawLine(center, Offset(dotX, dotY), linePaint);
|
||||
|
||||
// Draw contact dot (size varies with zoom)
|
||||
final dotSize = (6.0 * (1.0 + zoomLevel * 0.3)).clamp(4.0, 12.0);
|
||||
@@ -341,7 +353,10 @@ class _LargeCompassPainter extends CustomPainter {
|
||||
|
||||
textPainter.paint(
|
||||
canvas,
|
||||
Offset(labelX - textPainter.width / 2, labelY - textPainter.height / 2),
|
||||
Offset(
|
||||
labelX - textPainter.width / 2,
|
||||
labelY - textPainter.height / 2,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -419,11 +434,7 @@ class _LargeCompassPainter extends CustomPainter {
|
||||
..color = markerColor.withValues(alpha: 0.3)
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 2;
|
||||
canvas.drawLine(
|
||||
center,
|
||||
Offset(dotX, dotY),
|
||||
linePaint,
|
||||
);
|
||||
canvas.drawLine(center, Offset(dotX, dotY), linePaint);
|
||||
|
||||
// Draw SAR marker dot (slightly larger than contacts)
|
||||
final dotSize = (8.0 * (1.0 + zoomLevel * 0.3)).clamp(6.0, 14.0);
|
||||
@@ -472,7 +483,10 @@ class _LargeCompassPainter extends CustomPainter {
|
||||
|
||||
textPainter.paint(
|
||||
canvas,
|
||||
Offset(labelX - textPainter.width / 2, labelY - textPainter.height / 2),
|
||||
Offset(
|
||||
labelX - textPainter.width / 2,
|
||||
labelY - textPainter.height / 2,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -492,27 +506,31 @@ class _LargeCompassPainter extends CustomPainter {
|
||||
canvas.drawPath(path, indicatorPaint);
|
||||
}
|
||||
|
||||
double _calculateBearing(
|
||||
double lat1, double lon1, double lat2, double lon2) {
|
||||
double _calculateBearing(double lat1, double lon1, double lat2, double lon2) {
|
||||
final dLon = (lon2 - lon1) * pi / 180;
|
||||
final lat1Rad = lat1 * pi / 180;
|
||||
final lat2Rad = lat2 * pi / 180;
|
||||
|
||||
final y = sin(dLon) * cos(lat2Rad);
|
||||
final x = cos(lat1Rad) * sin(lat2Rad) -
|
||||
sin(lat1Rad) * cos(lat2Rad) * cos(dLon);
|
||||
final x =
|
||||
cos(lat1Rad) * sin(lat2Rad) - sin(lat1Rad) * cos(lat2Rad) * cos(dLon);
|
||||
|
||||
final bearing = atan2(y, x) * 180 / pi;
|
||||
return (bearing + 360) % 360;
|
||||
}
|
||||
|
||||
double _calculateDistance(
|
||||
double lat1, double lon1, double lat2, double lon2) {
|
||||
double lat1,
|
||||
double lon1,
|
||||
double lat2,
|
||||
double lon2,
|
||||
) {
|
||||
const R = 6371000; // Earth's radius in meters
|
||||
final dLat = (lat2 - lat1) * pi / 180;
|
||||
final dLon = (lon2 - lon1) * pi / 180;
|
||||
|
||||
final a = sin(dLat / 2) * sin(dLat / 2) +
|
||||
final a =
|
||||
sin(dLat / 2) * sin(dLat / 2) +
|
||||
cos(lat1 * pi / 180) *
|
||||
cos(lat2 * pi / 180) *
|
||||
sin(dLon / 2) *
|
||||
@@ -572,7 +590,8 @@ class _LocationFormatToggleState extends State<_LocationFormatToggle> {
|
||||
final String displayText;
|
||||
|
||||
if (_showDMS) {
|
||||
displayText = '${_formatDMS(position.latitude, true)} ${_formatDMS(position.longitude, false)}';
|
||||
displayText =
|
||||
'${_formatDMS(position.latitude, true)} ${_formatDMS(position.longitude, false)}';
|
||||
} else {
|
||||
displayText = l10n.latLonFormat(
|
||||
position.latitude.toStringAsFixed(5),
|
||||
@@ -598,9 +617,9 @@ class _LocationFormatToggleState extends State<_LocationFormatToggle> {
|
||||
displayText,
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
fontFamily: 'monospace',
|
||||
),
|
||||
fontWeight: FontWeight.w600,
|
||||
fontFamily: 'monospace',
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
22
lib/widgets/map/compass/compass_math.dart
Normal file
22
lib/widgets/map/compass/compass_math.dart
Normal file
@@ -0,0 +1,22 @@
|
||||
import 'dart:math';
|
||||
|
||||
/// Rotate the compass rose opposite the device heading so the current heading
|
||||
/// stays under the fixed indicator at the top of the dial.
|
||||
double compassRoseRotationRadians(double headingDegrees) {
|
||||
final normalizedHeading = headingDegrees % 360;
|
||||
return _normalizeRadians(-normalizedHeading * pi / 180);
|
||||
}
|
||||
|
||||
/// Convert a compass marker bearing into an on-screen angle for the dial.
|
||||
double compassDialAngleRadians({
|
||||
required double markerDegrees,
|
||||
required double headingDegrees,
|
||||
}) {
|
||||
return _normalizeRadians(
|
||||
markerDegrees * pi / 180 -
|
||||
pi / 2 +
|
||||
compassRoseRotationRadians(headingDegrees),
|
||||
);
|
||||
}
|
||||
|
||||
double _normalizeRadians(double angle) => atan2(sin(angle), cos(angle));
|
||||
@@ -1,5 +1,6 @@
|
||||
import 'dart:math';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'compass/compass_math.dart';
|
||||
|
||||
class CompassWidget extends StatelessWidget {
|
||||
final double heading;
|
||||
@@ -21,9 +22,9 @@ class CompassWidget extends StatelessWidget {
|
||||
child: Stack(
|
||||
alignment: Alignment.center,
|
||||
children: [
|
||||
// Compass rose background - rotates to show true north at top
|
||||
// Rotate the rose opposite the heading under the fixed needle.
|
||||
Transform.rotate(
|
||||
angle: heading * pi / 180,
|
||||
angle: compassRoseRotationRadians(heading),
|
||||
child: CustomPaint(
|
||||
size: const Size(40, 40),
|
||||
painter: _CompassRosePainter(),
|
||||
@@ -76,9 +77,7 @@ class _CompassRosePainter extends CustomPainter {
|
||||
canvas.drawCircle(center, radius, paint);
|
||||
|
||||
// Draw cardinal direction markers
|
||||
final textPainter = TextPainter(
|
||||
textDirection: TextDirection.ltr,
|
||||
);
|
||||
final textPainter = TextPainter(textDirection: TextDirection.ltr);
|
||||
|
||||
final directions = ['N', 'E', 'S', 'W'];
|
||||
for (int i = 0; i < 4; i++) {
|
||||
|
||||
@@ -174,15 +174,22 @@ class _MessageBubbleState extends State<MessageBubble> {
|
||||
!widget.message.isSystemMessage) {
|
||||
context.read<MessagesProvider>().markAsRead(widget.message.id);
|
||||
}
|
||||
|
||||
if (!widget.isCompact && !isSarMarker && !isDrawing) {
|
||||
setState(() {
|
||||
_showReceivedStats = !_showReceivedStats;
|
||||
});
|
||||
}
|
||||
widget.onTap?.call();
|
||||
}
|
||||
|
||||
void _handleBubbleDoubleTap({
|
||||
required bool isSarMarker,
|
||||
required bool isDrawing,
|
||||
}) {
|
||||
if (widget.isCompact || isSarMarker || isDrawing) {
|
||||
return;
|
||||
}
|
||||
|
||||
setState(() {
|
||||
_showReceivedStats = !_showReceivedStats;
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _retryFailedMessage(
|
||||
BuildContext context,
|
||||
Message failedMessage,
|
||||
@@ -684,7 +691,10 @@ class _MessageBubbleState extends State<MessageBubble> {
|
||||
|
||||
void copyField(String value) {
|
||||
Clipboard.setData(ClipboardData(text: value));
|
||||
ToastLogger.success(context, AppLocalizations.of(context)!.textCopiedToClipboard);
|
||||
ToastLogger.success(
|
||||
context,
|
||||
AppLocalizations.of(context)!.textCopiedToClipboard,
|
||||
);
|
||||
}
|
||||
|
||||
showModalBottomSheet(
|
||||
@@ -812,7 +822,9 @@ class _MessageBubbleState extends State<MessageBubble> {
|
||||
),
|
||||
_detailRow(
|
||||
sheetContext,
|
||||
label: AppLocalizations.of(context)!.receivedRfc3339,
|
||||
label: AppLocalizations.of(
|
||||
context,
|
||||
)!.receivedRfc3339,
|
||||
value: _formatRfc3339(widget.message.receivedAt),
|
||||
onCopy: () => copyField(
|
||||
_formatRfc3339(widget.message.receivedAt),
|
||||
@@ -821,14 +833,18 @@ class _MessageBubbleState extends State<MessageBubble> {
|
||||
if (widget.message.expectedAckTag != null)
|
||||
_detailRow(
|
||||
sheetContext,
|
||||
label: AppLocalizations.of(context)!.expectedAckTag,
|
||||
label: AppLocalizations.of(
|
||||
context,
|
||||
)!.expectedAckTag,
|
||||
value: widget.message.expectedAckTag!
|
||||
.toString(),
|
||||
),
|
||||
if (receptionDetails?.senderToReceiptMs != null)
|
||||
_detailRow(
|
||||
sheetContext,
|
||||
label: AppLocalizations.of(context)!.senderToReceipt,
|
||||
label: AppLocalizations.of(
|
||||
context,
|
||||
)!.senderToReceipt,
|
||||
value: _formatDurationMs(
|
||||
receptionDetails!.senderToReceiptMs!,
|
||||
),
|
||||
@@ -836,7 +852,9 @@ class _MessageBubbleState extends State<MessageBubble> {
|
||||
if (receptionDetails?.estimatedTransmitMs != null)
|
||||
_detailRow(
|
||||
sheetContext,
|
||||
label: AppLocalizations.of(context)!.estimatedTx,
|
||||
label: AppLocalizations.of(
|
||||
context,
|
||||
)!.estimatedTx,
|
||||
value: _formatDurationMs(
|
||||
receptionDetails!.estimatedTransmitMs!,
|
||||
),
|
||||
@@ -844,7 +862,9 @@ class _MessageBubbleState extends State<MessageBubble> {
|
||||
if (receptionDetails?.postTransmitDelayMs != null)
|
||||
_detailRow(
|
||||
sheetContext,
|
||||
label: AppLocalizations.of(context)!.posttxDelay,
|
||||
label: AppLocalizations.of(
|
||||
context,
|
||||
)!.posttxDelay,
|
||||
value: _formatDurationMs(
|
||||
receptionDetails!.postTransmitDelayMs!,
|
||||
),
|
||||
@@ -852,7 +872,9 @@ class _MessageBubbleState extends State<MessageBubble> {
|
||||
if (widget.receivedCopies > 1)
|
||||
_detailRow(
|
||||
sheetContext,
|
||||
label: AppLocalizations.of(context)!.receivedCopies,
|
||||
label: AppLocalizations.of(
|
||||
context,
|
||||
)!.receivedCopies,
|
||||
value: '${widget.receivedCopies}',
|
||||
),
|
||||
if (widget.message.suggestedTimeoutMs != null)
|
||||
@@ -883,7 +905,9 @@ class _MessageBubbleState extends State<MessageBubble> {
|
||||
if (widget.message.retryAttempt > 0)
|
||||
_detailRow(
|
||||
sheetContext,
|
||||
label: AppLocalizations.of(context)!.retryAttempt,
|
||||
label: AppLocalizations.of(
|
||||
context,
|
||||
)!.retryAttempt,
|
||||
value: '${widget.message.retryAttempt}/4',
|
||||
),
|
||||
if (widget.message.lastRetryAt != null)
|
||||
@@ -900,21 +924,27 @@ class _MessageBubbleState extends State<MessageBubble> {
|
||||
if (widget.message.usedFloodFallback)
|
||||
_detailRow(
|
||||
sheetContext,
|
||||
label: AppLocalizations.of(context)!.floodFallback,
|
||||
label: AppLocalizations.of(
|
||||
context,
|
||||
)!.floodFallback,
|
||||
value: AppLocalizations.of(context)!.yes,
|
||||
),
|
||||
if (routeMetadata?.canonicalPath
|
||||
case final routePath?)
|
||||
_detailRow(
|
||||
sheetContext,
|
||||
label: AppLocalizations.of(context)!.selectedPath,
|
||||
label: AppLocalizations.of(
|
||||
context,
|
||||
)!.selectedPath,
|
||||
value: routePath,
|
||||
onCopy: () => copyField(routePath),
|
||||
),
|
||||
if (retryResult != null)
|
||||
_detailRow(
|
||||
sheetContext,
|
||||
label: AppLocalizations.of(context)!.retryResult,
|
||||
label: AppLocalizations.of(
|
||||
context,
|
||||
)!.retryResult,
|
||||
value: retryResult,
|
||||
),
|
||||
if (packetPathHex != null)
|
||||
@@ -964,7 +994,9 @@ class _MessageBubbleState extends State<MessageBubble> {
|
||||
if (recipientPrefixHex != null)
|
||||
_detailRow(
|
||||
sheetContext,
|
||||
label: AppLocalizations.of(context)!.recipientKey,
|
||||
label: AppLocalizations.of(
|
||||
context,
|
||||
)!.recipientKey,
|
||||
value: recipientPrefixHex,
|
||||
onCopy: () => copyField(recipientPrefixHex),
|
||||
),
|
||||
@@ -994,7 +1026,9 @@ class _MessageBubbleState extends State<MessageBubble> {
|
||||
if (voiceSession != null)
|
||||
_detailRow(
|
||||
sheetContext,
|
||||
label: AppLocalizations.of(context)!.sessionProgress,
|
||||
label: AppLocalizations.of(
|
||||
context,
|
||||
)!.sessionProgress,
|
||||
value:
|
||||
'${voiceSession.receivedCount}/${voiceSession.total} segments',
|
||||
),
|
||||
@@ -1009,14 +1043,18 @@ class _MessageBubbleState extends State<MessageBubble> {
|
||||
if (transferDetails != null)
|
||||
_detailRow(
|
||||
sheetContext,
|
||||
label: AppLocalizations.of(context)!.transfers,
|
||||
label: AppLocalizations.of(
|
||||
context,
|
||||
)!.transfers,
|
||||
value: '${transferDetails.totalTransfers}',
|
||||
),
|
||||
if (transferDetails != null &&
|
||||
transferDetails.downloaders.isNotEmpty)
|
||||
_detailRow(
|
||||
sheetContext,
|
||||
label: AppLocalizations.of(context)!.downloadedBy,
|
||||
label: AppLocalizations.of(
|
||||
context,
|
||||
)!.downloadedBy,
|
||||
value: _formatDownloaderSummary(
|
||||
transferDetails,
|
||||
),
|
||||
@@ -1024,7 +1062,9 @@ class _MessageBubbleState extends State<MessageBubble> {
|
||||
if (voiceTxEstimate > Duration.zero)
|
||||
_detailRow(
|
||||
sheetContext,
|
||||
label: AppLocalizations.of(context)!.estimatedTx,
|
||||
label: AppLocalizations.of(
|
||||
context,
|
||||
)!.estimatedTx,
|
||||
value: voiceTxEstimate.inSeconds < 60
|
||||
? '~${voiceTxEstimate.inSeconds}s'
|
||||
: '~${voiceTxEstimate.inMinutes}m ${voiceTxEstimate.inSeconds % 60}s',
|
||||
@@ -1075,14 +1115,18 @@ class _MessageBubbleState extends State<MessageBubble> {
|
||||
if (transferDetails != null)
|
||||
_detailRow(
|
||||
sheetContext,
|
||||
label: AppLocalizations.of(context)!.transfers,
|
||||
label: AppLocalizations.of(
|
||||
context,
|
||||
)!.transfers,
|
||||
value: '${transferDetails.totalTransfers}',
|
||||
),
|
||||
if (transferDetails != null &&
|
||||
transferDetails.downloaders.isNotEmpty)
|
||||
_detailRow(
|
||||
sheetContext,
|
||||
label: AppLocalizations.of(context)!.downloadedBy,
|
||||
label: AppLocalizations.of(
|
||||
context,
|
||||
)!.downloadedBy,
|
||||
value: _formatDownloaderSummary(
|
||||
transferDetails,
|
||||
),
|
||||
@@ -1090,7 +1134,9 @@ class _MessageBubbleState extends State<MessageBubble> {
|
||||
if (imageTxEstimate > Duration.zero)
|
||||
_detailRow(
|
||||
sheetContext,
|
||||
label: AppLocalizations.of(context)!.estimatedTx,
|
||||
label: AppLocalizations.of(
|
||||
context,
|
||||
)!.estimatedTx,
|
||||
value: imageTxEstimate.inSeconds < 60
|
||||
? '~${imageTxEstimate.inSeconds}s'
|
||||
: '~${imageTxEstimate.inMinutes}m ${imageTxEstimate.inSeconds % 60}s',
|
||||
@@ -1438,7 +1484,10 @@ class _MessageBubbleState extends State<MessageBubble> {
|
||||
|
||||
// Share the location
|
||||
SharePlus.instance.share(
|
||||
ShareParams(text: shareText, subject: AppLocalizations.of(context)!.sarLocationShare),
|
||||
ShareParams(
|
||||
text: shareText,
|
||||
subject: AppLocalizations.of(context)!.sarLocationShare,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1890,6 +1939,10 @@ class _MessageBubbleState extends State<MessageBubble> {
|
||||
isSarMarker: isSarMarker,
|
||||
isDrawing: message.isDrawing,
|
||||
),
|
||||
onDoubleTap: () => _handleBubbleDoubleTap(
|
||||
isSarMarker: isSarMarker,
|
||||
isDrawing: message.isDrawing,
|
||||
),
|
||||
onLongPress: widget.isCompact
|
||||
? null
|
||||
: () => _showMessageOptions(context),
|
||||
@@ -2779,10 +2832,8 @@ class _MessageBubbleState extends State<MessageBubble> {
|
||||
);
|
||||
},
|
||||
),
|
||||
if (shouldShowSentChannelStats(
|
||||
message,
|
||||
showReceivedStats: _showReceivedStats,
|
||||
)) ...[
|
||||
if (_showReceivedStats &&
|
||||
shouldShowSentChannelStats(message)) ...[
|
||||
const SizedBox(height: 6),
|
||||
buildChannelEchoStatus(context, message),
|
||||
],
|
||||
|
||||
@@ -6,6 +6,7 @@ import '../../models/message_route_metadata.dart';
|
||||
import '../../models/path_selection.dart';
|
||||
import '../../models/message_reception_details.dart';
|
||||
import '../../providers/messages_provider.dart';
|
||||
import '../../utils/link_quality.dart';
|
||||
|
||||
IconData getDeliveryStatusIcon(MessageDeliveryStatus status) {
|
||||
switch (status) {
|
||||
@@ -91,10 +92,7 @@ Widget buildChannelEchoStatus(BuildContext context, Message message) {
|
||||
);
|
||||
}
|
||||
|
||||
bool shouldShowSentChannelStats(
|
||||
Message message, {
|
||||
required bool showReceivedStats,
|
||||
}) {
|
||||
bool shouldShowSentChannelStats(Message message) {
|
||||
if (!message.isSentMessage || !message.isChannelMessage) {
|
||||
return false;
|
||||
}
|
||||
@@ -104,7 +102,7 @@ bool shouldShowSentChannelStats(
|
||||
message.lastEchoRssiDbm != null ||
|
||||
message.lastEchoSnrRaw != null ||
|
||||
message.expectedAckTag != null;
|
||||
return showReceivedStats && hasSignalData;
|
||||
return hasSignalData;
|
||||
}
|
||||
|
||||
Widget buildReceivedSignalStatus(
|
||||
@@ -382,30 +380,3 @@ Widget _signalCapsule(
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
int rssiScore(int rssiDbm) => ((rssiDbm + 120) / 10).round().clamp(0, 5);
|
||||
|
||||
int snrScore(double snrDb) => ((snrDb + 5.0) / 5.0).round().clamp(0, 5);
|
||||
|
||||
String linkQualityLabel(int? rssiDbm, double? snrDb) {
|
||||
var score = 0;
|
||||
if (rssiDbm != null) score += rssiScore(rssiDbm);
|
||||
if (snrDb != null) score += snrScore(snrDb);
|
||||
if (score >= 8) return 'Excellent';
|
||||
if (score >= 6) return 'Good';
|
||||
if (score >= 4) return 'Fair';
|
||||
return 'Weak';
|
||||
}
|
||||
|
||||
Color linkQualityColor(String quality) {
|
||||
switch (quality) {
|
||||
case 'Excellent':
|
||||
return Colors.green;
|
||||
case 'Good':
|
||||
return Colors.lightGreen;
|
||||
case 'Fair':
|
||||
return Colors.orange;
|
||||
default:
|
||||
return Colors.redAccent;
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -207,9 +207,25 @@ List<SensorMetricOption> sensorMetricOptionsFor(
|
||||
),
|
||||
];
|
||||
|
||||
// Keys that are already shown as core telemetry fields above.
|
||||
// Skip them from extraSensorData to avoid duplicates.
|
||||
final coreFieldKeys = <String>{
|
||||
if (batteryMilliVolts != null || batteryPercentage != null)
|
||||
...extraSensorData?.keys.where(
|
||||
(k) => k.startsWith('voltage_') || k.startsWith('analog_input_'),
|
||||
) ??
|
||||
[],
|
||||
if (temperature != null)
|
||||
...extraSensorData?.keys.where((k) => k.startsWith('temperature_')) ?? [],
|
||||
if (humidity != null)
|
||||
...extraSensorData?.keys.where((k) => k.startsWith('humidity_')) ?? [],
|
||||
if (pressure != null)
|
||||
...extraSensorData?.keys.where((k) => k.startsWith('pressure_')) ?? [],
|
||||
};
|
||||
|
||||
if (extraSensorData != null) {
|
||||
for (final key in extraSensorData.keys) {
|
||||
if (_isTelemetryMetadataKey(key)) {
|
||||
if (_isTelemetryMetadataKey(key) || coreFieldKeys.contains(key)) {
|
||||
continue;
|
||||
}
|
||||
final metricKey = _parseMetricKey(key);
|
||||
@@ -276,14 +292,14 @@ SensorMetricCardData? _buildOptionPreviewCardData(
|
||||
);
|
||||
case 'illuminance':
|
||||
final lux = _previewAsDouble(value);
|
||||
final irradiance = lux == null
|
||||
? null
|
||||
: _previewFormatDaylightIrradiance(lux);
|
||||
return SensorMetricCardData(
|
||||
fieldKey: fieldKey,
|
||||
icon: Icons.light_mode_outlined,
|
||||
label: label,
|
||||
value: previewValue,
|
||||
secondaryValue: lux == null
|
||||
? null
|
||||
: '~${_formatPreviewNumber(_previewApproxDaylightIrradiance(lux), maxFractionDigits: 1)} W/m2 daylight',
|
||||
value: irradiance ?? previewValue,
|
||||
accent: const Color(0xFFC17B1D),
|
||||
channel: metricKey.channel,
|
||||
);
|
||||
@@ -660,6 +676,10 @@ double _previewApproxDaylightIrradiance(double lux) {
|
||||
return lux / 120.0;
|
||||
}
|
||||
|
||||
String _previewFormatDaylightIrradiance(double lux) {
|
||||
return '~${_formatPreviewNumber(_previewApproxDaylightIrradiance(lux), maxFractionDigits: 1)} W/m2';
|
||||
}
|
||||
|
||||
String _previewFormatCardinalDirection(double degrees) {
|
||||
const points = <String>['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'];
|
||||
final normalized = ((degrees % 360) + 360) % 360;
|
||||
@@ -685,7 +705,7 @@ String? _sensorMetricPreviewValue(String rawKey, dynamic value) {
|
||||
case 'illuminance':
|
||||
final lux = _previewAsDouble(value);
|
||||
if (lux == null) return null;
|
||||
return '${_formatPreviewNumber(lux, maxFractionDigits: 0)} lx';
|
||||
return _previewFormatDaylightIrradiance(lux);
|
||||
|
||||
case 'presence':
|
||||
final isPresent = _previewAsBool(value);
|
||||
@@ -1425,9 +1445,7 @@ class SensorTelemetryCard extends StatelessWidget {
|
||||
fieldKey: _extraFieldKey(rawKey),
|
||||
icon: Icons.light_mode_outlined,
|
||||
label: label,
|
||||
value: '${_formatNumber(lux, maxFractionDigits: 0)} lx',
|
||||
secondaryValue:
|
||||
'~${_formatNumber(_approxDaylightIrradiance(lux), maxFractionDigits: 1)} W/m2 daylight',
|
||||
value: _formatDaylightIrradiance(lux),
|
||||
accent: const Color(0xFFC17B1D),
|
||||
channel: metricKey.channel,
|
||||
);
|
||||
@@ -1944,6 +1962,10 @@ class SensorTelemetryCard extends StatelessWidget {
|
||||
return lux / 120.0;
|
||||
}
|
||||
|
||||
String _formatDaylightIrradiance(double lux) {
|
||||
return '~${_formatNumber(_approxDaylightIrradiance(lux), maxFractionDigits: 1)} W/m2';
|
||||
}
|
||||
|
||||
String _formatCurrent(double amps) {
|
||||
final absolute = amps.abs();
|
||||
if (absolute < 1.0) {
|
||||
@@ -2237,14 +2259,31 @@ class SensorMetricTile extends StatelessWidget {
|
||||
border: Border.all(color: data.accent.withValues(alpha: 0.14)),
|
||||
),
|
||||
child: data.mapLocation == null || !allowMapPreview
|
||||
? Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
? Stack(
|
||||
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),
|
||||
),
|
||||
],
|
||||
),
|
||||
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(
|
||||
@@ -2381,39 +2420,14 @@ class _MetricText extends StatelessWidget {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
data.label,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: Theme.of(context).textTheme.labelMedium?.copyWith(
|
||||
color: data.accent,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (data.channel != null) ...[
|
||||
const SizedBox(width: 8),
|
||||
Container(
|
||||
key: ValueKey('${keyPrefix}_channel_${data.fieldKey}'),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
|
||||
decoration: BoxDecoration(
|
||||
color: data.accent.withValues(alpha: 0.12),
|
||||
borderRadius: BorderRadius.circular(999),
|
||||
),
|
||||
child: Text(
|
||||
'ch${data.channel}',
|
||||
style: Theme.of(context).textTheme.labelSmall?.copyWith(
|
||||
color: data.accent,
|
||||
fontWeight: FontWeight.w800,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
Text(
|
||||
data.label,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: Theme.of(context).textTheme.labelMedium?.copyWith(
|
||||
color: data.accent,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
#include <audioplayers_linux/audioplayers_linux_plugin.h>
|
||||
#include <file_selector_linux/file_selector_plugin.h>
|
||||
#include <flutter_avif_linux/flutter_avif_linux_plugin.h>
|
||||
#include <flutter_libserialport/flutter_libserialport_plugin.h>
|
||||
#include <record_linux/record_linux_plugin.h>
|
||||
#include <url_launcher_linux/url_launcher_plugin.h>
|
||||
|
||||
@@ -22,6 +23,9 @@ void fl_register_plugins(FlPluginRegistry* registry) {
|
||||
g_autoptr(FlPluginRegistrar) flutter_avif_linux_registrar =
|
||||
fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterAvifLinuxPlugin");
|
||||
flutter_avif_linux_plugin_register_with_registrar(flutter_avif_linux_registrar);
|
||||
g_autoptr(FlPluginRegistrar) flutter_libserialport_registrar =
|
||||
fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterLibserialportPlugin");
|
||||
flutter_libserialport_plugin_register_with_registrar(flutter_libserialport_registrar);
|
||||
g_autoptr(FlPluginRegistrar) record_linux_registrar =
|
||||
fl_plugin_registry_get_registrar_for_plugin(registry, "RecordLinuxPlugin");
|
||||
record_linux_plugin_register_with_registrar(record_linux_registrar);
|
||||
|
||||
@@ -6,6 +6,7 @@ list(APPEND FLUTTER_PLUGIN_LIST
|
||||
audioplayers_linux
|
||||
file_selector_linux
|
||||
flutter_avif_linux
|
||||
flutter_libserialport
|
||||
record_linux
|
||||
url_launcher_linux
|
||||
)
|
||||
|
||||
@@ -11,6 +11,7 @@ import file_picker
|
||||
import file_selector_macos
|
||||
import flutter_avif_macos
|
||||
import flutter_blue_plus_darwin
|
||||
import flutter_libserialport
|
||||
import flutter_local_notifications
|
||||
import geolocator_apple
|
||||
import nsd_macos
|
||||
@@ -30,6 +31,7 @@ func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
|
||||
FileSelectorPlugin.register(with: registry.registrar(forPlugin: "FileSelectorPlugin"))
|
||||
FlutterAvifPlugin.register(with: registry.registrar(forPlugin: "FlutterAvifPlugin"))
|
||||
FlutterBluePlusPlugin.register(with: registry.registrar(forPlugin: "FlutterBluePlusPlugin"))
|
||||
FlutterLibserialportPlugin.register(with: registry.registrar(forPlugin: "FlutterLibserialportPlugin"))
|
||||
FlutterLocalNotificationsPlugin.register(with: registry.registrar(forPlugin: "FlutterLocalNotificationsPlugin"))
|
||||
GeolocatorPlugin.register(with: registry.registrar(forPlugin: "GeolocatorPlugin"))
|
||||
NsdMacosPlugin.register(with: registry.registrar(forPlugin: "NsdMacosPlugin"))
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
platform :osx, '10.15'
|
||||
platform :osx, '26.0'
|
||||
|
||||
# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
|
||||
ENV['COCOAPODS_DISABLE_STATS'] = 'true'
|
||||
@@ -38,6 +38,9 @@ end
|
||||
post_install do |installer|
|
||||
installer.pods_project.targets.each do |target|
|
||||
flutter_additional_macos_build_settings(target)
|
||||
target.build_configurations.each do |config|
|
||||
config.build_settings['MACOSX_DEPLOYMENT_TARGET'] = '26.0'
|
||||
end
|
||||
# codec2_flutter uses ARM-specific register asm("sp") in debug_alloc.h that
|
||||
# does not compile on x86_64 macOS. Voice messages are iOS-only, so exclude
|
||||
# all C source files from the macOS codec2_flutter build entirely.
|
||||
|
||||
@@ -15,12 +15,16 @@ PODS:
|
||||
- flutter_blue_plus_darwin (0.0.2):
|
||||
- Flutter
|
||||
- FlutterMacOS
|
||||
- flutter_libserialport (0.0.1):
|
||||
- FlutterMacOS
|
||||
- libserialport
|
||||
- flutter_local_notifications (0.0.1):
|
||||
- FlutterMacOS
|
||||
- FlutterMacOS (1.0.0)
|
||||
- geolocator_apple (1.2.0):
|
||||
- Flutter
|
||||
- FlutterMacOS
|
||||
- libserialport (0.1.1)
|
||||
- nsd_macos (0.0.1):
|
||||
- FlutterMacOS
|
||||
- package_info_plus (0.0.1):
|
||||
@@ -40,6 +44,8 @@ PODS:
|
||||
- FlutterMacOS
|
||||
- url_launcher_macos (0.0.1):
|
||||
- FlutterMacOS
|
||||
- wakelock_plus (0.0.1):
|
||||
- FlutterMacOS
|
||||
|
||||
DEPENDENCIES:
|
||||
- audioplayers_darwin (from `Flutter/ephemeral/.symlinks/plugins/audioplayers_darwin/darwin`)
|
||||
@@ -49,6 +55,7 @@ DEPENDENCIES:
|
||||
- file_selector_macos (from `Flutter/ephemeral/.symlinks/plugins/file_selector_macos/macos`)
|
||||
- flutter_avif_macos (from `Flutter/ephemeral/.symlinks/plugins/flutter_avif_macos/macos`)
|
||||
- flutter_blue_plus_darwin (from `Flutter/ephemeral/.symlinks/plugins/flutter_blue_plus_darwin/darwin`)
|
||||
- flutter_libserialport (from `Flutter/ephemeral/.symlinks/plugins/flutter_libserialport/macos`)
|
||||
- flutter_local_notifications (from `Flutter/ephemeral/.symlinks/plugins/flutter_local_notifications/macos`)
|
||||
- FlutterMacOS (from `Flutter/ephemeral`)
|
||||
- geolocator_apple (from `Flutter/ephemeral/.symlinks/plugins/geolocator_apple/darwin`)
|
||||
@@ -60,6 +67,11 @@ DEPENDENCIES:
|
||||
- shared_preferences_foundation (from `Flutter/ephemeral/.symlinks/plugins/shared_preferences_foundation/darwin`)
|
||||
- sqflite_darwin (from `Flutter/ephemeral/.symlinks/plugins/sqflite_darwin/darwin`)
|
||||
- url_launcher_macos (from `Flutter/ephemeral/.symlinks/plugins/url_launcher_macos/macos`)
|
||||
- wakelock_plus (from `Flutter/ephemeral/.symlinks/plugins/wakelock_plus/macos`)
|
||||
|
||||
SPEC REPOS:
|
||||
trunk:
|
||||
- libserialport
|
||||
|
||||
EXTERNAL SOURCES:
|
||||
audioplayers_darwin:
|
||||
@@ -76,6 +88,8 @@ EXTERNAL SOURCES:
|
||||
:path: Flutter/ephemeral/.symlinks/plugins/flutter_avif_macos/macos
|
||||
flutter_blue_plus_darwin:
|
||||
:path: Flutter/ephemeral/.symlinks/plugins/flutter_blue_plus_darwin/darwin
|
||||
flutter_libserialport:
|
||||
:path: Flutter/ephemeral/.symlinks/plugins/flutter_libserialport/macos
|
||||
flutter_local_notifications:
|
||||
:path: Flutter/ephemeral/.symlinks/plugins/flutter_local_notifications/macos
|
||||
FlutterMacOS:
|
||||
@@ -98,6 +112,8 @@ EXTERNAL SOURCES:
|
||||
:path: Flutter/ephemeral/.symlinks/plugins/sqflite_darwin/darwin
|
||||
url_launcher_macos:
|
||||
:path: Flutter/ephemeral/.symlinks/plugins/url_launcher_macos/macos
|
||||
wakelock_plus:
|
||||
:path: Flutter/ephemeral/.symlinks/plugins/wakelock_plus/macos
|
||||
|
||||
SPEC CHECKSUMS:
|
||||
audioplayers_darwin: 835ced6edd4c9fc8ebb0a7cc9e294a91d99917d5
|
||||
@@ -107,9 +123,11 @@ SPEC CHECKSUMS:
|
||||
file_selector_macos: 9e9e068e90ebee155097d00e89ae91edb2374db7
|
||||
flutter_avif_macos: 9ed61d67adfbd6964eccb59971020fb55c31fc11
|
||||
flutter_blue_plus_darwin: 20a08bfeaa0f7804d524858d3d8744bcc1b6dbc3
|
||||
flutter_libserialport: 2c523cb8d8203fc6d1b0da88190da31ac970eb93
|
||||
flutter_local_notifications: 1fc7ffb10a83d6a2eeeeddb152d43f1944b0aad0
|
||||
FlutterMacOS: d0db08ddef1a9af05a5ec4b724367152bb0500b1
|
||||
geolocator_apple: ab36aa0e8b7d7a2d7639b3b4e48308394e8cef5e
|
||||
libserialport: 1cb25e66ef3c92a8e59c2ea3820302c3fa2268cd
|
||||
nsd_macos: a472240e770b92f6c6df1022403aa29c90d012e3
|
||||
package_info_plus: f0052d280d17aa382b932f399edf32507174e870
|
||||
path_provider_foundation: bb55f6dbba17d0dccd6737fe6f7f34fbd0376880
|
||||
@@ -118,7 +136,8 @@ SPEC CHECKSUMS:
|
||||
shared_preferences_foundation: 7036424c3d8ec98dfe75ff1667cb0cd531ec82bb
|
||||
sqflite_darwin: 20b2a3a3b70e43edae938624ce550a3cbf66a3d0
|
||||
url_launcher_macos: f87a979182d112f911de6820aefddaf56ee9fbfd
|
||||
wakelock_plus: 917609be14d812ddd9e9528876538b2263aaa03b
|
||||
|
||||
PODFILE CHECKSUM: e3de8f2486e300492cc80a2fe0576e9d269ba22b
|
||||
PODFILE CHECKSUM: 467066e8d30d1105257e0877b8cdd20642e7b3db
|
||||
|
||||
COCOAPODS: 1.16.2
|
||||
|
||||
@@ -557,7 +557,7 @@
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
MACOSX_DEPLOYMENT_TARGET = 10.15;
|
||||
MACOSX_DEPLOYMENT_TARGET = 26.0;
|
||||
MTL_ENABLE_DEBUG_INFO = NO;
|
||||
SDKROOT = macosx;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
@@ -639,7 +639,7 @@
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
MACOSX_DEPLOYMENT_TARGET = 10.15;
|
||||
MACOSX_DEPLOYMENT_TARGET = 26.0;
|
||||
MTL_ENABLE_DEBUG_INFO = YES;
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
SDKROOT = macosx;
|
||||
@@ -689,7 +689,7 @@
|
||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||
MACOSX_DEPLOYMENT_TARGET = 10.15;
|
||||
MACOSX_DEPLOYMENT_TARGET = 26.0;
|
||||
MTL_ENABLE_DEBUG_INFO = NO;
|
||||
SDKROOT = macosx;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
|
||||
@@ -2,11 +2,7 @@
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>com.apple.security.app-sandbox</key>
|
||||
<true/>
|
||||
<key>com.apple.security.cs.allow-jit</key>
|
||||
<true/>
|
||||
<key>com.apple.security.network.server</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
|
||||
@@ -24,10 +24,16 @@
|
||||
<false/>
|
||||
<key>LSMinimumSystemVersion</key>
|
||||
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
|
||||
<key>NSBluetoothAlwaysUsageDescription</key>
|
||||
<string>MeshCore SAR needs Bluetooth to discover and communicate with MeshCore devices during SAR operations</string>
|
||||
<key>NSBluetoothPeripheralUsageDescription</key>
|
||||
<string>MeshCore SAR needs Bluetooth to discover and communicate with MeshCore devices during SAR operations</string>
|
||||
<key>NSHumanReadableCopyright</key>
|
||||
<string>$(PRODUCT_COPYRIGHT)</string>
|
||||
<key>NSMainNibFile</key>
|
||||
<string>MainMenu</string>
|
||||
<key>NSLocationUsageDescription</key>
|
||||
<string>MeshCore SAR needs your location to track your team, share your position over the mesh network, and show your location on the map during SAR operations</string>
|
||||
<key>NSMicrophoneUsageDescription</key>
|
||||
<string>MeshCore SAR needs microphone access to send voice messages over the mesh radio network during SAR operations</string>
|
||||
<key>NSPrincipalClass</key>
|
||||
|
||||
@@ -2,7 +2,5 @@
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>com.apple.security.app-sandbox</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
|
||||
34
pubspec.lock
34
pubspec.lock
@@ -218,6 +218,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "7.0.3"
|
||||
dylib:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: dylib
|
||||
sha256: bf609b3eb6492a3309b3d1dbe8f83a4031de5535dd7686be33487051cc760bb0
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.3.3"
|
||||
exif:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -479,6 +487,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.14.4"
|
||||
flutter_libserialport:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: flutter_libserialport
|
||||
sha256: f24b5fe6f1821d1c1b3bf2be737ca53f6b0ae78657032a790aa00abb810c8759
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.6.0"
|
||||
flutter_lints:
|
||||
dependency: "direct dev"
|
||||
description:
|
||||
@@ -759,6 +775,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.0.2"
|
||||
libserialport:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: libserialport
|
||||
sha256: "392e1592def65282429832ec66fa25e9e163d3b37716b97691482e2406720727"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.3.0+1"
|
||||
lints:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -788,7 +812,7 @@ packages:
|
||||
description:
|
||||
path: "."
|
||||
ref: main
|
||||
resolved-ref: abff892fac0dd0e8004bfa1f415df74b44b8eb52
|
||||
resolved-ref: "3dbc82170583f616b590e5204a307a02f2b8833d"
|
||||
url: "https://github.com/dz0ny/meshcore_client.git"
|
||||
source: git
|
||||
version: "0.1.0"
|
||||
@@ -1477,6 +1501,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.1"
|
||||
webserial:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: webserial
|
||||
sha256: b39c2175190ee1c75e996bf137bfee3e3e8fd06ee0ec24f0d3c10bdf7b323786
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.2.0"
|
||||
win32:
|
||||
dependency: transitive
|
||||
description:
|
||||
|
||||
@@ -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.0317.1+33
|
||||
version: 2026.0319.1+35
|
||||
|
||||
environment:
|
||||
sdk: ^3.9.2
|
||||
@@ -123,6 +123,8 @@ dependencies:
|
||||
nsd: ^4.0.3
|
||||
usb_serial: ^0.5.2
|
||||
web: ^1.1.1
|
||||
flutter_libserialport: ^0.6.0
|
||||
webserial: ^1.2.0
|
||||
|
||||
dev_dependencies:
|
||||
flutter_test:
|
||||
|
||||
35
test/models/channel_test.dart
Normal file
35
test/models/channel_test.dart
Normal file
@@ -0,0 +1,35 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_sar_app/models/channel.dart';
|
||||
|
||||
void main() {
|
||||
test('hash channels expose deterministic psk_base64', () {
|
||||
final channel = Channel.create(index: 3, name: '#ops');
|
||||
|
||||
expect(channel.isHashChannel, isTrue);
|
||||
expect(channel.pskBase64, 'O2RN43fDLHh5NgWiWqkVvw==');
|
||||
expect(
|
||||
Channel.pskBase64ForHashChannelName('#ops'),
|
||||
'O2RN43fDLHh5NgWiWqkVvw==',
|
||||
);
|
||||
});
|
||||
|
||||
test('normal channels reject derived hashtag psk export helper', () {
|
||||
expect(
|
||||
() => Channel.pskBase64ForHashChannelName('ops'),
|
||||
throwsArgumentError,
|
||||
);
|
||||
});
|
||||
|
||||
test('normal channels still expose their stored psk_base64', () {
|
||||
final channel = Channel.create(
|
||||
index: 4,
|
||||
name: 'ops',
|
||||
explicitSecret: Uint8List.fromList(List<int>.generate(16, (i) => i)),
|
||||
);
|
||||
|
||||
expect(channel.isHashChannel, isFalse);
|
||||
expect(channel.pskBase64, 'AAECAwQFBgcICQoLDA0ODw==');
|
||||
});
|
||||
}
|
||||
@@ -1,22 +1,80 @@
|
||||
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/channel.dart';
|
||||
import 'package:meshcore_sar_app/models/contact.dart';
|
||||
import 'package:meshcore_sar_app/models/contact_group.dart';
|
||||
import 'package:meshcore_sar_app/models/device_info.dart' as device_info;
|
||||
import 'package:meshcore_sar_app/providers/app_provider.dart';
|
||||
import 'package:meshcore_sar_app/providers/channels_provider.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/drawing_provider.dart';
|
||||
import 'package:meshcore_sar_app/providers/image_provider.dart'
|
||||
as image_provider;
|
||||
import 'package:meshcore_sar_app/providers/map_provider.dart';
|
||||
import 'package:meshcore_sar_app/providers/messages_provider.dart';
|
||||
import 'package:meshcore_sar_app/providers/voice_provider.dart';
|
||||
import 'package:meshcore_sar_app/screens/contacts_tab.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/contact_grouping.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;
|
||||
|
||||
@override
|
||||
device_info.DeviceInfo get deviceInfo => device_info.DeviceInfo(
|
||||
connectionState: _isConnected
|
||||
? device_info.ConnectionState.connected
|
||||
: device_info.ConnectionState.disconnected,
|
||||
);
|
||||
}
|
||||
|
||||
class _FakeMessagesProvider extends MessagesProvider {
|
||||
@override
|
||||
bool get isInitialized => true;
|
||||
}
|
||||
|
||||
class _FakeDrawingProvider extends DrawingProvider {
|
||||
@override
|
||||
bool get isInitialized => true;
|
||||
}
|
||||
|
||||
void main() {
|
||||
String? clipboardText;
|
||||
|
||||
setUp(() {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
ProfileStorageScope.setScope(
|
||||
profilesEnabled: false,
|
||||
activeProfileId: 'default',
|
||||
);
|
||||
clipboardText = null;
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(SystemChannels.platform, (call) async {
|
||||
switch (call.method) {
|
||||
case 'Clipboard.setData':
|
||||
clipboardText =
|
||||
(call.arguments as Map<dynamic, dynamic>)['text'] as String?;
|
||||
return null;
|
||||
case 'Clipboard.getData':
|
||||
return <String, dynamic>{'text': clipboardText};
|
||||
}
|
||||
return null;
|
||||
});
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(SystemChannels.platform, null);
|
||||
});
|
||||
|
||||
Contact buildChannel({required String name, required int channelIndex}) {
|
||||
@@ -80,8 +138,28 @@ void main() {
|
||||
WidgetTester tester, {
|
||||
List<Contact> contacts = const [],
|
||||
List<SavedContactGroup> savedGroups = const [],
|
||||
ConnectionProvider? connectionProvider,
|
||||
}) async {
|
||||
final contactsProvider = ContactsProvider();
|
||||
final resolvedConnectionProvider =
|
||||
connectionProvider ?? ConnectionProvider();
|
||||
final messagesProvider = _FakeMessagesProvider();
|
||||
final drawingProvider = _FakeDrawingProvider();
|
||||
final channelsProvider = ChannelsProvider();
|
||||
final voiceProvider = VoiceProvider(
|
||||
codec: VoiceCodecService(),
|
||||
player: VoicePlayerService(),
|
||||
);
|
||||
final imageProvider = image_provider.ImageProvider();
|
||||
final appProvider = AppProvider(
|
||||
connectionProvider: resolvedConnectionProvider,
|
||||
contactsProvider: contactsProvider,
|
||||
messagesProvider: messagesProvider,
|
||||
drawingProvider: drawingProvider,
|
||||
channelsProvider: channelsProvider,
|
||||
voiceProvider: voiceProvider,
|
||||
imageProvider: imageProvider,
|
||||
);
|
||||
for (final contact in contacts) {
|
||||
contactsProvider.addOrUpdateContact(contact);
|
||||
}
|
||||
@@ -95,10 +173,17 @@ void main() {
|
||||
await tester.pumpWidget(
|
||||
MultiProvider(
|
||||
providers: [
|
||||
ChangeNotifierProvider.value(value: contactsProvider),
|
||||
ChangeNotifierProvider(create: (_) => ConnectionProvider()),
|
||||
ChangeNotifierProvider(create: (_) => MessagesProvider()),
|
||||
ChangeNotifierProvider<ContactsProvider>(
|
||||
create: (_) => contactsProvider,
|
||||
),
|
||||
ChangeNotifierProvider<ConnectionProvider>(
|
||||
create: (_) => resolvedConnectionProvider,
|
||||
),
|
||||
ChangeNotifierProvider<MessagesProvider>(
|
||||
create: (_) => messagesProvider,
|
||||
),
|
||||
ChangeNotifierProvider(create: (_) => MapProvider()),
|
||||
ChangeNotifierProvider<AppProvider>(create: (_) => appProvider),
|
||||
],
|
||||
child: MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
@@ -123,6 +208,7 @@ void main() {
|
||||
await tester.tap(find.text('Ops'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('Export psk_base64'), findsNothing);
|
||||
expect(find.text('Delete Channel'), findsOneWidget);
|
||||
|
||||
await tester.tap(find.text('Delete Channel'));
|
||||
@@ -137,6 +223,26 @@ void main() {
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('hash channel activity card exports psk_base64', (tester) async {
|
||||
await pumpContactsTab(
|
||||
tester,
|
||||
contacts: [buildChannel(name: '#ops', channelIndex: 3)],
|
||||
);
|
||||
|
||||
expect(find.text('#ops'), findsOneWidget);
|
||||
await tester.tap(find.text('#ops'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('Export psk_base64'), findsOneWidget);
|
||||
|
||||
await tester.tap(find.text('Export psk_base64'));
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(milliseconds: 300));
|
||||
|
||||
expect(clipboardText, Channel.pskBase64ForHashChannelName('#ops'));
|
||||
expect(find.text('psk_base64 copied to clipboard'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('repeaters show Others group when multiple groups exist', (
|
||||
tester,
|
||||
) async {
|
||||
@@ -218,7 +324,25 @@ void main() {
|
||||
contacts: [buildSensor(seed: 60, name: 'WX Station')],
|
||||
);
|
||||
|
||||
expect(find.text('Sensors'), findsOneWidget);
|
||||
expect(find.text('Sensors'), findsWidgets);
|
||||
expect(find.text('WX Station'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'contacts sections do not show sensor or repeater discovery actions',
|
||||
(tester) async {
|
||||
await pumpContactsTab(
|
||||
tester,
|
||||
contacts: [
|
||||
buildRepeater(seed: 70, name: 'Relay 1'),
|
||||
buildSensor(seed: 71, name: 'WX Station'),
|
||||
],
|
||||
connectionProvider: _FakeConnectionProvider(isConnected: true),
|
||||
);
|
||||
|
||||
expect(find.byTooltip('Discover repeaters'), findsNothing);
|
||||
expect(find.byTooltip('Discover sensors'), findsNothing);
|
||||
expect(find.byIcon(Icons.radar), findsNothing);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import 'dart:typed_data';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_sar_app/models/ble_packet_log.dart';
|
||||
import 'package:meshcore_sar_app/l10n/app_localizations.dart';
|
||||
import 'package:meshcore_sar_app/screens/live_traffic_screen.dart';
|
||||
|
||||
BlePacketLog _log({
|
||||
@@ -50,6 +51,14 @@ List<int> _multiHopRaw({
|
||||
];
|
||||
}
|
||||
|
||||
Widget _testApp(Widget child) {
|
||||
return MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: child,
|
||||
);
|
||||
}
|
||||
|
||||
void main() {
|
||||
testWidgets('shows empty state before traffic arrives', (tester) async {
|
||||
final logs = <BlePacketLog>[];
|
||||
@@ -57,8 +66,8 @@ void main() {
|
||||
DateTime now = DateTime(2026, 3, 12, 12, 0, 0);
|
||||
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: LiveTrafficScreen(
|
||||
_testApp(
|
||||
LiveTrafficScreen(
|
||||
logReader: () => logs,
|
||||
refreshListenable: refresh,
|
||||
now: () => now,
|
||||
@@ -78,10 +87,9 @@ void main() {
|
||||
DateTime now = DateTime(2026, 3, 12, 12, 0, 0);
|
||||
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: LiveTrafficScreen(
|
||||
_testApp(
|
||||
LiveTrafficScreen(
|
||||
logReader: () => logs,
|
||||
rxCountReader: () => 7,
|
||||
refreshListenable: refresh,
|
||||
now: () => now,
|
||||
),
|
||||
@@ -114,10 +122,9 @@ void main() {
|
||||
await tester.pump();
|
||||
|
||||
expect(find.text('1 pkt/min'), findsOneWidget);
|
||||
expect(find.text('Device total 7'), findsOneWidget);
|
||||
expect(find.text('Device total 1'), findsOneWidget);
|
||||
expect(find.text('FLOOD RESPONSE'), findsOneWidget);
|
||||
expect(find.text('MULTI-HOP'), findsOneWidget);
|
||||
expect(find.textContaining('RSSI -84 dBm'), findsOneWidget);
|
||||
expect(find.text('-84 dBm'), findsOneWidget);
|
||||
expect(find.textContaining('Hash:'), findsOneWidget);
|
||||
expect(
|
||||
find.textContaining('Path: 3 hops [c010,6301,68d9]'),
|
||||
@@ -143,8 +150,8 @@ void main() {
|
||||
);
|
||||
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: LiveTrafficScreen(
|
||||
_testApp(
|
||||
LiveTrafficScreen(
|
||||
logReader: () => logs,
|
||||
refreshListenable: refresh,
|
||||
now: () => now,
|
||||
@@ -152,7 +159,7 @@ void main() {
|
||||
),
|
||||
);
|
||||
|
||||
expect(find.text('MULTI-HOP'), findsOneWidget);
|
||||
expect(find.text('FLOOD RESPONSE'), findsOneWidget);
|
||||
|
||||
await tester.tap(find.byTooltip('Clear live view'));
|
||||
await tester.pump();
|
||||
@@ -182,4 +189,43 @@ void main() {
|
||||
expect(find.text('No packets for this filter'), findsNothing);
|
||||
expect(find.textContaining('Size: 3 bytes'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('summary metrics expand across wide layouts', (tester) async {
|
||||
tester.view.physicalSize = const Size(1200, 900);
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.reset);
|
||||
|
||||
final now = DateTime(2026, 3, 12, 12, 0, 0);
|
||||
final logs = [
|
||||
_log(
|
||||
timestamp: now.subtract(const Duration(seconds: 10)),
|
||||
direction: PacketDirection.rx,
|
||||
rawData: _multiHopRaw(hops: [0xC0, 0x10, 0x63, 0x01]),
|
||||
responseCode: 0x88,
|
||||
snrDb: 9.5,
|
||||
rssiDbm: -82,
|
||||
),
|
||||
];
|
||||
|
||||
await tester.pumpWidget(
|
||||
_testApp(LiveTrafficScreen(logReader: () => logs, now: () => now)),
|
||||
);
|
||||
|
||||
expect(
|
||||
tester
|
||||
.getSize(
|
||||
find.byKey(const ValueKey('liveTrafficMetric:rxPackets')),
|
||||
)
|
||||
.width >
|
||||
200,
|
||||
isTrue,
|
||||
);
|
||||
expect(
|
||||
tester
|
||||
.getSize(find.byKey(const ValueKey('liveTrafficMetric:multihop')))
|
||||
.width >
|
||||
200,
|
||||
isTrue,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -146,23 +146,55 @@ void main() {
|
||||
test('supports clearing the live view without mutating source logs', () {
|
||||
final now = DateTime(2026, 3, 12, 12, 0, 0);
|
||||
final clearAt = now.subtract(const Duration(seconds: 8));
|
||||
final snapshot = LiveTrafficSummary.fromLogs([
|
||||
_log(
|
||||
timestamp: now.subtract(const Duration(seconds: 10)),
|
||||
direction: PacketDirection.rx,
|
||||
rawData: [0x88, 0x00, 0x00],
|
||||
responseCode: 0x88,
|
||||
),
|
||||
_log(
|
||||
timestamp: now.subtract(const Duration(seconds: 4)),
|
||||
direction: PacketDirection.rx,
|
||||
rawData: [0x88, 0x00, 0x00],
|
||||
responseCode: 0x88,
|
||||
),
|
||||
], now: now, clearedAt: clearAt);
|
||||
final snapshot = LiveTrafficSummary.fromLogs(
|
||||
[
|
||||
_log(
|
||||
timestamp: now.subtract(const Duration(seconds: 10)),
|
||||
direction: PacketDirection.rx,
|
||||
rawData: [0x88, 0x00, 0x00],
|
||||
responseCode: 0x88,
|
||||
),
|
||||
_log(
|
||||
timestamp: now.subtract(const Duration(seconds: 4)),
|
||||
direction: PacketDirection.rx,
|
||||
rawData: [0x88, 0x00, 0x00],
|
||||
responseCode: 0x88,
|
||||
),
|
||||
],
|
||||
now: now,
|
||||
clearedAt: clearAt,
|
||||
);
|
||||
|
||||
expect(snapshot.totalCount, 1);
|
||||
expect(snapshot.visibleEntries, hasLength(1));
|
||||
});
|
||||
|
||||
test('counts only RX data packets for device totals', () {
|
||||
final now = DateTime(2026, 3, 12, 12, 0, 0);
|
||||
|
||||
expect(
|
||||
LiveTrafficSummary.countRxDataLogs([
|
||||
_log(
|
||||
timestamp: now.subtract(const Duration(seconds: 30)),
|
||||
direction: PacketDirection.rx,
|
||||
rawData: [0x88, 0x00, 0x00],
|
||||
responseCode: 0x88,
|
||||
),
|
||||
_log(
|
||||
timestamp: now.subtract(const Duration(seconds: 20)),
|
||||
direction: PacketDirection.tx,
|
||||
rawData: [0x88, 0x00, 0x00],
|
||||
responseCode: 0x88,
|
||||
),
|
||||
_log(
|
||||
timestamp: now.subtract(const Duration(seconds: 10)),
|
||||
direction: PacketDirection.rx,
|
||||
rawData: [0x05, 0x01, 0x02],
|
||||
responseCode: 0x05,
|
||||
),
|
||||
]),
|
||||
1,
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -10,40 +10,28 @@ void main() {
|
||||
setUp(() {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
ProfileStorageScope.setScope(
|
||||
profilesEnabled: false,
|
||||
profilesEnabled: true,
|
||||
activeProfileId: ConfigProfile.defaultProfileId,
|
||||
);
|
||||
});
|
||||
|
||||
group('ProfileManager', () {
|
||||
test(
|
||||
'hides the built-in default profile until profiles are enabled',
|
||||
() async {
|
||||
final manager = ProfileManager();
|
||||
test('shows the built-in default profile on a fresh install', () async {
|
||||
final manager = ProfileManager();
|
||||
|
||||
await manager.initialize();
|
||||
await manager.initialize();
|
||||
|
||||
expect(manager.activeProfileId, ConfigProfile.defaultProfileId);
|
||||
expect(manager.visibleProfiles, isEmpty);
|
||||
expect(
|
||||
manager.getProfile(ConfigProfile.defaultProfileId)?.isDefault,
|
||||
isTrue,
|
||||
);
|
||||
expect(ProfileStorageScope.profilesEnabled, isFalse);
|
||||
expect(ProfileStorageScope.effectiveNamespace, isNull);
|
||||
|
||||
await manager.setProfilesEnabled(true);
|
||||
|
||||
expect(manager.visibleProfiles, hasLength(1));
|
||||
expect(
|
||||
manager.visibleProfiles.single.id,
|
||||
ConfigProfile.defaultProfileId,
|
||||
);
|
||||
expect(manager.visibleProfiles.single.name, 'Default');
|
||||
expect(ProfileStorageScope.profilesEnabled, isTrue);
|
||||
expect(ProfileStorageScope.effectiveNamespace, isNull);
|
||||
},
|
||||
);
|
||||
expect(manager.activeProfileId, ConfigProfile.defaultProfileId);
|
||||
expect(manager.visibleProfiles, hasLength(1));
|
||||
expect(
|
||||
manager.getProfile(ConfigProfile.defaultProfileId)?.isDefault,
|
||||
isTrue,
|
||||
);
|
||||
expect(ProfileStorageScope.profilesEnabled, isTrue);
|
||||
expect(ProfileStorageScope.effectiveNamespace, isNull);
|
||||
expect(manager.visibleProfiles.single.name, 'Default');
|
||||
expect(ProfileStorageScope.effectiveNamespace, isNull);
|
||||
});
|
||||
|
||||
test(
|
||||
'persists custom profiles and restores scoped active profile state',
|
||||
@@ -82,5 +70,44 @@ void main() {
|
||||
expect(reloaded.activeProfileId, profile.id);
|
||||
},
|
||||
);
|
||||
|
||||
test('stores per-device default profiles independently', () async {
|
||||
final manager = ProfileManager();
|
||||
await manager.initialize();
|
||||
await manager.setProfilesEnabled(true);
|
||||
|
||||
final profile = ConfigProfile(
|
||||
id: 'profile-alpha',
|
||||
name: 'Alpha',
|
||||
createdAt: DateTime.parse('2026-03-16T12:00:00Z'),
|
||||
updatedAt: DateTime.parse('2026-03-16T12:00:00Z'),
|
||||
sections: const ConfigProfileSections(),
|
||||
);
|
||||
|
||||
await manager.upsertProfile(profile);
|
||||
await manager.setActiveProfileIdForDevice(
|
||||
profile.id,
|
||||
deviceKey: 'pk:device-a',
|
||||
);
|
||||
await manager.setActiveProfileIdForDevice(
|
||||
ConfigProfile.defaultProfileId,
|
||||
deviceKey: 'pk:device-b',
|
||||
);
|
||||
|
||||
final reloaded = ProfileManager();
|
||||
await reloaded.initialize();
|
||||
|
||||
expect(reloaded.profileIdForDevice('pk:device-a'), profile.id);
|
||||
expect(
|
||||
reloaded.profileIdForDevice('pk:device-b'),
|
||||
ConfigProfile.defaultProfileId,
|
||||
);
|
||||
expect(
|
||||
reloaded.profileIdForDevice('pk:device-c'),
|
||||
ConfigProfile.defaultProfileId,
|
||||
);
|
||||
expect(reloaded.hasProfileForDevice('pk:device-a'), isTrue);
|
||||
expect(reloaded.hasProfileForDevice('pk:device-c'), isFalse);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -184,6 +184,73 @@ void main() {
|
||||
expect(manager.activeProfileId, target.id);
|
||||
},
|
||||
);
|
||||
|
||||
test('syncActiveProfileForCurrentDevice uses per-device default', () async {
|
||||
final manager = ProfileManager();
|
||||
await manager.initialize();
|
||||
await manager.setProfilesEnabled(true);
|
||||
|
||||
final alpha = ConfigProfile(
|
||||
id: 'profile-alpha',
|
||||
name: 'Alpha',
|
||||
createdAt: DateTime.parse('2026-03-16T12:00:00Z'),
|
||||
updatedAt: DateTime.parse('2026-03-16T12:00:00Z'),
|
||||
sections: const ConfigProfileSections(),
|
||||
);
|
||||
await manager.upsertProfile(alpha);
|
||||
await manager.setActiveProfileIdForDevice(
|
||||
alpha.id,
|
||||
deviceKey: 'pk:01020304',
|
||||
);
|
||||
await manager.setActiveProfileId(ConfigProfile.defaultProfileId);
|
||||
|
||||
final connectionProvider = _FakeConnectionProvider(
|
||||
deviceInfo: DeviceInfo(publicKey: Uint8List.fromList([1, 2, 3, 4])),
|
||||
);
|
||||
final coordinator = _buildCoordinator(
|
||||
profileManager: manager,
|
||||
connectionProvider: connectionProvider,
|
||||
);
|
||||
|
||||
await coordinator.syncActiveProfileForCurrentDevice();
|
||||
|
||||
expect(manager.activeProfileId, alpha.id);
|
||||
expect(connectionProvider.disconnectCallCount, 0);
|
||||
});
|
||||
|
||||
test(
|
||||
'syncActiveProfileForCurrentDevice creates a profile for a new device',
|
||||
() async {
|
||||
final manager = ProfileManager();
|
||||
await manager.initialize();
|
||||
await manager.setProfilesEnabled(true);
|
||||
|
||||
final connectionProvider = _FakeConnectionProvider(
|
||||
deviceInfo: DeviceInfo(
|
||||
deviceId: 'ble-77',
|
||||
deviceName: 'MeshCore-Field Unit',
|
||||
selfName: 'Field Unit',
|
||||
publicKey: Uint8List.fromList([7, 7, 7, 7]),
|
||||
),
|
||||
);
|
||||
final coordinator = _buildCoordinator(
|
||||
profileManager: manager,
|
||||
connectionProvider: connectionProvider,
|
||||
);
|
||||
|
||||
await coordinator.syncActiveProfileForCurrentDevice();
|
||||
|
||||
expect(manager.activeProfileId, isNot(ConfigProfile.defaultProfileId));
|
||||
final profile = manager.getProfile(manager.activeProfileId);
|
||||
expect(profile, isNotNull);
|
||||
expect(profile!.name, 'Device Field Unit');
|
||||
expect(manager.hasProfileForDevice('pk:07070707'), isTrue);
|
||||
expect(
|
||||
manager.profileIdForDevice('pk:07070707'),
|
||||
manager.activeProfileId,
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -265,10 +332,17 @@ class _FakeDeviceConfigApplicator extends DeviceConfigApplicator {
|
||||
}
|
||||
|
||||
class _FakeConnectionProvider implements ConnectionProvider {
|
||||
_FakeConnectionProvider({
|
||||
DeviceInfo? deviceInfo,
|
||||
}) : deviceInfo = deviceInfo ?? DeviceInfo();
|
||||
|
||||
int disconnectCallCount = 0;
|
||||
|
||||
@override
|
||||
DeviceInfo get deviceInfo => DeviceInfo();
|
||||
final DeviceInfo deviceInfo;
|
||||
|
||||
@override
|
||||
ConnectionMode get connectionMode => ConnectionMode.ble;
|
||||
|
||||
@override
|
||||
Future<void> disconnect() async {
|
||||
|
||||
25
test/utils/link_quality_test.dart
Normal file
25
test/utils/link_quality_test.dart
Normal file
@@ -0,0 +1,25 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_sar_app/utils/link_quality.dart';
|
||||
|
||||
void main() {
|
||||
group('linkQualityLabel', () {
|
||||
test('classifies SNR-only values without forcing them to weak', () {
|
||||
expect(linkQualityLabel(null, 12.0), 'Excellent');
|
||||
expect(linkQualityLabel(null, 6.0), 'Good');
|
||||
expect(linkQualityLabel(null, 1.0), 'Fair');
|
||||
expect(linkQualityLabel(null, -6.0), 'Weak');
|
||||
});
|
||||
|
||||
test('classifies RSSI-only values using direct thresholds', () {
|
||||
expect(linkQualityLabel(-58, null), 'Excellent');
|
||||
expect(linkQualityLabel(-68, null), 'Good');
|
||||
expect(linkQualityLabel(-78, null), 'Fair');
|
||||
expect(linkQualityLabel(-92, null), 'Weak');
|
||||
});
|
||||
|
||||
test('averages mixed metrics when both are available', () {
|
||||
expect(linkQualityLabel(-72, 11.0), 'Good');
|
||||
expect(linkQualityLabel(-85, 7.0), 'Fair');
|
||||
});
|
||||
});
|
||||
}
|
||||
36
test/widgets/compass_math_test.dart
Normal file
36
test/widgets/compass_math_test.dart
Normal file
@@ -0,0 +1,36 @@
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_sar_app/widgets/map/compass/compass_math.dart';
|
||||
|
||||
void main() {
|
||||
group('compass dial math', () {
|
||||
test('rotates the rose opposite the heading', () {
|
||||
expect(compassRoseRotationRadians(0), closeTo(0, 1e-10));
|
||||
expect(compassRoseRotationRadians(90), closeTo(-pi / 2, 1e-10));
|
||||
expect(compassRoseRotationRadians(450), closeTo(-pi / 2, 1e-10));
|
||||
});
|
||||
|
||||
test('places east at the top when heading east', () {
|
||||
expect(
|
||||
compassDialAngleRadians(markerDegrees: 90, headingDegrees: 90),
|
||||
closeTo(-pi / 2, 1e-10),
|
||||
);
|
||||
expect(
|
||||
compassDialAngleRadians(markerDegrees: 270, headingDegrees: 90),
|
||||
closeTo(pi / 2, 1e-10),
|
||||
);
|
||||
});
|
||||
|
||||
test('places west at the top when heading west', () {
|
||||
expect(
|
||||
compassDialAngleRadians(markerDegrees: 270, headingDegrees: 270),
|
||||
closeTo(-pi / 2, 1e-10),
|
||||
);
|
||||
expect(
|
||||
compassDialAngleRadians(markerDegrees: 90, headingDegrees: 270),
|
||||
closeTo(pi / 2, 1e-10),
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -164,18 +164,16 @@ void main() {
|
||||
expect(find.text('CO2'), findsOneWidget);
|
||||
expect(find.text('415 ppm'), findsOneWidget);
|
||||
expect(find.text('Illuminance'), findsOneWidget);
|
||||
expect(find.text('~4.2 W/m2 daylight'), findsOneWidget);
|
||||
expect(find.text('~4.2 W/m2'), findsOneWidget);
|
||||
expect(find.textContaining('lx'), findsNothing);
|
||||
expect(find.text('Current'), findsOneWidget);
|
||||
expect(find.text('15 mA'), findsOneWidget);
|
||||
expect(find.text('Power'), findsOneWidget);
|
||||
expect(find.text('Distance'), findsOneWidget);
|
||||
expect(
|
||||
find.byKey(const ValueKey('sensor_metric_channel_battery')),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(find.byKey(const ValueKey('sensor_metric_battery')), findsOneWidget);
|
||||
expect(find.text('ch1'), findsWidgets);
|
||||
expect(
|
||||
find.byKey(const ValueKey('sensor_metric_channel_extra:illuminance_2')),
|
||||
find.byKey(const ValueKey('sensor_metric_extra:illuminance_2')),
|
||||
findsOneWidget,
|
||||
);
|
||||
|
||||
|
||||
244
test/widgets/message_bubble_test.dart
Normal file
244
test/widgets/message_bubble_test.dart
Normal file
@@ -0,0 +1,244 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter/gestures.dart';
|
||||
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/message.dart';
|
||||
import 'package:meshcore_sar_app/providers/app_provider.dart';
|
||||
import 'package:meshcore_sar_app/providers/channels_provider.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/drawing_provider.dart';
|
||||
import 'package:meshcore_sar_app/providers/image_provider.dart' as ip;
|
||||
import 'package:meshcore_sar_app/providers/messages_provider.dart';
|
||||
import 'package:meshcore_sar_app/providers/voice_provider.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/widgets/messages/message_bubble.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
setUp(() {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
});
|
||||
|
||||
testWidgets('received bubbles show signal chips on double tap', (
|
||||
tester,
|
||||
) async {
|
||||
final harness = await _TestHarness.create();
|
||||
try {
|
||||
final message = Message(
|
||||
id: 'received-signal',
|
||||
messageType: MessageType.contact,
|
||||
senderPublicKeyPrefix: _prefix(1),
|
||||
pathLen: 1,
|
||||
textType: MessageTextType.plain,
|
||||
senderTimestamp: 1700000000,
|
||||
text: 'Inbound message',
|
||||
receivedAt: DateTime.fromMillisecondsSinceEpoch(1700000000500),
|
||||
deliveryStatus: MessageDeliveryStatus.received,
|
||||
lastEchoRssiDbm: -84,
|
||||
lastEchoSnrRaw: 24,
|
||||
);
|
||||
|
||||
await tester.pumpWidget(_buildApp(harness, message));
|
||||
await tester.pump(const Duration(milliseconds: 60));
|
||||
|
||||
expect(find.text('1 hop'), findsNothing);
|
||||
expect(find.text('Fair'), findsNothing);
|
||||
expect(find.text('-84'), findsNothing);
|
||||
expect(find.text('6.0'), findsNothing);
|
||||
|
||||
await tester.tap(find.text('Inbound message'));
|
||||
await tester.pump(kDoubleTapTimeout);
|
||||
|
||||
expect(find.text('1 hop'), findsNothing);
|
||||
expect(find.text('-84'), findsNothing);
|
||||
|
||||
await _doubleTap(tester, find.text('Inbound message'));
|
||||
|
||||
expect(find.text('1 hop'), findsOneWidget);
|
||||
expect(find.text('Fair'), findsOneWidget);
|
||||
expect(find.text('-84'), findsOneWidget);
|
||||
expect(find.text('6.0'), findsOneWidget);
|
||||
} finally {
|
||||
await _disposeHarness(tester, harness);
|
||||
}
|
||||
});
|
||||
|
||||
testWidgets('delivered direct bubbles show timing chips on double tap', (
|
||||
tester,
|
||||
) async {
|
||||
final harness = await _TestHarness.create();
|
||||
try {
|
||||
final message = Message(
|
||||
id: 'sent-direct-signal',
|
||||
messageType: MessageType.contact,
|
||||
senderPublicKeyPrefix: _prefix(11),
|
||||
recipientPublicKey: _key(77),
|
||||
pathLen: 0,
|
||||
textType: MessageTextType.plain,
|
||||
senderTimestamp: 1700000000,
|
||||
text: 'Outbound message',
|
||||
receivedAt: DateTime.fromMillisecondsSinceEpoch(1700000000500),
|
||||
deliveryStatus: MessageDeliveryStatus.delivered,
|
||||
roundTripTimeMs: 320,
|
||||
);
|
||||
|
||||
await tester.pumpWidget(_buildApp(harness, message));
|
||||
await tester.pump(const Duration(milliseconds: 60));
|
||||
|
||||
expect(find.text('Direct'), findsNothing);
|
||||
expect(find.text('320ms'), findsNothing);
|
||||
|
||||
await tester.tap(find.text('Outbound message'));
|
||||
await tester.pump(kDoubleTapTimeout);
|
||||
|
||||
expect(find.text('Direct'), findsNothing);
|
||||
expect(find.text('320ms'), findsNothing);
|
||||
|
||||
await _doubleTap(tester, find.text('Outbound message'));
|
||||
|
||||
expect(find.text('Direct'), findsOneWidget);
|
||||
expect(find.text('320ms'), findsOneWidget);
|
||||
} finally {
|
||||
await _disposeHarness(tester, harness);
|
||||
}
|
||||
});
|
||||
|
||||
testWidgets('sent channel bubbles show echo chips on double tap', (
|
||||
tester,
|
||||
) async {
|
||||
final harness = await _TestHarness.create();
|
||||
try {
|
||||
final message = Message(
|
||||
id: 'sent-channel-signal',
|
||||
messageType: MessageType.channel,
|
||||
senderPublicKeyPrefix: _prefix(21),
|
||||
channelIdx: 0,
|
||||
pathLen: 0,
|
||||
textType: MessageTextType.plain,
|
||||
senderTimestamp: 1700000000,
|
||||
text: 'Broadcast message',
|
||||
receivedAt: DateTime.fromMillisecondsSinceEpoch(1700000000500),
|
||||
deliveryStatus: MessageDeliveryStatus.sent,
|
||||
echoCount: 2,
|
||||
lastEchoRssiDbm: -76,
|
||||
lastEchoSnrRaw: 20,
|
||||
);
|
||||
|
||||
await tester.pumpWidget(_buildApp(harness, message));
|
||||
await tester.pump(const Duration(milliseconds: 60));
|
||||
|
||||
expect(find.text('x2'), findsNothing);
|
||||
expect(find.text('-76'), findsNothing);
|
||||
expect(find.text('5.0'), findsNothing);
|
||||
|
||||
await tester.tap(find.text('Broadcast message'));
|
||||
await tester.pump(kDoubleTapTimeout);
|
||||
|
||||
expect(find.text('x2'), findsNothing);
|
||||
expect(find.text('-76'), findsNothing);
|
||||
|
||||
await _doubleTap(tester, find.text('Broadcast message'));
|
||||
|
||||
expect(find.text('x2'), findsOneWidget);
|
||||
expect(find.text('-76'), findsOneWidget);
|
||||
expect(find.text('5.0'), findsOneWidget);
|
||||
} finally {
|
||||
await _disposeHarness(tester, harness);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Widget _buildApp(_TestHarness harness, Message message) {
|
||||
return MultiProvider(
|
||||
providers: [
|
||||
ChangeNotifierProvider.value(value: harness.connectionProvider),
|
||||
ChangeNotifierProvider.value(value: harness.contactsProvider),
|
||||
ChangeNotifierProvider.value(value: harness.messagesProvider),
|
||||
ChangeNotifierProvider.value(value: harness.drawingProvider),
|
||||
ChangeNotifierProvider.value(value: harness.channelsProvider),
|
||||
ChangeNotifierProvider.value(value: harness.voiceProvider),
|
||||
ChangeNotifierProvider.value(value: harness.imageProvider),
|
||||
ChangeNotifierProvider.value(value: harness.appProvider),
|
||||
],
|
||||
child: MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: Scaffold(body: MessageBubble(message: message)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class _TestHarness {
|
||||
final connectionProvider = ConnectionProvider();
|
||||
final contactsProvider = ContactsProvider();
|
||||
final messagesProvider = MessagesProvider();
|
||||
final drawingProvider = DrawingProvider();
|
||||
final channelsProvider = ChannelsProvider()..initializePublicChannel();
|
||||
final voiceProvider = VoiceProvider(
|
||||
codec: VoiceCodecService(),
|
||||
player: VoicePlayerService(),
|
||||
);
|
||||
final imageProvider = ip.ImageProvider();
|
||||
|
||||
late final AppProvider appProvider;
|
||||
|
||||
static Future<_TestHarness> create() async {
|
||||
final harness = _TestHarness();
|
||||
await harness.messagesProvider.initialize();
|
||||
await harness.drawingProvider.initialize();
|
||||
harness.appProvider = AppProvider(
|
||||
connectionProvider: harness.connectionProvider,
|
||||
contactsProvider: harness.contactsProvider,
|
||||
messagesProvider: harness.messagesProvider,
|
||||
drawingProvider: harness.drawingProvider,
|
||||
channelsProvider: harness.channelsProvider,
|
||||
voiceProvider: harness.voiceProvider,
|
||||
imageProvider: harness.imageProvider,
|
||||
);
|
||||
return harness;
|
||||
}
|
||||
|
||||
bool _isDisposed = false;
|
||||
|
||||
void dispose() {
|
||||
if (_isDisposed) {
|
||||
return;
|
||||
}
|
||||
_isDisposed = true;
|
||||
appProvider.dispose();
|
||||
voiceProvider.dispose();
|
||||
imageProvider.dispose();
|
||||
drawingProvider.dispose();
|
||||
messagesProvider.dispose();
|
||||
contactsProvider.dispose();
|
||||
connectionProvider.dispose();
|
||||
channelsProvider.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
Uint8List _prefix(int seed) =>
|
||||
Uint8List.fromList(List<int>.generate(6, (index) => seed + index));
|
||||
|
||||
Uint8List _key(int seed) =>
|
||||
Uint8List.fromList(List<int>.generate(32, (index) => seed + index));
|
||||
|
||||
Future<void> _disposeHarness(WidgetTester tester, _TestHarness harness) async {
|
||||
await tester.pump(kDoubleTapTimeout);
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
harness.dispose();
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
Future<void> _doubleTap(WidgetTester tester, Finder finder) async {
|
||||
await tester.tap(finder);
|
||||
await tester.pump(kDoubleTapMinTime);
|
||||
await tester.tap(finder);
|
||||
await tester.pump();
|
||||
}
|
||||
@@ -11,6 +11,8 @@ void main() {
|
||||
required String name,
|
||||
required ContactType type,
|
||||
int secondByte = 0,
|
||||
int flags = 0,
|
||||
int lastAdvert = 0,
|
||||
}) {
|
||||
final publicKey = Uint8List(32);
|
||||
publicKey[1] = secondByte;
|
||||
@@ -18,11 +20,11 @@ void main() {
|
||||
return Contact(
|
||||
publicKey: publicKey,
|
||||
type: type,
|
||||
flags: 0,
|
||||
flags: flags,
|
||||
outPathLen: 0,
|
||||
outPath: Uint8List(0),
|
||||
advName: name,
|
||||
lastAdvert: 0,
|
||||
lastAdvert: lastAdvert,
|
||||
advLat: 0,
|
||||
advLon: 0,
|
||||
lastMod: 0,
|
||||
@@ -98,4 +100,54 @@ void main() {
|
||||
expect(find.text('Show all'), findsNothing);
|
||||
expect(find.text('John Smith'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('sorts contacts with favourites first, then last seen', (
|
||||
tester,
|
||||
) async {
|
||||
final recentNonFavourite = buildContact(
|
||||
name: 'Alpha',
|
||||
type: ContactType.chat,
|
||||
secondByte: 1,
|
||||
lastAdvert: 300,
|
||||
);
|
||||
final olderFavourite = buildContact(
|
||||
name: 'Bravo',
|
||||
type: ContactType.chat,
|
||||
secondByte: 2,
|
||||
flags: 0x01,
|
||||
lastAdvert: 100,
|
||||
);
|
||||
final newerFavourite = buildContact(
|
||||
name: 'Charlie',
|
||||
type: ContactType.chat,
|
||||
secondByte: 3,
|
||||
flags: 0x01,
|
||||
lastAdvert: 200,
|
||||
);
|
||||
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: Scaffold(
|
||||
body: RecipientSelectorSheet(
|
||||
contacts: [recentNonFavourite, olderFavourite, newerFavourite],
|
||||
rooms: const [],
|
||||
channels: const [],
|
||||
unreadCount: 0,
|
||||
unreadCountsByPublicKey: const {},
|
||||
showAllOption: false,
|
||||
onSelect: (selectedRecipient, draftMessage) {},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
final charlieY = tester.getTopLeft(find.text('Charlie')).dy;
|
||||
final bravoY = tester.getTopLeft(find.text('Bravo')).dy;
|
||||
final alphaY = tester.getTopLeft(find.text('Alpha')).dy;
|
||||
|
||||
expect(charlieY, lessThan(bravoY));
|
||||
expect(bravoY, lessThan(alphaY));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
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/screens/sensors_tab.dart';
|
||||
import 'package:meshcore_sar_app/widgets/sensors/sensor_telemetry_card.dart';
|
||||
|
||||
@@ -7,6 +8,8 @@ void main() {
|
||||
testWidgets('renders selector previews and channel badges', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: Scaffold(
|
||||
body: SensorMetricSelectorItem(
|
||||
option: const SensorMetricOption(
|
||||
@@ -14,12 +17,12 @@ void main() {
|
||||
label: 'Illuminance (ch 2)',
|
||||
defaultLabel: 'Illuminance',
|
||||
channel: 2,
|
||||
valuePreview: '500 lx',
|
||||
valuePreview: '~4.2 W/m2',
|
||||
previewCardData: SensorMetricCardData(
|
||||
fieldKey: 'extra:illuminance_2',
|
||||
icon: Icons.light_mode_outlined,
|
||||
label: 'Illuminance',
|
||||
value: '500 lx',
|
||||
value: '~4.2 W/m2',
|
||||
accent: Color(0xFFC17B1D),
|
||||
channel: 2,
|
||||
),
|
||||
@@ -39,7 +42,8 @@ void main() {
|
||||
);
|
||||
|
||||
expect(find.text('Show on sensor card'), findsOneWidget);
|
||||
expect(find.text('500 lx'), findsOneWidget);
|
||||
expect(find.text('~4.2 W/m2'), findsOneWidget);
|
||||
expect(find.textContaining('lx'), findsNothing);
|
||||
expect(
|
||||
find.byKey(const ValueKey('sensor_selector_channel_extra:illuminance_2')),
|
||||
findsOneWidget,
|
||||
@@ -50,6 +54,8 @@ void main() {
|
||||
testWidgets('omits duplicate channel chip for channel 1', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: Scaffold(
|
||||
body: SensorMetricSelectorItem(
|
||||
option: const SensorMetricOption(
|
||||
|
||||
@@ -63,12 +63,14 @@ void main() {
|
||||
expect(find.text('Light'), findsOneWidget);
|
||||
expect(find.text('Temperature'), findsNothing);
|
||||
expect(find.text('Illuminance'), findsNothing);
|
||||
expect(find.text('~4.2 W/m2'), findsOneWidget);
|
||||
expect(find.textContaining('lx'), findsNothing);
|
||||
expect(
|
||||
find.byKey(const ValueKey('sensor_metric_channel_temperature')),
|
||||
find.byKey(const ValueKey('sensor_metric_temperature')),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(
|
||||
find.byKey(const ValueKey('sensor_metric_channel_extra:illuminance_2')),
|
||||
find.byKey(const ValueKey('sensor_metric_extra:illuminance_2')),
|
||||
findsOneWidget,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
#include <file_selector_windows/file_selector_windows.h>
|
||||
#include <flutter_avif_windows/flutter_avif_windows_plugin.h>
|
||||
#include <flutter_blue_plus_winrt/flutter_blue_plus_plugin.h>
|
||||
#include <flutter_libserialport/flutter_libserialport_plugin.h>
|
||||
#include <geolocator_windows/geolocator_windows.h>
|
||||
#include <nsd_windows/nsd_windows_plugin_c_api.h>
|
||||
#include <permission_handler_windows/permission_handler_windows_plugin.h>
|
||||
@@ -26,6 +27,8 @@ void RegisterPlugins(flutter::PluginRegistry* registry) {
|
||||
registry->GetRegistrarForPlugin("FlutterAvifWindowsPlugin"));
|
||||
FlutterBluePlusPluginRegisterWithRegistrar(
|
||||
registry->GetRegistrarForPlugin("FlutterBluePlusPlugin"));
|
||||
FlutterLibserialportPluginRegisterWithRegistrar(
|
||||
registry->GetRegistrarForPlugin("FlutterLibserialportPlugin"));
|
||||
GeolocatorWindowsRegisterWithRegistrar(
|
||||
registry->GetRegistrarForPlugin("GeolocatorWindows"));
|
||||
NsdWindowsPluginCApiRegisterWithRegistrar(
|
||||
|
||||
@@ -7,6 +7,7 @@ list(APPEND FLUTTER_PLUGIN_LIST
|
||||
file_selector_windows
|
||||
flutter_avif_windows
|
||||
flutter_blue_plus_winrt
|
||||
flutter_libserialport
|
||||
geolocator_windows
|
||||
nsd_windows
|
||||
permission_handler_windows
|
||||
|
||||
Reference in New Issue
Block a user