mirror of
https://github.com/dz0ny/meshcore-sar.git
synced 2026-08-11 16:30:28 +00:00
Compare commits
24 Commits
v2026.0317
...
v2026.0321
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9279ff2158 | ||
|
|
dc297b0b9f | ||
|
|
2d24481aba | ||
|
|
20a1df94eb | ||
|
|
5cc81bef65 | ||
|
|
6145462555 | ||
|
|
721fb7e7a2 | ||
|
|
5a58e45e13 | ||
|
|
de4258c0a4 | ||
|
|
d8cb35c595 | ||
|
|
8da69705ee | ||
|
|
e474168ba8 | ||
|
|
03dba8b3ce | ||
|
|
bc9e37bd22 | ||
|
|
a32d5d2c85 | ||
|
|
e683ab933f | ||
|
|
f286b0afd1 | ||
|
|
68ec72534d | ||
|
|
6af8b62d9b | ||
|
|
01fbb7de6c | ||
|
|
9303d24b69 | ||
|
|
140088fe2f | ||
|
|
67d8e1c906 | ||
|
|
29b75a3155 |
21
.github/workflows/build-artifacts.yml
vendored
21
.github/workflows/build-artifacts.yml
vendored
@@ -40,6 +40,9 @@ jobs:
|
|||||||
flutter-version: ${{ env.FLUTTER_VERSION }}
|
flutter-version: ${{ env.FLUTTER_VERSION }}
|
||||||
channel: stable
|
channel: stable
|
||||||
cache: true
|
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
|
- name: Cache Android NDK
|
||||||
uses: actions/cache@v4
|
uses: actions/cache@v4
|
||||||
@@ -95,6 +98,9 @@ jobs:
|
|||||||
flutter-version: ${{ env.FLUTTER_VERSION }}
|
flutter-version: ${{ env.FLUTTER_VERSION }}
|
||||||
channel: stable
|
channel: stable
|
||||||
cache: true
|
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
|
- name: Enable Linux desktop
|
||||||
run: flutter config --enable-linux-desktop
|
run: flutter config --enable-linux-desktop
|
||||||
@@ -132,6 +138,9 @@ jobs:
|
|||||||
flutter-version: ${{ env.FLUTTER_VERSION }}
|
flutter-version: ${{ env.FLUTTER_VERSION }}
|
||||||
channel: stable
|
channel: stable
|
||||||
cache: true
|
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
|
- name: Enable Windows desktop
|
||||||
shell: pwsh
|
shell: pwsh
|
||||||
@@ -174,6 +183,9 @@ jobs:
|
|||||||
flutter-version: ${{ env.FLUTTER_VERSION }}
|
flutter-version: ${{ env.FLUTTER_VERSION }}
|
||||||
channel: stable
|
channel: stable
|
||||||
cache: true
|
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
|
- name: Enable macOS desktop
|
||||||
run: flutter config --enable-macos-desktop
|
run: flutter config --enable-macos-desktop
|
||||||
@@ -181,6 +193,9 @@ jobs:
|
|||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: flutter pub get
|
run: flutter pub get
|
||||||
|
|
||||||
|
- name: Install macOS native build tools
|
||||||
|
run: brew install automake libtool
|
||||||
|
|
||||||
- name: Build macOS release
|
- name: Build macOS release
|
||||||
run: flutter build macos --release
|
run: flutter build macos --release
|
||||||
|
|
||||||
@@ -216,6 +231,9 @@ jobs:
|
|||||||
flutter-version: ${{ env.FLUTTER_VERSION }}
|
flutter-version: ${{ env.FLUTTER_VERSION }}
|
||||||
channel: stable
|
channel: stable
|
||||||
cache: true
|
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
|
- name: Install dependencies
|
||||||
run: flutter pub get
|
run: flutter pub get
|
||||||
@@ -272,6 +290,9 @@ jobs:
|
|||||||
flutter-version: ${{ env.FLUTTER_VERSION }}
|
flutter-version: ${{ env.FLUTTER_VERSION }}
|
||||||
channel: stable
|
channel: stable
|
||||||
cache: true
|
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
|
- name: Enable web
|
||||||
run: flutter config --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 }}
|
flutter-version: ${{ env.FLUTTER_VERSION }}
|
||||||
channel: 'stable'
|
channel: 'stable'
|
||||||
cache: true
|
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
|
- name: Install dependencies
|
||||||
run: flutter pub get
|
run: flutter pub get
|
||||||
|
|||||||
@@ -489,7 +489,7 @@
|
|||||||
buildSettings = {
|
buildSettings = {
|
||||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||||
CLANG_ENABLE_MODULES = YES;
|
CLANG_ENABLE_MODULES = YES;
|
||||||
CURRENT_PROJECT_VERSION = 119;
|
CURRENT_PROJECT_VERSION = 123;
|
||||||
DEVELOPMENT_TEAM = JND55328G8;
|
DEVELOPMENT_TEAM = JND55328G8;
|
||||||
ENABLE_BITCODE = NO;
|
ENABLE_BITCODE = NO;
|
||||||
INFOPLIST_FILE = Runner/Info.plist;
|
INFOPLIST_FILE = Runner/Info.plist;
|
||||||
@@ -511,7 +511,7 @@
|
|||||||
buildSettings = {
|
buildSettings = {
|
||||||
BUNDLE_LOADER = "$(TEST_HOST)";
|
BUNDLE_LOADER = "$(TEST_HOST)";
|
||||||
CODE_SIGN_STYLE = Automatic;
|
CODE_SIGN_STYLE = Automatic;
|
||||||
CURRENT_PROJECT_VERSION = 119;
|
CURRENT_PROJECT_VERSION = 123;
|
||||||
DEVELOPMENT_TEAM = JND55328G8;
|
DEVELOPMENT_TEAM = JND55328G8;
|
||||||
GENERATE_INFOPLIST_FILE = YES;
|
GENERATE_INFOPLIST_FILE = YES;
|
||||||
MARKETING_VERSION = 1.0;
|
MARKETING_VERSION = 1.0;
|
||||||
@@ -530,7 +530,7 @@
|
|||||||
buildSettings = {
|
buildSettings = {
|
||||||
BUNDLE_LOADER = "$(TEST_HOST)";
|
BUNDLE_LOADER = "$(TEST_HOST)";
|
||||||
CODE_SIGN_STYLE = Automatic;
|
CODE_SIGN_STYLE = Automatic;
|
||||||
CURRENT_PROJECT_VERSION = 119;
|
CURRENT_PROJECT_VERSION = 123;
|
||||||
DEVELOPMENT_TEAM = JND55328G8;
|
DEVELOPMENT_TEAM = JND55328G8;
|
||||||
GENERATE_INFOPLIST_FILE = YES;
|
GENERATE_INFOPLIST_FILE = YES;
|
||||||
MARKETING_VERSION = 1.0;
|
MARKETING_VERSION = 1.0;
|
||||||
@@ -547,7 +547,7 @@
|
|||||||
buildSettings = {
|
buildSettings = {
|
||||||
BUNDLE_LOADER = "$(TEST_HOST)";
|
BUNDLE_LOADER = "$(TEST_HOST)";
|
||||||
CODE_SIGN_STYLE = Automatic;
|
CODE_SIGN_STYLE = Automatic;
|
||||||
CURRENT_PROJECT_VERSION = 119;
|
CURRENT_PROJECT_VERSION = 123;
|
||||||
DEVELOPMENT_TEAM = JND55328G8;
|
DEVELOPMENT_TEAM = JND55328G8;
|
||||||
GENERATE_INFOPLIST_FILE = YES;
|
GENERATE_INFOPLIST_FILE = YES;
|
||||||
MARKETING_VERSION = 1.0;
|
MARKETING_VERSION = 1.0;
|
||||||
@@ -679,7 +679,7 @@
|
|||||||
buildSettings = {
|
buildSettings = {
|
||||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||||
CLANG_ENABLE_MODULES = YES;
|
CLANG_ENABLE_MODULES = YES;
|
||||||
CURRENT_PROJECT_VERSION = 119;
|
CURRENT_PROJECT_VERSION = 123;
|
||||||
DEVELOPMENT_TEAM = JND55328G8;
|
DEVELOPMENT_TEAM = JND55328G8;
|
||||||
ENABLE_BITCODE = NO;
|
ENABLE_BITCODE = NO;
|
||||||
INFOPLIST_FILE = Runner/Info.plist;
|
INFOPLIST_FILE = Runner/Info.plist;
|
||||||
@@ -702,7 +702,7 @@
|
|||||||
buildSettings = {
|
buildSettings = {
|
||||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||||
CLANG_ENABLE_MODULES = YES;
|
CLANG_ENABLE_MODULES = YES;
|
||||||
CURRENT_PROJECT_VERSION = 119;
|
CURRENT_PROJECT_VERSION = 123;
|
||||||
DEVELOPMENT_TEAM = JND55328G8;
|
DEVELOPMENT_TEAM = JND55328G8;
|
||||||
ENABLE_BITCODE = NO;
|
ENABLE_BITCODE = NO;
|
||||||
INFOPLIST_FILE = Runner/Info.plist;
|
INFOPLIST_FILE = Runner/Info.plist;
|
||||||
|
|||||||
@@ -43,7 +43,7 @@
|
|||||||
<key>CFBundleSignature</key>
|
<key>CFBundleSignature</key>
|
||||||
<string>????</string>
|
<string>????</string>
|
||||||
<key>CFBundleVersion</key>
|
<key>CFBundleVersion</key>
|
||||||
<string>119</string>
|
<string>123</string>
|
||||||
<key>LSRequiresIPhoneOS</key>
|
<key>LSRequiresIPhoneOS</key>
|
||||||
<true/>
|
<true/>
|
||||||
<key>ITSAppUsesNonExemptEncryption</key>
|
<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.000217">
|
||||||
|
|
||||||
</testcase>
|
</testcase>
|
||||||
|
|
||||||
|
|
||||||
<testcase classname="fastlane.lanes" name="1: increment_build_number" time="0.554978">
|
<testcase classname="fastlane.lanes" name="1: increment_build_number" time="0.503497">
|
||||||
|
|
||||||
</testcase>
|
</testcase>
|
||||||
|
|
||||||
|
|
||||||
<testcase classname="fastlane.lanes" name="2: build_app" time="100.17557">
|
<testcase classname="fastlane.lanes" name="2: build_app" time="103.12875">
|
||||||
|
|
||||||
</testcase>
|
</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="58490.472877">
|
||||||
|
|
||||||
</testcase>
|
</testcase>
|
||||||
|
|
||||||
|
|||||||
@@ -372,6 +372,8 @@ class _MeshCoreSarAppState extends State<MeshCoreSarApp> {
|
|||||||
mapProvider: mapProvider,
|
mapProvider: mapProvider,
|
||||||
drawingProvider: context.read<DrawingProvider>(),
|
drawingProvider: context.read<DrawingProvider>(),
|
||||||
channelsProvider: context.read<ChannelsProvider>(),
|
channelsProvider: context.read<ChannelsProvider>(),
|
||||||
|
voiceProvider: context.read<VoiceProvider>(),
|
||||||
|
imageProvider: context.read<ip.ImageProvider>(),
|
||||||
appProvider: appProvider,
|
appProvider: appProvider,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -57,9 +57,7 @@ class Channel {
|
|||||||
} else {
|
} else {
|
||||||
// Normal channel: require explicit secret
|
// Normal channel: require explicit secret
|
||||||
if (explicitSecret == null || explicitSecret.length != 16) {
|
if (explicitSecret == null || explicitSecret.length != 16) {
|
||||||
throw ArgumentError(
|
throw ArgumentError('Normal channels require a 16-byte secret');
|
||||||
'Normal channels require a 16-byte secret',
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
return Channel(
|
return Channel(
|
||||||
index: index,
|
index: index,
|
||||||
@@ -78,6 +76,18 @@ class Channel {
|
|||||||
return Uint8List.fromList(digest.bytes.sublist(0, 16));
|
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)
|
/// Create the default public channel (channel 0)
|
||||||
/// Uses the well-known pre-shared key from MeshCore
|
/// Uses the well-known pre-shared key from MeshCore
|
||||||
factory Channel.publicChannel() {
|
factory Channel.publicChannel() {
|
||||||
@@ -85,8 +95,22 @@ class Channel {
|
|||||||
index: 0,
|
index: 0,
|
||||||
name: 'Public Channel',
|
name: 'Public Channel',
|
||||||
secret: Uint8List.fromList([
|
secret: Uint8List.fromList([
|
||||||
0x8b, 0x33, 0x87, 0xe9, 0xc5, 0xcd, 0xea, 0x6a,
|
0x8b,
|
||||||
0xc9, 0xe5, 0xed, 0xba, 0xa1, 0x15, 0xcd, 0x72,
|
0x33,
|
||||||
|
0x87,
|
||||||
|
0xe9,
|
||||||
|
0xc5,
|
||||||
|
0xcd,
|
||||||
|
0xea,
|
||||||
|
0x6a,
|
||||||
|
0xc9,
|
||||||
|
0xe5,
|
||||||
|
0xed,
|
||||||
|
0xba,
|
||||||
|
0xa1,
|
||||||
|
0x15,
|
||||||
|
0xcd,
|
||||||
|
0x72,
|
||||||
]),
|
]),
|
||||||
flags: null,
|
flags: null,
|
||||||
);
|
);
|
||||||
@@ -95,6 +119,9 @@ class Channel {
|
|||||||
/// Check if this is a hash-based channel (name starts with '#')
|
/// Check if this is a hash-based channel (name starts with '#')
|
||||||
bool get isHashChannel => name.startsWith('#');
|
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
|
/// Display name for the channel
|
||||||
/// Returns "Public" for channel 0, otherwise returns the custom name or "Channel N"
|
/// Returns "Public" for channel 0, otherwise returns the custom name or "Channel N"
|
||||||
String get displayName {
|
String get displayName {
|
||||||
@@ -131,12 +158,7 @@ class Channel {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Create a copy with modified fields
|
/// Create a copy with modified fields
|
||||||
Channel copyWith({
|
Channel copyWith({int? index, String? name, Uint8List? secret, int? flags}) {
|
||||||
int? index,
|
|
||||||
String? name,
|
|
||||||
Uint8List? secret,
|
|
||||||
int? flags,
|
|
||||||
}) {
|
|
||||||
return Channel(
|
return Channel(
|
||||||
index: index ?? this.index,
|
index: index ?? this.index,
|
||||||
name: name ?? this.name,
|
name: name ?? this.name,
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ extension ConnectionModeExtension on ConnectionMode {
|
|||||||
case ConnectionMode.tcp:
|
case ConnectionMode.tcp:
|
||||||
return 'Direct (WiFi)';
|
return 'Direct (WiFi)';
|
||||||
case ConnectionMode.usb:
|
case ConnectionMode.usb:
|
||||||
return 'Direct (USB)';
|
return 'Direct (Serial)';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -40,7 +40,7 @@ extension ConnectionModeExtension on ConnectionMode {
|
|||||||
case ConnectionMode.tcp:
|
case ConnectionMode.tcp:
|
||||||
return 'Direct WiFi/TCP connection to MeshCore device';
|
return 'Direct WiFi/TCP connection to MeshCore device';
|
||||||
case ConnectionMode.usb:
|
case ConnectionMode.usb:
|
||||||
return 'USB serial connection to MeshCore device';
|
return 'Direct serial connection to MeshCore device';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -71,6 +71,7 @@ class DeviceInfo {
|
|||||||
final bool? autoAddRoomServers;
|
final bool? autoAddRoomServers;
|
||||||
final bool? autoAddSensors;
|
final bool? autoAddSensors;
|
||||||
final bool? autoAddOverwriteOldest;
|
final bool? autoAddOverwriteOldest;
|
||||||
|
final int? autoAddMaxHops;
|
||||||
final int? radioFreq;
|
final int? radioFreq;
|
||||||
final int? radioBw;
|
final int? radioBw;
|
||||||
final int? radioSf;
|
final int? radioSf;
|
||||||
@@ -95,6 +96,7 @@ class DeviceInfo {
|
|||||||
|
|
||||||
// Repeat mode (firmware v9+)
|
// Repeat mode (firmware v9+)
|
||||||
final bool? clientRepeat;
|
final bool? clientRepeat;
|
||||||
|
final int? pathHashMode;
|
||||||
final bool? supportsSpectrumScan;
|
final bool? supportsSpectrumScan;
|
||||||
final int? spectrumScanMinKhz;
|
final int? spectrumScanMinKhz;
|
||||||
final int? spectrumScanMaxKhz;
|
final int? spectrumScanMaxKhz;
|
||||||
@@ -123,6 +125,7 @@ class DeviceInfo {
|
|||||||
this.autoAddRoomServers,
|
this.autoAddRoomServers,
|
||||||
this.autoAddSensors,
|
this.autoAddSensors,
|
||||||
this.autoAddOverwriteOldest,
|
this.autoAddOverwriteOldest,
|
||||||
|
this.autoAddMaxHops,
|
||||||
this.radioFreq,
|
this.radioFreq,
|
||||||
this.radioBw,
|
this.radioBw,
|
||||||
this.radioSf,
|
this.radioSf,
|
||||||
@@ -139,6 +142,7 @@ class DeviceInfo {
|
|||||||
this.manufacturerModel,
|
this.manufacturerModel,
|
||||||
this.semanticVersion,
|
this.semanticVersion,
|
||||||
this.clientRepeat,
|
this.clientRepeat,
|
||||||
|
this.pathHashMode,
|
||||||
this.supportsSpectrumScan,
|
this.supportsSpectrumScan,
|
||||||
this.spectrumScanMinKhz,
|
this.spectrumScanMinKhz,
|
||||||
this.spectrumScanMaxKhz,
|
this.spectrumScanMaxKhz,
|
||||||
@@ -254,6 +258,7 @@ class DeviceInfo {
|
|||||||
bool? autoAddRoomServers,
|
bool? autoAddRoomServers,
|
||||||
bool? autoAddSensors,
|
bool? autoAddSensors,
|
||||||
bool? autoAddOverwriteOldest,
|
bool? autoAddOverwriteOldest,
|
||||||
|
int? autoAddMaxHops,
|
||||||
int? radioFreq,
|
int? radioFreq,
|
||||||
int? radioBw,
|
int? radioBw,
|
||||||
int? radioSf,
|
int? radioSf,
|
||||||
@@ -270,6 +275,7 @@ class DeviceInfo {
|
|||||||
String? manufacturerModel,
|
String? manufacturerModel,
|
||||||
String? semanticVersion,
|
String? semanticVersion,
|
||||||
bool? clientRepeat,
|
bool? clientRepeat,
|
||||||
|
int? pathHashMode,
|
||||||
bool? supportsSpectrumScan,
|
bool? supportsSpectrumScan,
|
||||||
int? spectrumScanMinKhz,
|
int? spectrumScanMinKhz,
|
||||||
int? spectrumScanMaxKhz,
|
int? spectrumScanMaxKhz,
|
||||||
@@ -299,6 +305,7 @@ class DeviceInfo {
|
|||||||
autoAddSensors: autoAddSensors ?? this.autoAddSensors,
|
autoAddSensors: autoAddSensors ?? this.autoAddSensors,
|
||||||
autoAddOverwriteOldest:
|
autoAddOverwriteOldest:
|
||||||
autoAddOverwriteOldest ?? this.autoAddOverwriteOldest,
|
autoAddOverwriteOldest ?? this.autoAddOverwriteOldest,
|
||||||
|
autoAddMaxHops: autoAddMaxHops ?? this.autoAddMaxHops,
|
||||||
radioFreq: radioFreq ?? this.radioFreq,
|
radioFreq: radioFreq ?? this.radioFreq,
|
||||||
radioBw: radioBw ?? this.radioBw,
|
radioBw: radioBw ?? this.radioBw,
|
||||||
radioSf: radioSf ?? this.radioSf,
|
radioSf: radioSf ?? this.radioSf,
|
||||||
@@ -315,6 +322,7 @@ class DeviceInfo {
|
|||||||
manufacturerModel: manufacturerModel ?? this.manufacturerModel,
|
manufacturerModel: manufacturerModel ?? this.manufacturerModel,
|
||||||
semanticVersion: semanticVersion ?? this.semanticVersion,
|
semanticVersion: semanticVersion ?? this.semanticVersion,
|
||||||
clientRepeat: clientRepeat ?? this.clientRepeat,
|
clientRepeat: clientRepeat ?? this.clientRepeat,
|
||||||
|
pathHashMode: pathHashMode ?? this.pathHashMode,
|
||||||
supportsSpectrumScan: supportsSpectrumScan ?? this.supportsSpectrumScan,
|
supportsSpectrumScan: supportsSpectrumScan ?? this.supportsSpectrumScan,
|
||||||
spectrumScanMinKhz: spectrumScanMinKhz ?? this.spectrumScanMinKhz,
|
spectrumScanMinKhz: spectrumScanMinKhz ?? this.spectrumScanMinKhz,
|
||||||
spectrumScanMaxKhz: spectrumScanMaxKhz ?? this.spectrumScanMaxKhz,
|
spectrumScanMaxKhz: spectrumScanMaxKhz ?? this.spectrumScanMaxKhz,
|
||||||
|
|||||||
@@ -107,6 +107,15 @@ class _PendingRepeaterOwnerRequest {
|
|||||||
const _PendingRepeaterOwnerRequest({required this.publicKey});
|
const _PendingRepeaterOwnerRequest({required this.publicKey});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
enum ContactsTabSection {
|
||||||
|
favourites,
|
||||||
|
teamMembers,
|
||||||
|
repeaters,
|
||||||
|
sensors,
|
||||||
|
rooms,
|
||||||
|
channels,
|
||||||
|
}
|
||||||
|
|
||||||
/// Main App Provider - coordinates all other providers
|
/// Main App Provider - coordinates all other providers
|
||||||
class AppProvider with ChangeNotifier {
|
class AppProvider with ChangeNotifier {
|
||||||
static const int _maxDirectPayloadHops = 3;
|
static const int _maxDirectPayloadHops = 3;
|
||||||
@@ -162,6 +171,9 @@ class AppProvider with ChangeNotifier {
|
|||||||
bool get isContactsEnabled => _isContactsEnabled;
|
bool get isContactsEnabled => _isContactsEnabled;
|
||||||
bool _isSensorsEnabled = true;
|
bool _isSensorsEnabled = true;
|
||||||
bool get isSensorsEnabled => _isSensorsEnabled;
|
bool get isSensorsEnabled => _isSensorsEnabled;
|
||||||
|
final Map<ContactsTabSection, bool> _contactsSectionVisibility = {
|
||||||
|
for (final section in ContactsTabSection.values) section: true,
|
||||||
|
};
|
||||||
|
|
||||||
bool _isVoiceSilenceTrimmingEnabled = true;
|
bool _isVoiceSilenceTrimmingEnabled = true;
|
||||||
bool get isVoiceSilenceTrimmingEnabled => _isVoiceSilenceTrimmingEnabled;
|
bool get isVoiceSilenceTrimmingEnabled => _isVoiceSilenceTrimmingEnabled;
|
||||||
@@ -238,6 +250,7 @@ class AppProvider with ChangeNotifier {
|
|||||||
_initializeLocationTracking();
|
_initializeLocationTracking();
|
||||||
_loadMapEnabled();
|
_loadMapEnabled();
|
||||||
_loadContactsEnabled();
|
_loadContactsEnabled();
|
||||||
|
_loadContactsSectionVisibility();
|
||||||
_loadSensorsEnabled();
|
_loadSensorsEnabled();
|
||||||
_loadVoiceSilenceTrimmingEnabled();
|
_loadVoiceSilenceTrimmingEnabled();
|
||||||
_loadVoiceBandPassFilterEnabled();
|
_loadVoiceBandPassFilterEnabled();
|
||||||
@@ -259,6 +272,27 @@ class AppProvider with ChangeNotifier {
|
|||||||
return ProfileStorageScope.scopedKey(baseKey);
|
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() {
|
void _startPacketCapturePersistence() {
|
||||||
_packetCaptureFlushTimer?.cancel();
|
_packetCaptureFlushTimer?.cancel();
|
||||||
_packetCaptureFlushTimer = Timer.periodic(const Duration(seconds: 2), (_) {
|
_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
|
/// Load sensors enabled setting from shared preferences
|
||||||
Future<void> _loadSensorsEnabled() async {
|
Future<void> _loadSensorsEnabled() async {
|
||||||
try {
|
try {
|
||||||
@@ -933,9 +998,7 @@ class AppProvider with ChangeNotifier {
|
|||||||
// we also import into firmware so subsequent getContact calls work.
|
// we also import into firmware so subsequent getContact calls work.
|
||||||
// Matches the official app which calls cmdGetAdvertPath for all adverts.
|
// Matches the official app which calls cmdGetAdvertPath for all adverts.
|
||||||
if (source == ContactReceiveSource.advert) {
|
if (source == ContactReceiveSource.advert) {
|
||||||
unawaited(
|
unawaited(connectionProvider.importReceivedAdvert(contact.publicKey));
|
||||||
connectionProvider.importReceivedAdvert(contact.publicKey),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
final isNewPendingAdvert = contactsProvider
|
final isNewPendingAdvert = contactsProvider
|
||||||
.addOrUpdatePendingAdvertContact(
|
.addOrUpdatePendingAdvertContact(
|
||||||
@@ -1134,16 +1197,31 @@ class AppProvider with ChangeNotifier {
|
|||||||
return;
|
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;
|
Message enrichedMessage = message;
|
||||||
Contact? senderContact;
|
Contact? senderContact;
|
||||||
if (message.senderPublicKeyPrefix != null && message.senderName == null) {
|
if (message.senderName == null) {
|
||||||
final contact = contactsProvider.findContactByKey(
|
// Try room post author first (the actual person who posted)
|
||||||
message.senderPublicKeyPrefix!,
|
if (message.roomPostAuthorPrefix != null) {
|
||||||
);
|
final author = contactsProvider.findContactByPrefix(
|
||||||
if (contact != null) {
|
message.roomPostAuthorPrefix!,
|
||||||
senderContact = contact;
|
);
|
||||||
enrichedMessage = message.copyWith(senderName: contact.advName);
|
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
|
senderContact ??= message.senderPublicKeyPrefix != null
|
||||||
@@ -1337,12 +1415,13 @@ class AppProvider with ChangeNotifier {
|
|||||||
if (_handlePendingRepeaterOwnerResponse(tag, responseData)) {
|
if (_handlePendingRepeaterOwnerResponse(tag, responseData)) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
debugPrint(
|
debugPrint('📊 [AppProvider] Binary response (0x8C tag=$tag) received');
|
||||||
'📊 [AppProvider] Binary response (0x8C) received - updating contact telemetry',
|
// Binary responses carry Cayenne LPP telemetry data.
|
||||||
);
|
// The data starts with a channel byte — valid LPP always has at least
|
||||||
// Binary response tag 0 = telemetry data (Cayenne LPP format)
|
// 3 bytes (channel + type + value). Skip clearly non-telemetry payloads.
|
||||||
// Other tags may be used for different data types in the future
|
if (responseData.length >= 3) {
|
||||||
contactsProvider.updateTelemetry(publicKeyPrefix, responseData);
|
contactsProvider.updateTelemetry(publicKeyPrefix, responseData);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// When raw binary data is received (PUSH_CODE_RAW_DATA 0x84)
|
// 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.
|
// already added to pending adverts and showed notification.
|
||||||
// Nothing else to do — the callback pipeline handles everything.
|
// Nothing else to do — the callback pipeline handles everything.
|
||||||
if (wasKnown) {
|
if (wasKnown) {
|
||||||
debugPrint(
|
debugPrint(' [pushAdvert] Existing contact refreshed');
|
||||||
' [pushAdvert] Existing contact refreshed',
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2476,12 +2553,10 @@ class AppProvider with ChangeNotifier {
|
|||||||
try {
|
try {
|
||||||
_isReconnectSyncInProgress = true;
|
_isReconnectSyncInProgress = true;
|
||||||
_hasCompletedConnectionBootstrap = false;
|
_hasCompletedConnectionBootstrap = false;
|
||||||
// Initialize contacts provider with device public key to exclude self
|
await contactsProvider.prepareForDeviceContactSync(
|
||||||
// If already initialized (from early load), this will just filter out self-contact
|
|
||||||
// This must happen before getContacts to ensure proper filtering
|
|
||||||
await contactsProvider.initialize(
|
|
||||||
devicePublicKey: connectionProvider.deviceInfo.publicKey,
|
devicePublicKey: connectionProvider.deviceInfo.publicKey,
|
||||||
);
|
);
|
||||||
|
channelsProvider.prepareForDeviceSync();
|
||||||
|
|
||||||
// Note: Device clock is automatically synced during connection in MeshCoreBleService
|
// Note: Device clock is automatically synced during connection in MeshCoreBleService
|
||||||
// No need to sync it again here
|
// No need to sync it again here
|
||||||
@@ -2557,10 +2632,14 @@ class AppProvider with ChangeNotifier {
|
|||||||
'🔄 [AppProvider] Device reconnected - syncing contacts and missed messages',
|
'🔄 [AppProvider] Device reconnected - syncing contacts and missed messages',
|
||||||
);
|
);
|
||||||
|
|
||||||
await contactsProvider.initialize(
|
await contactsProvider.prepareForDeviceContactSync(
|
||||||
devicePublicKey: connectionProvider.deviceInfo.publicKey,
|
devicePublicKey: connectionProvider.deviceInfo.publicKey,
|
||||||
);
|
);
|
||||||
|
channelsProvider.prepareForDeviceSync();
|
||||||
await connectionProvider.getContacts();
|
await connectionProvider.getContacts();
|
||||||
|
await connectionProvider.syncChannels(
|
||||||
|
maxChannels: connectionProvider.deviceInfo.maxChannels,
|
||||||
|
);
|
||||||
|
|
||||||
final messageCount = await connectionProvider.syncAllMessages(
|
final messageCount = await connectionProvider.syncAllMessages(
|
||||||
force: true,
|
force: true,
|
||||||
@@ -2703,6 +2782,7 @@ class AppProvider with ChangeNotifier {
|
|||||||
await Future.wait([
|
await Future.wait([
|
||||||
_loadMapEnabled(),
|
_loadMapEnabled(),
|
||||||
_loadContactsEnabled(),
|
_loadContactsEnabled(),
|
||||||
|
_loadContactsSectionVisibility(),
|
||||||
_loadSensorsEnabled(),
|
_loadSensorsEnabled(),
|
||||||
_loadVoiceSilenceTrimmingEnabled(),
|
_loadVoiceSilenceTrimmingEnabled(),
|
||||||
_loadVoiceBandPassFilterEnabled(),
|
_loadVoiceBandPassFilterEnabled(),
|
||||||
@@ -3564,6 +3644,7 @@ class AppProvider with ChangeNotifier {
|
|||||||
await connectionProvider.getContacts();
|
await connectionProvider.getContacts();
|
||||||
|
|
||||||
// Sync all channels so refresh reflects the full device state.
|
// Sync all channels so refresh reflects the full device state.
|
||||||
|
channelsProvider.prepareForDeviceSync();
|
||||||
await connectionProvider.syncChannels(
|
await connectionProvider.syncChannels(
|
||||||
maxChannels: connectionProvider.deviceInfo.maxChannels,
|
maxChannels: connectionProvider.deviceInfo.maxChannels,
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -7,7 +7,8 @@ class ChannelsProvider with ChangeNotifier {
|
|||||||
int _selectedChannelIndex = 0; // Default to public channel
|
int _selectedChannelIndex = 0; // Default to public channel
|
||||||
|
|
||||||
/// Get all channels
|
/// Get all channels
|
||||||
List<Channel> get channels => _channels.values.toList()..sort((a, b) => a.index.compareTo(b.index));
|
List<Channel> get channels =>
|
||||||
|
_channels.values.toList()..sort((a, b) => a.index.compareTo(b.index));
|
||||||
|
|
||||||
/// Get a specific channel by index
|
/// Get a specific channel by index
|
||||||
Channel? getChannel(int index) => _channels[index];
|
Channel? getChannel(int index) => _channels[index];
|
||||||
@@ -54,12 +55,12 @@ class ChannelsProvider with ChangeNotifier {
|
|||||||
void removeChannel(int index) {
|
void removeChannel(int index) {
|
||||||
if (_channels.containsKey(index)) {
|
if (_channels.containsKey(index)) {
|
||||||
_channels.remove(index);
|
_channels.remove(index);
|
||||||
|
|
||||||
// If the deleted channel was selected, switch to public channel
|
// If the deleted channel was selected, switch to public channel
|
||||||
if (_selectedChannelIndex == index) {
|
if (_selectedChannelIndex == index) {
|
||||||
_selectedChannelIndex = 0;
|
_selectedChannelIndex = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -96,6 +97,13 @@ class ChannelsProvider with ChangeNotifier {
|
|||||||
notifyListeners();
|
notifyListeners();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Clear runtime channel state before a live device sync begins.
|
||||||
|
void prepareForDeviceSync() {
|
||||||
|
_channels.clear();
|
||||||
|
_selectedChannelIndex = 0;
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
/// Check if channels have been loaded
|
/// Check if channels have been loaded
|
||||||
bool get hasChannels => _channels.isNotEmpty;
|
bool get hasChannels => _channels.isNotEmpty;
|
||||||
|
|
||||||
|
|||||||
@@ -73,6 +73,7 @@ class ConnectionProvider with ChangeNotifier {
|
|||||||
final MeshCoreBleService _bleService = MeshCoreBleService();
|
final MeshCoreBleService _bleService = MeshCoreBleService();
|
||||||
MeshCoreTcpService? _tcpService;
|
MeshCoreTcpService? _tcpService;
|
||||||
MeshCoreSerialService? _serialService;
|
MeshCoreSerialService? _serialService;
|
||||||
|
Future<void> Function()? _serialDisconnectTransport;
|
||||||
|
|
||||||
/// Expose BLE service for background location tracking
|
/// Expose BLE service for background location tracking
|
||||||
MeshCoreBleService get bleService => _bleService;
|
MeshCoreBleService get bleService => _bleService;
|
||||||
@@ -224,6 +225,87 @@ class ConnectionProvider with ChangeNotifier {
|
|||||||
_wireServiceCallbacks(_bleService);
|
_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].
|
/// Wire all shared event callbacks onto [service].
|
||||||
/// Called for both BLE and TCP services so the provider handles events
|
/// Called for both BLE and TCP services so the provider handles events
|
||||||
/// identically regardless of transport.
|
/// identically regardless of transport.
|
||||||
@@ -465,6 +547,7 @@ class ConnectionProvider with ChangeNotifier {
|
|||||||
manufacturerModel: deviceInfo['manufacturerModel'] as String?,
|
manufacturerModel: deviceInfo['manufacturerModel'] as String?,
|
||||||
semanticVersion: deviceInfo['semanticVersion'] as String?,
|
semanticVersion: deviceInfo['semanticVersion'] as String?,
|
||||||
clientRepeat: deviceInfo['clientRepeat'] as bool?,
|
clientRepeat: deviceInfo['clientRepeat'] as bool?,
|
||||||
|
pathHashMode: deviceInfo['pathHashMode'] as int?,
|
||||||
supportsSpectrumScan: deviceInfo['supportsSpectrumScan'] as bool?,
|
supportsSpectrumScan: deviceInfo['supportsSpectrumScan'] as bool?,
|
||||||
spectrumScanMinKhz: deviceInfo['spectrumScanMinKhz'] as int?,
|
spectrumScanMinKhz: deviceInfo['spectrumScanMinKhz'] as int?,
|
||||||
spectrumScanMaxKhz: deviceInfo['spectrumScanMaxKhz'] as int?,
|
spectrumScanMaxKhz: deviceInfo['spectrumScanMaxKhz'] as int?,
|
||||||
@@ -481,6 +564,9 @@ class ConnectionProvider with ChangeNotifier {
|
|||||||
publicKey: selfInfo['publicKey'] as Uint8List?,
|
publicKey: selfInfo['publicKey'] as Uint8List?,
|
||||||
advLat: selfInfo['advLat'] as int?,
|
advLat: selfInfo['advLat'] as int?,
|
||||||
advLon: selfInfo['advLon'] as int?,
|
advLon: selfInfo['advLon'] as int?,
|
||||||
|
multiAcks: selfInfo['multiAcks'] as int?,
|
||||||
|
advertLocPolicy: selfInfo['advertLocPolicy'] as int?,
|
||||||
|
telemetryModes: selfInfo['telemetryModes'] as int?,
|
||||||
manualAddContacts: selfInfo['manualAddContacts'] as bool?,
|
manualAddContacts: selfInfo['manualAddContacts'] as bool?,
|
||||||
radioFreq: selfInfo['radioFreq'] as int?,
|
radioFreq: selfInfo['radioFreq'] as int?,
|
||||||
radioBw: selfInfo['radioBw'] as int?,
|
radioBw: selfInfo['radioBw'] as int?,
|
||||||
@@ -523,6 +609,7 @@ class ConnectionProvider with ChangeNotifier {
|
|||||||
autoAddRoomServers: config['autoAddRoomServers'] as bool?,
|
autoAddRoomServers: config['autoAddRoomServers'] as bool?,
|
||||||
autoAddSensors: config['autoAddSensors'] as bool?,
|
autoAddSensors: config['autoAddSensors'] as bool?,
|
||||||
autoAddOverwriteOldest: config['autoAddOverwriteOldest'] as bool?,
|
autoAddOverwriteOldest: config['autoAddOverwriteOldest'] as bool?,
|
||||||
|
autoAddMaxHops: config['autoAddMaxHops'] as int?,
|
||||||
);
|
);
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
};
|
};
|
||||||
@@ -564,6 +651,13 @@ class ConnectionProvider with ChangeNotifier {
|
|||||||
debugPrint('✅ [Provider] Scan state initialized, notifying listeners');
|
debugPrint('✅ [Provider] Scan state initialized, notifying listeners');
|
||||||
|
|
||||||
try {
|
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(
|
await for (final scanResult in _bleService.scanForDevices(
|
||||||
timeout: const Duration(seconds: 10),
|
timeout: const Duration(seconds: 10),
|
||||||
)) {
|
)) {
|
||||||
@@ -605,6 +699,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
|
/// Stop scanning
|
||||||
Future<void> stopScan() async {
|
Future<void> stopScan() async {
|
||||||
await FlutterBluePlus.stopScan();
|
await FlutterBluePlus.stopScan();
|
||||||
@@ -629,27 +770,15 @@ class ConnectionProvider with ChangeNotifier {
|
|||||||
debugPrint(
|
debugPrint(
|
||||||
'🔵 [Provider] connect() called for device: ${device.platformName}',
|
'🔵 [Provider] connect() called for device: ${device.platformName}',
|
||||||
);
|
);
|
||||||
|
await _prepareForConnectionSwitch(ConnectionMode.ble);
|
||||||
if (_isScanning) {
|
_beginConnectionAttempt(
|
||||||
debugPrint('🔵 [Provider] Stopping active scan before connect()');
|
mode: ConnectionMode.ble,
|
||||||
await stopScan();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Ensure we route commands to BLE, not a stale TCP service.
|
|
||||||
_connectionMode = ConnectionMode.ble;
|
|
||||||
|
|
||||||
_deviceInfo = _deviceInfo.copyWith(
|
|
||||||
deviceId: device.remoteId.toString(),
|
deviceId: device.remoteId.toString(),
|
||||||
deviceName: device.platformName.isNotEmpty
|
deviceName: device.platformName.isNotEmpty
|
||||||
? device.platformName
|
? device.platformName
|
||||||
: 'Unknown',
|
: 'Unknown',
|
||||||
connectionState: ConnectionState.connecting,
|
|
||||||
);
|
);
|
||||||
_error = null;
|
|
||||||
_supportsAutoaddConfig = null;
|
|
||||||
_resetSyncState();
|
|
||||||
debugPrint('✅ [Provider] Device info updated to connecting state');
|
debugPrint('✅ [Provider] Device info updated to connecting state');
|
||||||
notifyListeners();
|
|
||||||
|
|
||||||
debugPrint('🔵 [Provider] Calling BLE service connect()...');
|
debugPrint('🔵 [Provider] Calling BLE service connect()...');
|
||||||
final success = await _bleService.connect(device);
|
final success = await _bleService.connect(device);
|
||||||
@@ -669,23 +798,18 @@ class ConnectionProvider with ChangeNotifier {
|
|||||||
/// Connect to a MeshCore device over TCP/WiFi (port 5000)
|
/// Connect to a MeshCore device over TCP/WiFi (port 5000)
|
||||||
Future<bool> connectTcp(String host, int port) async {
|
Future<bool> connectTcp(String host, int port) async {
|
||||||
debugPrint('🌐 [Provider] connectTcp() $host:$port');
|
debugPrint('🌐 [Provider] connectTcp() $host:$port');
|
||||||
|
await _prepareForConnectionSwitch(ConnectionMode.tcp);
|
||||||
_tcpHost = host;
|
|
||||||
_deviceInfo = _deviceInfo.copyWith(
|
|
||||||
deviceId: '$host:$port',
|
|
||||||
deviceName: host,
|
|
||||||
connectionState: ConnectionState.connecting,
|
|
||||||
);
|
|
||||||
_error = null;
|
|
||||||
_supportsAutoaddConfig = null;
|
|
||||||
notifyListeners();
|
|
||||||
|
|
||||||
// Create fresh TCP service and wire its callbacks
|
// Create fresh TCP service and wire its callbacks
|
||||||
_tcpService?.dispose();
|
await _disposeTcpService();
|
||||||
_tcpService = MeshCoreTcpService();
|
_tcpService = MeshCoreTcpService();
|
||||||
_wireServiceCallbacks(_tcpService!);
|
_wireServiceCallbacks(_tcpService!);
|
||||||
|
_beginConnectionAttempt(
|
||||||
_connectionMode = ConnectionMode.tcp;
|
mode: ConnectionMode.tcp,
|
||||||
|
deviceId: '$host:$port',
|
||||||
|
deviceName: host,
|
||||||
|
tcpHost: host,
|
||||||
|
);
|
||||||
|
|
||||||
final success = await _tcpService!.connect(host, port);
|
final success = await _tcpService!.connect(host, port);
|
||||||
if (!success) {
|
if (!success) {
|
||||||
@@ -699,21 +823,8 @@ class ConnectionProvider with ChangeNotifier {
|
|||||||
|
|
||||||
/// Disconnect from TCP/WiFi device
|
/// Disconnect from TCP/WiFi device
|
||||||
Future<void> disconnectTcp() async {
|
Future<void> disconnectTcp() async {
|
||||||
if (_tcpService != null) {
|
await _disposeTcpService();
|
||||||
await _tcpService!.disconnect();
|
_resetConnectionSession();
|
||||||
_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();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Connect via USB serial using a pre-configured [MeshCoreSerialService].
|
/// Connect via USB serial using a pre-configured [MeshCoreSerialService].
|
||||||
@@ -721,22 +832,23 @@ class ConnectionProvider with ChangeNotifier {
|
|||||||
/// The caller is responsible for opening the serial port and wiring
|
/// The caller is responsible for opening the serial port and wiring
|
||||||
/// [service.writeRaw] + [service.feedRawBytes] before calling this.
|
/// [service.writeRaw] + [service.feedRawBytes] before calling this.
|
||||||
/// After this call succeeds, [service.markConnected()] has already run.
|
/// 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()');
|
debugPrint('🔌 [Provider] connectSerial()');
|
||||||
|
await _prepareForConnectionSwitch(ConnectionMode.usb);
|
||||||
_deviceInfo = _deviceInfo.copyWith(
|
await _disposeSerialService();
|
||||||
deviceId: 'usb',
|
|
||||||
deviceName: 'USB Companion',
|
|
||||||
connectionState: ConnectionState.connecting,
|
|
||||||
);
|
|
||||||
_error = null;
|
|
||||||
_supportsAutoaddConfig = null;
|
|
||||||
notifyListeners();
|
|
||||||
|
|
||||||
_serialService?.dispose();
|
|
||||||
_serialService = service;
|
_serialService = service;
|
||||||
|
_serialDisconnectTransport = disconnectTransport;
|
||||||
_wireServiceCallbacks(_serialService!);
|
_wireServiceCallbacks(_serialService!);
|
||||||
_connectionMode = ConnectionMode.usb;
|
_beginConnectionAttempt(
|
||||||
|
mode: ConnectionMode.usb,
|
||||||
|
deviceId: deviceId,
|
||||||
|
deviceName: deviceName,
|
||||||
|
);
|
||||||
|
|
||||||
// markConnected() should already have been called by the transport.
|
// markConnected() should already have been called by the transport.
|
||||||
// If it hasn't, the service won't be connected yet.
|
// If it hasn't, the service won't be connected yet.
|
||||||
@@ -744,6 +856,7 @@ class ConnectionProvider with ChangeNotifier {
|
|||||||
_deviceInfo = _deviceInfo.copyWith(
|
_deviceInfo = _deviceInfo.copyWith(
|
||||||
connectionState: ConnectionState.error,
|
connectionState: ConnectionState.error,
|
||||||
);
|
);
|
||||||
|
await _disposeSerialService();
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -752,18 +865,8 @@ class ConnectionProvider with ChangeNotifier {
|
|||||||
|
|
||||||
/// Disconnect from USB serial device.
|
/// Disconnect from USB serial device.
|
||||||
Future<void> disconnectSerial() async {
|
Future<void> disconnectSerial() async {
|
||||||
_serialService?.markDisconnected();
|
await _disposeSerialService();
|
||||||
_serialService?.dispose();
|
_resetConnectionSession();
|
||||||
_serialService = null;
|
|
||||||
_connectionMode = ConnectionMode.ble;
|
|
||||||
_supportsAutoaddConfig = null;
|
|
||||||
_resetSyncState();
|
|
||||||
_deviceInfo = DeviceInfo(connectionState: ConnectionState.disconnected);
|
|
||||||
_roomLoginManager.clearRoomLoginStates();
|
|
||||||
_pingTracker.clearAll();
|
|
||||||
_pendingSendOperations.clear();
|
|
||||||
_messageDeliveryTracker.clearTracking();
|
|
||||||
notifyListeners();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Disconnect from device
|
/// Disconnect from device
|
||||||
@@ -783,15 +886,7 @@ class ConnectionProvider with ChangeNotifier {
|
|||||||
}
|
}
|
||||||
|
|
||||||
await _bleService.disconnect();
|
await _bleService.disconnect();
|
||||||
|
_resetConnectionSession();
|
||||||
_supportsAutoaddConfig = null;
|
|
||||||
_resetSyncState();
|
|
||||||
_deviceInfo = DeviceInfo(connectionState: ConnectionState.disconnected);
|
|
||||||
_roomLoginManager.clearRoomLoginStates();
|
|
||||||
_pingTracker.clearAll();
|
|
||||||
_pendingSendOperations.clear();
|
|
||||||
_messageDeliveryTracker.clearTracking();
|
|
||||||
notifyListeners();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Reset message sync state so the next connect/reconnect can sync cleanly.
|
/// Reset message sync state so the next connect/reconnect can sync cleanly.
|
||||||
@@ -1763,11 +1858,13 @@ class ConnectionProvider with ChangeNotifier {
|
|||||||
return pendingPing;
|
return pendingPing;
|
||||||
}
|
}
|
||||||
|
|
||||||
final future = _runSmartPing(
|
final future = _isSelfPublicKey(contactPublicKey)
|
||||||
contactPublicKey: contactPublicKey,
|
? _runSelfTelemetryPing(contactPublicKey)
|
||||||
hasPath: hasPath,
|
: _runSmartPing(
|
||||||
onRetryWithFlooding: onRetryWithFlooding,
|
contactPublicKey: contactPublicKey,
|
||||||
);
|
hasPath: hasPath,
|
||||||
|
onRetryWithFlooding: onRetryWithFlooding,
|
||||||
|
);
|
||||||
_pendingSmartPings[pingKey] = future;
|
_pendingSmartPings[pingKey] = future;
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
|
|
||||||
@@ -1854,10 +1951,53 @@ class ConnectionProvider with ChangeNotifier {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<PingResult> _runSelfTelemetryPing(Uint8List devicePublicKey) async {
|
||||||
|
if (!_activeService.isConnected) {
|
||||||
|
_error = 'Not connected to device';
|
||||||
|
notifyListeners();
|
||||||
|
return PingResult(success: false, usedFlooding: false, timedOut: true);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
final pingFuture = _pingTracker.trackPing(
|
||||||
|
publicKey: devicePublicKey,
|
||||||
|
wasDirectAttempt: true,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Firmware treats a 4-byte telemetry request as "self telemetry".
|
||||||
|
await _activeService.requestTelemetry(Uint8List(0), zeroHop: true);
|
||||||
|
|
||||||
|
final gotResponse = await pingFuture;
|
||||||
|
return PingResult(
|
||||||
|
success: gotResponse,
|
||||||
|
usedFlooding: false,
|
||||||
|
timedOut: !gotResponse,
|
||||||
|
);
|
||||||
|
} catch (e) {
|
||||||
|
_error = 'Failed to request self telemetry: $e';
|
||||||
|
notifyListeners();
|
||||||
|
return PingResult(success: false, usedFlooding: false, timedOut: true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
String _publicKeyToHex(Uint8List publicKey) {
|
String _publicKeyToHex(Uint8List publicKey) {
|
||||||
return publicKey.map((b) => b.toRadixString(16).padLeft(2, '0')).join('');
|
return publicKey.map((b) => b.toRadixString(16).padLeft(2, '0')).join('');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool _isSelfPublicKey(Uint8List publicKey) {
|
||||||
|
final selfKey = _deviceInfo.publicKey;
|
||||||
|
if (selfKey == null || selfKey.length != publicKey.length) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var i = 0; i < publicKey.length; i++) {
|
||||||
|
if (selfKey[i] != publicKey[i]) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
/// Send binary request to contact (modern replacement for requestTelemetry)
|
/// Send binary request to contact (modern replacement for requestTelemetry)
|
||||||
///
|
///
|
||||||
/// Supports multiple request types:
|
/// Supports multiple request types:
|
||||||
@@ -2202,6 +2342,7 @@ class ConnectionProvider with ChangeNotifier {
|
|||||||
autoAddRoomServers: config['autoAddRoomServers'] as bool?,
|
autoAddRoomServers: config['autoAddRoomServers'] as bool?,
|
||||||
autoAddSensors: config['autoAddSensors'] as bool?,
|
autoAddSensors: config['autoAddSensors'] as bool?,
|
||||||
autoAddOverwriteOldest: config['autoAddOverwriteOldest'] as bool?,
|
autoAddOverwriteOldest: config['autoAddOverwriteOldest'] as bool?,
|
||||||
|
autoAddMaxHops: config['autoAddMaxHops'] as int?,
|
||||||
);
|
);
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -2213,6 +2354,7 @@ class ConnectionProvider with ChangeNotifier {
|
|||||||
autoAddRoomServers: null,
|
autoAddRoomServers: null,
|
||||||
autoAddSensors: null,
|
autoAddSensors: null,
|
||||||
autoAddOverwriteOldest: null,
|
autoAddOverwriteOldest: null,
|
||||||
|
autoAddMaxHops: null,
|
||||||
);
|
);
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
return;
|
return;
|
||||||
@@ -2232,6 +2374,7 @@ class ConnectionProvider with ChangeNotifier {
|
|||||||
required bool autoAddRoomServers,
|
required bool autoAddRoomServers,
|
||||||
required bool autoAddSensors,
|
required bool autoAddSensors,
|
||||||
required bool overwriteOldest,
|
required bool overwriteOldest,
|
||||||
|
int maxHops = 0,
|
||||||
}) async {
|
}) async {
|
||||||
if (!_activeService.isConnected) {
|
if (!_activeService.isConnected) {
|
||||||
_error = 'Not connected to device';
|
_error = 'Not connected to device';
|
||||||
@@ -2246,6 +2389,7 @@ class ConnectionProvider with ChangeNotifier {
|
|||||||
autoAddRoomServers: autoAddRoomServers,
|
autoAddRoomServers: autoAddRoomServers,
|
||||||
autoAddSensors: autoAddSensors,
|
autoAddSensors: autoAddSensors,
|
||||||
overwriteOldest: overwriteOldest,
|
overwriteOldest: overwriteOldest,
|
||||||
|
maxHops: maxHops,
|
||||||
);
|
);
|
||||||
_deviceInfo = _deviceInfo.copyWith(
|
_deviceInfo = _deviceInfo.copyWith(
|
||||||
autoAddUsers: autoAddUsers,
|
autoAddUsers: autoAddUsers,
|
||||||
@@ -2253,6 +2397,7 @@ class ConnectionProvider with ChangeNotifier {
|
|||||||
autoAddRoomServers: autoAddRoomServers,
|
autoAddRoomServers: autoAddRoomServers,
|
||||||
autoAddSensors: autoAddSensors,
|
autoAddSensors: autoAddSensors,
|
||||||
autoAddOverwriteOldest: overwriteOldest,
|
autoAddOverwriteOldest: overwriteOldest,
|
||||||
|
autoAddMaxHops: maxHops,
|
||||||
);
|
);
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -2261,15 +2406,30 @@ class ConnectionProvider with ChangeNotifier {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<void> setPathHashMode(int mode) async {
|
||||||
|
if (!_activeService.isConnected) {
|
||||||
|
_error = 'Not connected to device';
|
||||||
|
notifyListeners();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await _activeService.setPathHashMode(mode);
|
||||||
|
_deviceInfo = _deviceInfo.copyWith(pathHashMode: mode);
|
||||||
|
notifyListeners();
|
||||||
|
} catch (e) {
|
||||||
|
_error = 'Failed to set path hash mode: $e';
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Export a contact as a meshcore:// share URL.
|
/// Export a contact as a meshcore:// share URL.
|
||||||
/// Pass null to export self.
|
/// Pass null to export self.
|
||||||
Future<String?> exportContactUrl(Uint8List? publicKey) async {
|
Future<String?> exportContactUrl(Uint8List? publicKey) async {
|
||||||
if (!_activeService.isConnected) return null;
|
if (!_activeService.isConnected) return null;
|
||||||
try {
|
try {
|
||||||
final frame = await _activeService.exportContact(publicKey);
|
final frame = await _activeService.exportContact(publicKey);
|
||||||
final hex = frame
|
final hex = frame.map((b) => b.toRadixString(16).padLeft(2, '0')).join();
|
||||||
.map((b) => b.toRadixString(16).padLeft(2, '0'))
|
|
||||||
.join();
|
|
||||||
return 'meshcore://$hex';
|
return 'meshcore://$hex';
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
debugPrint('⚠️ [Provider] exportContact failed: $e');
|
debugPrint('⚠️ [Provider] exportContact failed: $e');
|
||||||
@@ -2347,6 +2507,18 @@ class ConnectionProvider with ChangeNotifier {
|
|||||||
/// - Total storage in KB (if available)
|
/// - Total storage in KB (if available)
|
||||||
///
|
///
|
||||||
/// Results arrive via onBatteryAndStorage callback and update deviceInfo.
|
/// 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 {
|
||||||
|
// Firmware expects a 4-byte CMD_SEND_TELEMETRY_REQ frame for "self".
|
||||||
|
await _activeService.requestTelemetry(Uint8List(0), zeroHop: true);
|
||||||
|
} catch (e) {
|
||||||
|
debugPrint('⚠️ [Provider] requestSelfTelemetry failed: $e');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Future<void> getBatteryAndStorage() async {
|
Future<void> getBatteryAndStorage() async {
|
||||||
if (!_activeService.isConnected) {
|
if (!_activeService.isConnected) {
|
||||||
_error = 'Not connected to device';
|
_error = 'Not connected to device';
|
||||||
@@ -2737,6 +2909,12 @@ class ConnectionProvider with ChangeNotifier {
|
|||||||
_rxActivityTimer?.cancel();
|
_rxActivityTimer?.cancel();
|
||||||
_txActivityTimer?.cancel();
|
_txActivityTimer?.cancel();
|
||||||
_stopAckCleanupTimer();
|
_stopAckCleanupTimer();
|
||||||
|
final disconnectTransport = _serialDisconnectTransport;
|
||||||
|
if (disconnectTransport != null) {
|
||||||
|
unawaited(disconnectTransport());
|
||||||
|
_serialDisconnectTransport = null;
|
||||||
|
}
|
||||||
|
_serialService?.dispose();
|
||||||
_bleService.dispose();
|
_bleService.dispose();
|
||||||
_tcpService?.dispose();
|
_tcpService?.dispose();
|
||||||
super.dispose();
|
super.dispose();
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import '../models/contact_group.dart';
|
|||||||
import '../models/message_contact_location.dart';
|
import '../models/message_contact_location.dart';
|
||||||
import '../services/cayenne_lpp_parser.dart';
|
import '../services/cayenne_lpp_parser.dart';
|
||||||
import '../services/contact_storage_service.dart';
|
import '../services/contact_storage_service.dart';
|
||||||
|
import '../services/profiles_feature_service.dart';
|
||||||
import '../utils/fast_gps_packet.dart';
|
import '../utils/fast_gps_packet.dart';
|
||||||
import '../utils/rssi_location_estimator.dart';
|
import '../utils/rssi_location_estimator.dart';
|
||||||
import '../utils/key_comparison.dart';
|
import '../utils/key_comparison.dart';
|
||||||
@@ -138,9 +139,12 @@ class ContactsProvider with ChangeNotifier {
|
|||||||
bool _isPersistingPendingAdverts = false;
|
bool _isPersistingPendingAdverts = false;
|
||||||
bool _persistPendingAdvertsRequested = false;
|
bool _persistPendingAdvertsRequested = false;
|
||||||
String? _storageNamespace;
|
String? _storageNamespace;
|
||||||
|
String? _selfPublicKeyHex;
|
||||||
|
ContactTelemetry? _selfTelemetry;
|
||||||
|
|
||||||
// Add default public channel on initialization
|
// Add default public channel on initialization
|
||||||
ContactsProvider() {
|
ContactsProvider()
|
||||||
|
: _storageNamespace = ProfileStorageScope.effectiveNamespace {
|
||||||
_ensurePublicChannelExists();
|
_ensurePublicChannelExists();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -160,6 +164,7 @@ class ContactsProvider with ChangeNotifier {
|
|||||||
Uint8List? devicePublicKey,
|
Uint8List? devicePublicKey,
|
||||||
}) async {
|
}) async {
|
||||||
_storageNamespace = namespace;
|
_storageNamespace = namespace;
|
||||||
|
_setSelfDevicePublicKey(devicePublicKey);
|
||||||
await _loadFromStorage(force: true, devicePublicKey: devicePublicKey);
|
await _loadFromStorage(force: true, devicePublicKey: devicePublicKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -251,6 +256,7 @@ class ContactsProvider with ChangeNotifier {
|
|||||||
/// Initialize and load persisted contacts
|
/// Initialize and load persisted contacts
|
||||||
/// [devicePublicKey] - device's own public key to exclude from loaded contacts
|
/// [devicePublicKey] - device's own public key to exclude from loaded contacts
|
||||||
Future<void> initialize({Uint8List? devicePublicKey}) async {
|
Future<void> initialize({Uint8List? devicePublicKey}) async {
|
||||||
|
_setSelfDevicePublicKey(devicePublicKey);
|
||||||
if (_isInitialized) {
|
if (_isInitialized) {
|
||||||
// If already initialized (from early load), just filter out self-contact
|
// If already initialized (from early load), just filter out self-contact
|
||||||
if (devicePublicKey != null) {
|
if (devicePublicKey != null) {
|
||||||
@@ -265,6 +271,36 @@ class ContactsProvider with ChangeNotifier {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Clear runtime contact state before a live device contact sync begins.
|
||||||
|
///
|
||||||
|
/// This intentionally does not touch persisted storage. It keeps any saved
|
||||||
|
/// contact groups for the active profile, but removes stale in-memory device
|
||||||
|
/// contacts and discovery state so a newly connected device starts from an
|
||||||
|
/// empty list while sync is in progress.
|
||||||
|
Future<void> prepareForDeviceContactSync({Uint8List? devicePublicKey}) async {
|
||||||
|
_setSelfDevicePublicKey(devicePublicKey);
|
||||||
|
_selfTelemetry = null;
|
||||||
|
if (!_isInitialized) {
|
||||||
|
final storedGroups = await _storageService.loadContactGroups(
|
||||||
|
namespace: _storageNamespace,
|
||||||
|
);
|
||||||
|
_savedContactGroups
|
||||||
|
..clear()
|
||||||
|
..addAll(storedGroups);
|
||||||
|
_isInitialized = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
debugPrint(
|
||||||
|
'🧹 [ContactsProvider] Clearing runtime contacts before device sync',
|
||||||
|
);
|
||||||
|
_contacts.clear();
|
||||||
|
_pendingAdverts.clear();
|
||||||
|
_estimatedLocations.clear();
|
||||||
|
_rssiObservations.clear();
|
||||||
|
_ensurePublicChannelExists();
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
/// Remove self-contact from loaded contacts (called after BLE connection established)
|
/// Remove self-contact from loaded contacts (called after BLE connection established)
|
||||||
void _removeSelfContact(Uint8List devicePublicKey) {
|
void _removeSelfContact(Uint8List devicePublicKey) {
|
||||||
final selfKeyHex = devicePublicKey
|
final selfKeyHex = devicePublicKey
|
||||||
@@ -345,6 +381,7 @@ class ContactsProvider with ChangeNotifier {
|
|||||||
}
|
}
|
||||||
|
|
||||||
List<Contact> get contacts => _contacts.values.toList();
|
List<Contact> get contacts => _contacts.values.toList();
|
||||||
|
ContactTelemetry? get selfTelemetry => _selfTelemetry;
|
||||||
List<Contact> get favouriteContacts =>
|
List<Contact> get favouriteContacts =>
|
||||||
_contacts.values.where((c) => c.isFavourite).toList();
|
_contacts.values.where((c) => c.isFavourite).toList();
|
||||||
List<SavedContactGroup> get savedContactGroups =>
|
List<SavedContactGroup> get savedContactGroups =>
|
||||||
@@ -535,9 +572,11 @@ class ContactsProvider with ChangeNotifier {
|
|||||||
// Replace existing observation from the same repeater, or add new
|
// Replace existing observation from the same repeater, or add new
|
||||||
final repeaterKey =
|
final repeaterKey =
|
||||||
'${observation.repeaterLocation.latitude},${observation.repeaterLocation.longitude}';
|
'${observation.repeaterLocation.latitude},${observation.repeaterLocation.longitude}';
|
||||||
observations.removeWhere((o) =>
|
observations.removeWhere(
|
||||||
'${o.repeaterLocation.latitude},${o.repeaterLocation.longitude}' ==
|
(o) =>
|
||||||
repeaterKey);
|
'${o.repeaterLocation.latitude},${o.repeaterLocation.longitude}' ==
|
||||||
|
repeaterKey,
|
||||||
|
);
|
||||||
observations.add(observation);
|
observations.add(observation);
|
||||||
|
|
||||||
// Keep at most 8 observations (most recent per repeater)
|
// Keep at most 8 observations (most recent per repeater)
|
||||||
@@ -926,6 +965,10 @@ class ContactsProvider with ChangeNotifier {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Update contact telemetry
|
/// 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) {
|
void updateTelemetry(Uint8List publicKeyPrefix, Uint8List lppData) {
|
||||||
debugPrint('📊 [ContactsProvider] updateTelemetry() called');
|
debugPrint('📊 [ContactsProvider] updateTelemetry() called');
|
||||||
debugPrint(
|
debugPrint(
|
||||||
@@ -933,15 +976,39 @@ class ContactsProvider with ChangeNotifier {
|
|||||||
);
|
);
|
||||||
debugPrint(' LPP data size: ${lppData.length} bytes');
|
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
|
// Find contact by public key prefix
|
||||||
final contact = _findContactByPrefix(publicKeyPrefix);
|
final contact = _findContactByPrefix(publicKeyPrefix);
|
||||||
if (contact == null) {
|
final isSelfTelemetry =
|
||||||
|
contact == null && _matchesSelfPrefix(publicKeyPrefix);
|
||||||
|
if (contact == null && !isSelfTelemetry) {
|
||||||
debugPrint(' ❌ Contact not found for this prefix');
|
debugPrint(' ❌ Contact not found for this prefix');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
debugPrint(' ✅ Found contact: ${contact.advName}');
|
if (isSelfTelemetry) {
|
||||||
debugPrint(' Old telemetry timestamp: ${contact.telemetry?.timestamp}');
|
debugPrint(' ✅ Matched self telemetry response');
|
||||||
|
debugPrint(
|
||||||
|
' Old self telemetry timestamp: ${_selfTelemetry?.timestamp}',
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
debugPrint(' ✅ Found contact: ${contact!.advName}');
|
||||||
|
debugPrint(' Old telemetry timestamp: ${contact.telemetry?.timestamp}');
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Parse Cayenne LPP data
|
// Parse Cayenne LPP data
|
||||||
@@ -964,7 +1031,9 @@ class ContactsProvider with ChangeNotifier {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
final previousTelemetry = contact.telemetry;
|
final previousTelemetry = isSelfTelemetry
|
||||||
|
? _selfTelemetry
|
||||||
|
: contact!.telemetry;
|
||||||
|
|
||||||
final mergedTelemetry = _mergeTelemetryForContact(
|
final mergedTelemetry = _mergeTelemetryForContact(
|
||||||
existingTelemetry: previousTelemetry,
|
existingTelemetry: previousTelemetry,
|
||||||
@@ -991,25 +1060,34 @@ class ContactsProvider with ChangeNotifier {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (isSelfTelemetry) {
|
||||||
|
_selfTelemetry = telemetry;
|
||||||
|
notifyListeners();
|
||||||
|
debugPrint(' ✅ Updated self telemetry');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
final resolvedContact = contact!;
|
||||||
|
|
||||||
// Update contact with new telemetry AND last seen time
|
// Update contact with new telemetry AND last seen time
|
||||||
// lastAdvert is Unix timestamp in seconds
|
// lastAdvert is Unix timestamp in seconds
|
||||||
final currentTimestamp = (DateTime.now().millisecondsSinceEpoch / 1000)
|
final currentTimestamp = (DateTime.now().millisecondsSinceEpoch / 1000)
|
||||||
.round();
|
.round();
|
||||||
debugPrint(' Old lastAdvert: ${contact.lastAdvert}');
|
debugPrint(' Old lastAdvert: ${resolvedContact.lastAdvert}');
|
||||||
debugPrint(' New lastAdvert: $currentTimestamp');
|
debugPrint(' New lastAdvert: $currentTimestamp');
|
||||||
|
|
||||||
final persistedGps = _getValidGpsOrNull(telemetry.gpsLocation);
|
final persistedGps = _getValidGpsOrNull(telemetry.gpsLocation);
|
||||||
final updatedContact = contact.copyWith(
|
final updatedContact = resolvedContact.copyWith(
|
||||||
telemetry: telemetry,
|
telemetry: telemetry,
|
||||||
lastAdvert: currentTimestamp, // Update last seen time
|
lastAdvert: currentTimestamp, // Update last seen time
|
||||||
advLat: persistedGps != null
|
advLat: persistedGps != null
|
||||||
? _coordinateToAdvertMicrodegrees(persistedGps.latitude)
|
? _coordinateToAdvertMicrodegrees(persistedGps.latitude)
|
||||||
: contact.advLat,
|
: resolvedContact.advLat,
|
||||||
advLon: persistedGps != null
|
advLon: persistedGps != null
|
||||||
? _coordinateToAdvertMicrodegrees(persistedGps.longitude)
|
? _coordinateToAdvertMicrodegrees(persistedGps.longitude)
|
||||||
: contact.advLon,
|
: resolvedContact.advLon,
|
||||||
);
|
);
|
||||||
_contacts[contact.publicKeyHex] = updatedContact;
|
_contacts[resolvedContact.publicKeyHex] = updatedContact;
|
||||||
debugPrint(' ✅ Updated contact in map (with new lastAdvert)');
|
debugPrint(' ✅ Updated contact in map (with new lastAdvert)');
|
||||||
|
|
||||||
_persistContacts();
|
_persistContacts();
|
||||||
@@ -1176,10 +1254,11 @@ class ContactsProvider with ChangeNotifier {
|
|||||||
|
|
||||||
/// Find contact by public key prefix (6 bytes)
|
/// Find contact by public key prefix (6 bytes)
|
||||||
Contact? _findContactByPrefix(Uint8List prefix) {
|
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
|
final prefixHex = prefix
|
||||||
.sublist(0, 6)
|
.sublist(0, takeLen)
|
||||||
.map((b) => b.toRadixString(16).padLeft(2, '0'))
|
.map((b) => b.toRadixString(16).padLeft(2, '0'))
|
||||||
.join('');
|
.join('');
|
||||||
|
|
||||||
@@ -1215,6 +1294,36 @@ class ContactsProvider with ChangeNotifier {
|
|||||||
return _contacts[keyHex];
|
return _contacts[keyHex];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void _setSelfDevicePublicKey(Uint8List? devicePublicKey) {
|
||||||
|
final nextKeyHex = _publicKeyHexOrNull(devicePublicKey);
|
||||||
|
if (_selfPublicKeyHex != nextKeyHex) {
|
||||||
|
_selfTelemetry = null;
|
||||||
|
}
|
||||||
|
_selfPublicKeyHex = nextKeyHex;
|
||||||
|
}
|
||||||
|
|
||||||
|
String? _publicKeyHexOrNull(Uint8List? publicKey) {
|
||||||
|
if (publicKey == null || publicKey.isEmpty) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return publicKey.map((b) => b.toRadixString(16).padLeft(2, '0')).join('');
|
||||||
|
}
|
||||||
|
|
||||||
|
bool _matchesSelfPrefix(Uint8List prefix) {
|
||||||
|
final selfKeyHex = _selfPublicKeyHex;
|
||||||
|
if (selfKeyHex == null || prefix.isEmpty) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
final takeLen = prefix.length < 6 ? prefix.length : 6;
|
||||||
|
final prefixHex = prefix
|
||||||
|
.sublist(0, takeLen)
|
||||||
|
.map((b) => b.toRadixString(16).padLeft(2, '0'))
|
||||||
|
.join('');
|
||||||
|
return selfKeyHex.startsWith(prefixHex);
|
||||||
|
}
|
||||||
|
|
||||||
/// Clear a contact's learned path locally so the UI and next send both
|
/// Clear a contact's learned path locally so the UI and next send both
|
||||||
/// prefer flood routing until the radio reports a fresh route.
|
/// prefer flood routing until the radio reports a fresh route.
|
||||||
void markPathUnhealthy(Uint8List publicKey) {
|
void markPathUnhealthy(Uint8List publicKey) {
|
||||||
@@ -1618,6 +1727,9 @@ class ContactsProvider with ChangeNotifier {
|
|||||||
_contacts.clear();
|
_contacts.clear();
|
||||||
_savedContactGroups.clear();
|
_savedContactGroups.clear();
|
||||||
_pendingAdverts.clear();
|
_pendingAdverts.clear();
|
||||||
|
_estimatedLocations.clear();
|
||||||
|
_rssiObservations.clear();
|
||||||
|
_selfTelemetry = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
Map<String, dynamic> _pendingAdvertToJson(PendingAdvert advert) {
|
Map<String, dynamic> _pendingAdvertToJson(PendingAdvert advert) {
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import 'dart:convert';
|
|||||||
import 'package:flutter/foundation.dart';
|
import 'package:flutter/foundation.dart';
|
||||||
import 'package:shared_preferences/shared_preferences.dart';
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
import '../models/contact.dart';
|
import '../models/contact.dart';
|
||||||
|
import '../services/profiles_feature_service.dart';
|
||||||
import 'helpers/raw_session_retransmit.dart';
|
import 'helpers/raw_session_retransmit.dart';
|
||||||
import '../utils/image_message_parser.dart';
|
import '../utils/image_message_parser.dart';
|
||||||
|
|
||||||
@@ -75,6 +76,8 @@ class ImageProvider with ChangeNotifier {
|
|||||||
_restore();
|
_restore();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
String _scopedStorageKey() => ProfileStorageScope.scopedKey(_storageKey);
|
||||||
|
|
||||||
// ── Accessors ────────────────────────────────────────────────────────────
|
// ── Accessors ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
ImageSession? session(String sessionId) => _sessions[sessionId];
|
ImageSession? session(String sessionId) => _sessions[sessionId];
|
||||||
@@ -292,18 +295,22 @@ class ImageProvider with ChangeNotifier {
|
|||||||
// ── Persistence ──────────────────────────────────────────────────────────
|
// ── Persistence ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
Future<void> clearAll() async {
|
Future<void> clearAll() async {
|
||||||
_sessions.clear();
|
_resetInMemoryState();
|
||||||
_outgoing.clear();
|
|
||||||
_ignoredIncomingSessions.clear();
|
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
try {
|
try {
|
||||||
final prefs = await SharedPreferences.getInstance();
|
final prefs = await SharedPreferences.getInstance();
|
||||||
await prefs.remove(_storageKey);
|
await prefs.remove(_scopedStorageKey());
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
debugPrint('❌ [ImageProvider] Failed to clear storage: $e');
|
debugPrint('❌ [ImageProvider] Failed to clear storage: $e');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<void> reloadProfileScopedState() async {
|
||||||
|
_resetInMemoryState();
|
||||||
|
await _restore();
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
void _evictExpiredOutgoing() {
|
void _evictExpiredOutgoing() {
|
||||||
final now = DateTime.now();
|
final now = DateTime.now();
|
||||||
_outgoing.removeWhere((_, s) => now.difference(s.cachedAt) > _outgoingTtl);
|
_outgoing.removeWhere((_, s) => now.difference(s.cachedAt) > _outgoingTtl);
|
||||||
@@ -343,7 +350,7 @@ class ImageProvider with ChangeNotifier {
|
|||||||
)
|
)
|
||||||
.toList(),
|
.toList(),
|
||||||
};
|
};
|
||||||
await prefs.setString(_storageKey, jsonEncode(payload));
|
await prefs.setString(_scopedStorageKey(), jsonEncode(payload));
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
debugPrint('❌ [ImageProvider] Failed to persist: $e');
|
debugPrint('❌ [ImageProvider] Failed to persist: $e');
|
||||||
}
|
}
|
||||||
@@ -352,7 +359,7 @@ class ImageProvider with ChangeNotifier {
|
|||||||
Future<void> _restore() async {
|
Future<void> _restore() async {
|
||||||
try {
|
try {
|
||||||
final prefs = await SharedPreferences.getInstance();
|
final prefs = await SharedPreferences.getInstance();
|
||||||
final raw = prefs.getString(_storageKey);
|
final raw = prefs.getString(_scopedStorageKey());
|
||||||
if (raw == null || raw.isEmpty) return;
|
if (raw == null || raw.isEmpty) return;
|
||||||
|
|
||||||
final parsed = jsonDecode(raw) as Map<String, dynamic>;
|
final parsed = jsonDecode(raw) as Map<String, dynamic>;
|
||||||
@@ -428,6 +435,12 @@ class ImageProvider with ChangeNotifier {
|
|||||||
debugPrint('❌ [ImageProvider] Failed to restore: $e');
|
debugPrint('❌ [ImageProvider] Failed to restore: $e');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void _resetInMemoryState() {
|
||||||
|
_sessions.clear();
|
||||||
|
_outgoing.clear();
|
||||||
|
_ignoredIncomingSessions.clear();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class _OutgoingSession {
|
class _OutgoingSession {
|
||||||
|
|||||||
@@ -737,8 +737,15 @@ class MessagesProvider with ChangeNotifier {
|
|||||||
if (message.isContactMessage) {
|
if (message.isContactMessage) {
|
||||||
// Match by sender key + sender timestamp (matches official app's DB
|
// Match by sender key + sender timestamp (matches official app's DB
|
||||||
// uniqueness: contactPublicKey + senderTimestamp + text + txtType).
|
// uniqueness: contactPublicKey + senderTimestamp + text + txtType).
|
||||||
return existing.senderKeyShort == message.senderKeyShort &&
|
if (existing.senderKeyShort == message.senderKeyShort &&
|
||||||
existing.senderTimestamp == message.senderTimestamp;
|
existing.senderTimestamp == message.senderTimestamp) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback dedup when retransmits surface as separate inbound rows
|
||||||
|
// without a stable timestamp/message id, but still carry the same
|
||||||
|
// visible sender identity and payload.
|
||||||
|
return _matchesDuplicateSenderIdentity(existing, message);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (message.isChannelMessage) {
|
if (message.isChannelMessage) {
|
||||||
@@ -760,29 +767,29 @@ class MessagesProvider with ChangeNotifier {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
final existingSenderKey = existing.senderKeyShort;
|
return _matchesDuplicateSenderIdentity(existing, message);
|
||||||
final incomingSenderKey = message.senderKeyShort;
|
|
||||||
if (existingSenderKey != null &&
|
|
||||||
incomingSenderKey != null &&
|
|
||||||
existingSenderKey == incomingSenderKey) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
final existingSenderName = _normalizedResolvedSenderName(existing);
|
|
||||||
final incomingSenderName = _normalizedResolvedSenderName(message);
|
|
||||||
if (existingSenderName != null &&
|
|
||||||
incomingSenderName != null &&
|
|
||||||
existingSenderName == incomingSenderName) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// System messages and other types: never deduplicate by scope alone.
|
// System messages and other types: never deduplicate by scope alone.
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool _matchesDuplicateSenderIdentity(Message existing, Message message) {
|
||||||
|
final existingSenderKey = existing.senderKeyShort;
|
||||||
|
final incomingSenderKey = message.senderKeyShort;
|
||||||
|
if (existingSenderKey != null &&
|
||||||
|
incomingSenderKey != null &&
|
||||||
|
existingSenderKey == incomingSenderKey) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
final existingSenderName = _normalizedResolvedSenderName(existing);
|
||||||
|
final incomingSenderName = _normalizedResolvedSenderName(message);
|
||||||
|
return existingSenderName != null &&
|
||||||
|
incomingSenderName != null &&
|
||||||
|
existingSenderName == incomingSenderName;
|
||||||
|
}
|
||||||
|
|
||||||
/// Add multiple messages
|
/// Add multiple messages
|
||||||
void addMessages(List<Message> messages) {
|
void addMessages(List<Message> messages) {
|
||||||
int addedCount = 0;
|
int addedCount = 0;
|
||||||
|
|||||||
@@ -474,6 +474,28 @@ class SensorsProvider with ChangeNotifier {
|
|||||||
bool isWatched(String publicKeyHex) =>
|
bool isWatched(String publicKeyHex) =>
|
||||||
_watchedSensorKeys.contains(publicKeyHex);
|
_watchedSensorKeys.contains(publicKeyHex);
|
||||||
|
|
||||||
|
Contact? selfContact(
|
||||||
|
ContactsProvider contactsProvider,
|
||||||
|
ConnectionProvider connectionProvider,
|
||||||
|
) {
|
||||||
|
final selfKey = connectionProvider.deviceInfo.publicKey;
|
||||||
|
if (selfKey == null || selfKey.isEmpty) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
final existing = contactsProvider.findContactByKey(
|
||||||
|
Uint8List.fromList(selfKey),
|
||||||
|
);
|
||||||
|
final selfTelemetry = contactsProvider.selfTelemetry;
|
||||||
|
if (existing != null) {
|
||||||
|
return selfTelemetry == null
|
||||||
|
? existing
|
||||||
|
: existing.copyWith(telemetry: selfTelemetry);
|
||||||
|
}
|
||||||
|
|
||||||
|
return _buildSelfCandidate(connectionProvider, telemetry: selfTelemetry);
|
||||||
|
}
|
||||||
|
|
||||||
Future<void> addSensor(Contact contact) async {
|
Future<void> addSensor(Contact contact) async {
|
||||||
if (!contact.isChat && !contact.isRepeater && !contact.isSensor) {
|
if (!contact.isChat && !contact.isRepeater && !contact.isSensor) {
|
||||||
return;
|
return;
|
||||||
@@ -549,17 +571,90 @@ class SensorsProvider with ChangeNotifier {
|
|||||||
notifyListeners();
|
notifyListeners();
|
||||||
}
|
}
|
||||||
|
|
||||||
List<Contact> availableCandidates(ContactsProvider contactsProvider) {
|
Future<void> reorderSensors(int oldIndex, int newIndex) async {
|
||||||
|
if (_watchedSensorKeys.length < 2) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (oldIndex < 0 ||
|
||||||
|
oldIndex >= _watchedSensorKeys.length ||
|
||||||
|
newIndex < 0 ||
|
||||||
|
newIndex > _watchedSensorKeys.length) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var targetIndex = newIndex;
|
||||||
|
if (oldIndex < targetIndex) {
|
||||||
|
targetIndex -= 1;
|
||||||
|
}
|
||||||
|
if (oldIndex == targetIndex) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
final movedKey = _watchedSensorKeys.removeAt(oldIndex);
|
||||||
|
_watchedSensorKeys.insert(targetIndex, movedKey);
|
||||||
|
await _persistWatchedSensors();
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Contact> availableCandidates(
|
||||||
|
ContactsProvider contactsProvider, {
|
||||||
|
ConnectionProvider? connectionProvider,
|
||||||
|
}) {
|
||||||
final candidates = <Contact>[
|
final candidates = <Contact>[
|
||||||
...contactsProvider.chatContacts,
|
...contactsProvider.chatContacts,
|
||||||
...contactsProvider.repeaters,
|
...contactsProvider.repeaters,
|
||||||
...contactsProvider.sensorContacts,
|
...contactsProvider.sensorContacts,
|
||||||
];
|
];
|
||||||
|
|
||||||
|
// Add "myself" (own device) as a candidate if it has a public key
|
||||||
|
if (connectionProvider != null) {
|
||||||
|
final self = selfContact(contactsProvider, connectionProvider);
|
||||||
|
if (self != null &&
|
||||||
|
!candidates.any((c) => c.publicKeyHex == self.publicKeyHex)) {
|
||||||
|
candidates.insert(0, self);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
candidates.removeWhere((contact) => isWatched(contact.publicKeyHex));
|
candidates.removeWhere((contact) => isWatched(contact.publicKeyHex));
|
||||||
candidates.sort((a, b) => b.lastSeenTime.compareTo(a.lastSeenTime));
|
candidates.sort((a, b) => b.lastSeenTime.compareTo(a.lastSeenTime));
|
||||||
return candidates;
|
return candidates;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
List<String> displaySensorKeys({
|
||||||
|
required ContactsProvider contactsProvider,
|
||||||
|
required ConnectionProvider connectionProvider,
|
||||||
|
}) {
|
||||||
|
if (_watchedSensorKeys.isNotEmpty) {
|
||||||
|
return List<String>.unmodifiable(_watchedSensorKeys);
|
||||||
|
}
|
||||||
|
|
||||||
|
final self = selfContact(contactsProvider, connectionProvider);
|
||||||
|
if (self == null) {
|
||||||
|
return const <String>[];
|
||||||
|
}
|
||||||
|
|
||||||
|
return <String>[self.publicKeyHex];
|
||||||
|
}
|
||||||
|
|
||||||
|
Contact? contactForDisplay(
|
||||||
|
String publicKeyHex, {
|
||||||
|
required ContactsProvider contactsProvider,
|
||||||
|
required ConnectionProvider connectionProvider,
|
||||||
|
}) {
|
||||||
|
for (final entry in contactsProvider.contacts) {
|
||||||
|
if (entry.publicKeyHex == publicKeyHex) {
|
||||||
|
return entry;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final self = selfContact(contactsProvider, connectionProvider);
|
||||||
|
if (self?.publicKeyHex == publicKeyHex) {
|
||||||
|
return self;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
Future<void> refreshAll({
|
Future<void> refreshAll({
|
||||||
required ContactsProvider contactsProvider,
|
required ContactsProvider contactsProvider,
|
||||||
required ConnectionProvider connectionProvider,
|
required ConnectionProvider connectionProvider,
|
||||||
@@ -597,13 +692,11 @@ class SensorsProvider with ChangeNotifier {
|
|||||||
|
|
||||||
_lastRefreshAttemptAt[publicKeyHex] = requestedAt ?? DateTime.now();
|
_lastRefreshAttemptAt[publicKeyHex] = requestedAt ?? DateTime.now();
|
||||||
|
|
||||||
Contact? contact;
|
final contact = contactForDisplay(
|
||||||
for (final entry in contactsProvider.contacts) {
|
publicKeyHex,
|
||||||
if (entry.publicKeyHex == publicKeyHex) {
|
contactsProvider: contactsProvider,
|
||||||
contact = entry;
|
connectionProvider: connectionProvider,
|
||||||
break;
|
);
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (contact == null) {
|
if (contact == null) {
|
||||||
_setRefreshState(publicKeyHex, SensorRefreshState.unavailable);
|
_setRefreshState(publicKeyHex, SensorRefreshState.unavailable);
|
||||||
@@ -686,4 +779,29 @@ class SensorsProvider with ChangeNotifier {
|
|||||||
_refreshStateUpdatedAt[publicKeyHex] = DateTime.now();
|
_refreshStateUpdatedAt[publicKeyHex] = DateTime.now();
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Contact? _buildSelfCandidate(
|
||||||
|
ConnectionProvider connectionProvider, {
|
||||||
|
ContactTelemetry? telemetry,
|
||||||
|
}) {
|
||||||
|
final deviceInfo = connectionProvider.deviceInfo;
|
||||||
|
final selfKey = deviceInfo.publicKey;
|
||||||
|
if (selfKey == null || selfKey.isEmpty) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Contact(
|
||||||
|
publicKey: Uint8List.fromList(selfKey),
|
||||||
|
type: ContactType.chat,
|
||||||
|
flags: 0,
|
||||||
|
outPathLen: 0,
|
||||||
|
outPath: Uint8List(64),
|
||||||
|
advName: deviceInfo.selfName ?? 'My Device',
|
||||||
|
lastAdvert: DateTime.now().millisecondsSinceEpoch ~/ 1000,
|
||||||
|
advLat: deviceInfo.advLat ?? 0,
|
||||||
|
advLon: deviceInfo.advLon ?? 0,
|
||||||
|
lastMod: DateTime.now().millisecondsSinceEpoch ~/ 1000,
|
||||||
|
telemetry: telemetry,
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import 'dart:typed_data';
|
|||||||
import 'package:flutter/foundation.dart';
|
import 'package:flutter/foundation.dart';
|
||||||
import 'package:shared_preferences/shared_preferences.dart';
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
import '../models/contact.dart';
|
import '../models/contact.dart';
|
||||||
|
import '../services/profiles_feature_service.dart';
|
||||||
import 'helpers/raw_session_retransmit.dart';
|
import 'helpers/raw_session_retransmit.dart';
|
||||||
import '../utils/voice_message_parser.dart';
|
import '../utils/voice_message_parser.dart';
|
||||||
import '../services/voice_codec_service.dart';
|
import '../services/voice_codec_service.dart';
|
||||||
@@ -92,6 +93,9 @@ class VoiceProvider with ChangeNotifier {
|
|||||||
_restorePersistedVoiceData();
|
_restorePersistedVoiceData();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
String _storageKey() =>
|
||||||
|
ProfileStorageScope.scopedKey(_voiceSessionsStorageKey);
|
||||||
|
|
||||||
// ── Session accessors ────────────────────────────────────────────────────
|
// ── Session accessors ────────────────────────────────────────────────────
|
||||||
|
|
||||||
VoiceSession? session(String sessionId) => _sessions[sessionId];
|
VoiceSession? session(String sessionId) => _sessions[sessionId];
|
||||||
@@ -329,19 +333,22 @@ class VoiceProvider with ChangeNotifier {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Future<void> clearStoredVoiceData() async {
|
Future<void> clearStoredVoiceData() async {
|
||||||
_sessions.clear();
|
await _resetInMemoryState();
|
||||||
_outgoingSessions.clear();
|
|
||||||
_ignoredIncomingSessions.clear();
|
|
||||||
_playingSessionId = null;
|
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
try {
|
try {
|
||||||
final prefs = await SharedPreferences.getInstance();
|
final prefs = await SharedPreferences.getInstance();
|
||||||
await prefs.remove(_voiceSessionsStorageKey);
|
await prefs.remove(_storageKey());
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
debugPrint('❌ [VoiceProvider] Failed to clear stored voice data: $e');
|
debugPrint('❌ [VoiceProvider] Failed to clear stored voice data: $e');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<void> reloadProfileScopedState() async {
|
||||||
|
await _resetInMemoryState();
|
||||||
|
await _restorePersistedVoiceData();
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
|
||||||
Future<void> _persistVoiceData() async {
|
Future<void> _persistVoiceData() async {
|
||||||
try {
|
try {
|
||||||
final prefs = await SharedPreferences.getInstance();
|
final prefs = await SharedPreferences.getInstance();
|
||||||
@@ -365,7 +372,7 @@ class VoiceProvider with ChangeNotifier {
|
|||||||
)
|
)
|
||||||
.toList(),
|
.toList(),
|
||||||
};
|
};
|
||||||
await prefs.setString(_voiceSessionsStorageKey, jsonEncode(payload));
|
await prefs.setString(_storageKey(), jsonEncode(payload));
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
debugPrint('❌ [VoiceProvider] Failed to persist voice data: $e');
|
debugPrint('❌ [VoiceProvider] Failed to persist voice data: $e');
|
||||||
}
|
}
|
||||||
@@ -374,7 +381,7 @@ class VoiceProvider with ChangeNotifier {
|
|||||||
Future<void> _restorePersistedVoiceData() async {
|
Future<void> _restorePersistedVoiceData() async {
|
||||||
try {
|
try {
|
||||||
final prefs = await SharedPreferences.getInstance();
|
final prefs = await SharedPreferences.getInstance();
|
||||||
final raw = prefs.getString(_voiceSessionsStorageKey);
|
final raw = prefs.getString(_storageKey());
|
||||||
if (raw == null || raw.isEmpty) return;
|
if (raw == null || raw.isEmpty) return;
|
||||||
|
|
||||||
final parsed = jsonDecode(raw) as Map<String, dynamic>;
|
final parsed = jsonDecode(raw) as Map<String, dynamic>;
|
||||||
@@ -437,6 +444,16 @@ class VoiceProvider with ChangeNotifier {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<void> _resetInMemoryState() async {
|
||||||
|
if (_playingSessionId != null || _player.isPlaying) {
|
||||||
|
await _player.stop();
|
||||||
|
}
|
||||||
|
_sessions.clear();
|
||||||
|
_outgoingSessions.clear();
|
||||||
|
_ignoredIncomingSessions.clear();
|
||||||
|
_playingSessionId = null;
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
_playerEventsSub.cancel();
|
_playerEventsSub.cancel();
|
||||||
|
|||||||
@@ -6,7 +6,9 @@ import '../providers/connection_provider.dart';
|
|||||||
import '../l10n/app_localizations.dart';
|
import '../l10n/app_localizations.dart';
|
||||||
|
|
||||||
class AddContactScreen extends StatefulWidget {
|
class AddContactScreen extends StatefulWidget {
|
||||||
const AddContactScreen({super.key});
|
final String? initialAdvert;
|
||||||
|
|
||||||
|
const AddContactScreen({super.key, this.initialAdvert});
|
||||||
|
|
||||||
@override
|
@override
|
||||||
State<AddContactScreen> createState() => _AddContactScreenState();
|
State<AddContactScreen> createState() => _AddContactScreenState();
|
||||||
@@ -21,7 +23,12 @@ class _AddContactScreenState extends State<AddContactScreen> {
|
|||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
super.initState();
|
super.initState();
|
||||||
_loadClipboardIfPresent();
|
if (widget.initialAdvert != null &&
|
||||||
|
widget.initialAdvert!.trim().isNotEmpty) {
|
||||||
|
_advertController.text = widget.initialAdvert!.trim();
|
||||||
|
} else {
|
||||||
|
_loadClipboardIfPresent();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@@ -79,9 +86,9 @@ class _AddContactScreenState extends State<AddContactScreen> {
|
|||||||
final text = clipboardData?.text;
|
final text = clipboardData?.text;
|
||||||
if (text == null || text.trim().isEmpty) {
|
if (text == null || text.trim().isEmpty) {
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
ScaffoldMessenger.of(
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
context,
|
SnackBar(content: Text(AppLocalizations.of(context)!.clipboardIsEmpty)),
|
||||||
).showSnackBar(SnackBar(content: Text(AppLocalizations.of(context)!.clipboardIsEmpty)));
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -140,9 +147,9 @@ class _AddContactScreenState extends State<AddContactScreen> {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
ScaffoldMessenger.of(
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
context,
|
SnackBar(content: Text(AppLocalizations.of(context)!.contactImported)),
|
||||||
).showSnackBar(SnackBar(content: Text(AppLocalizations.of(context)!.contactImported)));
|
);
|
||||||
setState(() {
|
setState(() {
|
||||||
_importSucceeded = true;
|
_importSucceeded = true;
|
||||||
});
|
});
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,3 +1,5 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:flutter/services.dart';
|
import 'package:flutter/services.dart';
|
||||||
import 'package:provider/provider.dart';
|
import 'package:provider/provider.dart';
|
||||||
@@ -6,7 +8,7 @@ import 'package:shared_preferences/shared_preferences.dart';
|
|||||||
import 'package:vibration/vibration.dart';
|
import 'package:vibration/vibration.dart';
|
||||||
import '../providers/connection_provider.dart';
|
import '../providers/connection_provider.dart';
|
||||||
import '../providers/app_provider.dart';
|
import '../providers/app_provider.dart';
|
||||||
import '../models/device_info.dart' show ConnectionMode;
|
import '../models/device_info.dart' show ConnectionMode, DeviceInfo;
|
||||||
import '../providers/messages_provider.dart';
|
import '../providers/messages_provider.dart';
|
||||||
import '../providers/contacts_provider.dart';
|
import '../providers/contacts_provider.dart';
|
||||||
import '../theme/app_theme.dart';
|
import '../theme/app_theme.dart';
|
||||||
@@ -29,7 +31,9 @@ import '../widgets/connection_dialog.dart';
|
|||||||
import '../utils/battery_display_helper.dart';
|
import '../utils/battery_display_helper.dart';
|
||||||
import '../services/developer_mode_service.dart';
|
import '../services/developer_mode_service.dart';
|
||||||
import '../services/mesh_map_nodes_service.dart';
|
import '../services/mesh_map_nodes_service.dart';
|
||||||
|
import '../services/profile_device_key_resolver.dart';
|
||||||
import '../services/profile_manager.dart';
|
import '../services/profile_manager.dart';
|
||||||
|
import '../services/profile_workspace_coordinator.dart';
|
||||||
import '../services/profiles_feature_service.dart';
|
import '../services/profiles_feature_service.dart';
|
||||||
|
|
||||||
enum _HomeTab { messages, contacts, sensors, map }
|
enum _HomeTab { messages, contacts, sensors, map }
|
||||||
@@ -60,6 +64,7 @@ class _HomeScreenState extends State<HomeScreen>
|
|||||||
with TickerProviderStateMixin, WidgetsBindingObserver {
|
with TickerProviderStateMixin, WidgetsBindingObserver {
|
||||||
late TabController _tabController;
|
late TabController _tabController;
|
||||||
late final AppProvider _appProvider;
|
late final AppProvider _appProvider;
|
||||||
|
late final ConnectionProvider _connectionProvider;
|
||||||
int _currentIndex = 0;
|
int _currentIndex = 0;
|
||||||
bool _isMapFullscreen = false;
|
bool _isMapFullscreen = false;
|
||||||
bool _showRxTxIndicators = true;
|
bool _showRxTxIndicators = true;
|
||||||
@@ -68,6 +73,7 @@ class _HomeScreenState extends State<HomeScreen>
|
|||||||
bool _isContactsEnabled = true;
|
bool _isContactsEnabled = true;
|
||||||
bool _isSensorsEnabled = false;
|
bool _isSensorsEnabled = false;
|
||||||
AppLifecycleState _lifecycleState = AppLifecycleState.resumed;
|
AppLifecycleState _lifecycleState = AppLifecycleState.resumed;
|
||||||
|
String? _lastProfileDeviceKey;
|
||||||
|
|
||||||
List<_HomeTab> get _enabledTabs {
|
List<_HomeTab> get _enabledTabs {
|
||||||
return [
|
return [
|
||||||
@@ -91,6 +97,8 @@ class _HomeScreenState extends State<HomeScreen>
|
|||||||
super.initState();
|
super.initState();
|
||||||
WidgetsBinding.instance.addObserver(this);
|
WidgetsBinding.instance.addObserver(this);
|
||||||
_appProvider = context.read<AppProvider>();
|
_appProvider = context.read<AppProvider>();
|
||||||
|
_connectionProvider = context.read<ConnectionProvider>();
|
||||||
|
_connectionProvider.addListener(_handleConnectionProviderChanged);
|
||||||
_isMapEnabled = _appProvider.isMapEnabled;
|
_isMapEnabled = _appProvider.isMapEnabled;
|
||||||
_isContactsEnabled = _appProvider.isContactsEnabled;
|
_isContactsEnabled = _appProvider.isContactsEnabled;
|
||||||
_isSensorsEnabled = _appProvider.isSensorsEnabled;
|
_isSensorsEnabled = _appProvider.isSensorsEnabled;
|
||||||
@@ -108,6 +116,10 @@ class _HomeScreenState extends State<HomeScreen>
|
|||||||
_showPermissionDialog();
|
_showPermissionDialog();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||||
|
_handleConnectionProviderChanged();
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
void _initTabController() {
|
void _initTabController() {
|
||||||
@@ -223,6 +235,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) {
|
void _openLiveTraffic(ConnectionProvider provider) {
|
||||||
openLiveTrafficScreen(context, provider);
|
openLiveTrafficScreen(context, provider);
|
||||||
}
|
}
|
||||||
@@ -257,16 +299,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() {
|
void _showPermissionDialog() {
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
|
|
||||||
@@ -402,10 +434,164 @@ class _HomeScreenState extends State<HomeScreen>
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _buildMiniSignalBars({
|
void _showDeviceInfoSheet(BuildContext context, DeviceInfo deviceInfo) {
|
||||||
required int activeBars,
|
// Request self telemetry so it's fresh
|
||||||
required Color color,
|
context.read<ConnectionProvider>().requestSelfTelemetry();
|
||||||
}) {
|
|
||||||
|
showModalBottomSheet(
|
||||||
|
context: context,
|
||||||
|
shape: const RoundedRectangleBorder(
|
||||||
|
borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
|
||||||
|
),
|
||||||
|
builder: (context) => Consumer<ContactsProvider>(
|
||||||
|
builder: (context, contactsProvider, child) {
|
||||||
|
final telemetry = contactsProvider.selfTelemetry;
|
||||||
|
|
||||||
|
return SafeArea(
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.all(20),
|
||||||
|
child: Column(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
Container(
|
||||||
|
width: 40,
|
||||||
|
height: 4,
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: Theme.of(context).dividerColor,
|
||||||
|
borderRadius: BorderRadius.circular(2),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
Text(
|
||||||
|
deviceInfo.selfName ?? deviceInfo.deviceName ?? 'Device',
|
||||||
|
style: Theme.of(context).textTheme.titleMedium,
|
||||||
|
),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
_deviceInfoRow(
|
||||||
|
context,
|
||||||
|
Icons.bluetooth,
|
||||||
|
'BLE Signal',
|
||||||
|
deviceInfo.signalRssi != null
|
||||||
|
? '${deviceInfo.signalRssi} dBm'
|
||||||
|
: 'N/A',
|
||||||
|
),
|
||||||
|
if (deviceInfo.batteryPercent != null)
|
||||||
|
_deviceInfoRow(
|
||||||
|
context,
|
||||||
|
BatteryDisplayHelper.getBatteryIcon(
|
||||||
|
deviceInfo.batteryPercent!,
|
||||||
|
),
|
||||||
|
'Battery',
|
||||||
|
'${deviceInfo.batteryPercent!.round()}%',
|
||||||
|
),
|
||||||
|
if (deviceInfo.batteryMilliVolts != null)
|
||||||
|
_deviceInfoRow(
|
||||||
|
context,
|
||||||
|
Icons.bolt,
|
||||||
|
'Voltage',
|
||||||
|
'${(deviceInfo.batteryMilliVolts! / 1000).toStringAsFixed(2)}V',
|
||||||
|
),
|
||||||
|
if (deviceInfo.storageUsedKb != null &&
|
||||||
|
deviceInfo.storageTotalKb != null)
|
||||||
|
_deviceInfoRow(
|
||||||
|
context,
|
||||||
|
Icons.storage,
|
||||||
|
'Storage',
|
||||||
|
'${deviceInfo.storageUsedKb} / ${deviceInfo.storageTotalKb} KB',
|
||||||
|
),
|
||||||
|
if (deviceInfo.firmwareVersion != null)
|
||||||
|
_deviceInfoRow(
|
||||||
|
context,
|
||||||
|
Icons.system_update,
|
||||||
|
'Firmware',
|
||||||
|
'v${deviceInfo.firmwareVersion}',
|
||||||
|
),
|
||||||
|
if (deviceInfo.radioFreq != null)
|
||||||
|
_deviceInfoRow(
|
||||||
|
context,
|
||||||
|
Icons.radio,
|
||||||
|
'Frequency',
|
||||||
|
'${(deviceInfo.radioFreq! / 1000).toStringAsFixed(3)} MHz',
|
||||||
|
),
|
||||||
|
if (deviceInfo.txPower != null)
|
||||||
|
_deviceInfoRow(
|
||||||
|
context,
|
||||||
|
Icons.power,
|
||||||
|
'TX Power',
|
||||||
|
'${deviceInfo.txPower} dBm',
|
||||||
|
),
|
||||||
|
if (telemetry != null) ...[
|
||||||
|
const Divider(height: 24),
|
||||||
|
Text(
|
||||||
|
'Self Telemetry',
|
||||||
|
style: Theme.of(context).textTheme.titleSmall,
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
if (telemetry.temperature != null)
|
||||||
|
_deviceInfoRow(
|
||||||
|
context,
|
||||||
|
Icons.thermostat,
|
||||||
|
'Temperature',
|
||||||
|
'${telemetry.temperature!.toStringAsFixed(1)}°C',
|
||||||
|
),
|
||||||
|
if (telemetry.humidity != null)
|
||||||
|
_deviceInfoRow(
|
||||||
|
context,
|
||||||
|
Icons.water_drop,
|
||||||
|
'Humidity',
|
||||||
|
'${telemetry.humidity!.toStringAsFixed(1)}%',
|
||||||
|
),
|
||||||
|
if (telemetry.pressure != null)
|
||||||
|
_deviceInfoRow(
|
||||||
|
context,
|
||||||
|
Icons.compress,
|
||||||
|
'Pressure',
|
||||||
|
'${telemetry.pressure!.toStringAsFixed(1)} hPa',
|
||||||
|
),
|
||||||
|
if (telemetry.gpsLocation != null)
|
||||||
|
_deviceInfoRow(
|
||||||
|
context,
|
||||||
|
Icons.gps_fixed,
|
||||||
|
'GPS',
|
||||||
|
'${telemetry.gpsLocation!.latitude.toStringAsFixed(5)}, ${telemetry.gpsLocation!.longitude.toStringAsFixed(5)}',
|
||||||
|
),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
final inactive = Colors.grey.withValues(alpha: 0.3);
|
||||||
return Row(
|
return Row(
|
||||||
mainAxisSize: MainAxisSize.min,
|
mainAxisSize: MainAxisSize.min,
|
||||||
@@ -914,19 +1100,35 @@ class _HomeScreenState extends State<HomeScreen>
|
|||||||
final isTcpConnected = provider.connectionMode == ConnectionMode.tcp;
|
final isTcpConnected = provider.connectionMode == ConnectionMode.tcp;
|
||||||
|
|
||||||
if (!isConnected) {
|
if (!isConnected) {
|
||||||
// Disconnected state: show connect button
|
final buttonLabel = provider.isReconnecting
|
||||||
|
? '${provider.reconnectionAttempt}/${provider.maxReconnectionAttempts}'
|
||||||
|
: AppLocalizations.of(context)!.connect;
|
||||||
return Row(
|
return Row(
|
||||||
children: [
|
children: [
|
||||||
Expanded(
|
Expanded(
|
||||||
child: Text(
|
child: Column(
|
||||||
AppLocalizations.of(context)!.appTitle,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
style: const TextStyle(
|
mainAxisSize: MainAxisSize.min,
|
||||||
fontSize: 20,
|
children: [
|
||||||
fontWeight: FontWeight.bold,
|
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
|
onPressed: provider.isReconnecting
|
||||||
? null
|
? null
|
||||||
: () => _showConnectionDialog(context),
|
: () => _showConnectionDialog(context),
|
||||||
@@ -937,22 +1139,19 @@ class _HomeScreenState extends State<HomeScreen>
|
|||||||
child: CircularProgressIndicator(
|
child: CircularProgressIndicator(
|
||||||
strokeWidth: 2,
|
strokeWidth: 2,
|
||||||
valueColor: AlwaysStoppedAnimation<Color>(
|
valueColor: AlwaysStoppedAnimation<Color>(
|
||||||
Colors.black54,
|
Colors.white70,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
: Icon(Icons.bluetooth, size: 18),
|
: const Icon(Icons.add_link_rounded, size: 18),
|
||||||
label: Text(
|
label: Text(buttonLabel),
|
||||||
provider.isReconnecting
|
style: FilledButton.styleFrom(
|
||||||
? '${provider.reconnectionAttempt}/${provider.maxReconnectionAttempts}'
|
padding: const EdgeInsets.symmetric(
|
||||||
: AppLocalizations.of(context)!.connect,
|
horizontal: 16,
|
||||||
),
|
vertical: 12,
|
||||||
style: ElevatedButton.styleFrom(
|
),
|
||||||
backgroundColor: Colors.white,
|
|
||||||
foregroundColor: Colors.black87,
|
|
||||||
elevation: 0,
|
|
||||||
shape: RoundedRectangleBorder(
|
shape: RoundedRectangleBorder(
|
||||||
borderRadius: BorderRadius.circular(20),
|
borderRadius: BorderRadius.circular(16),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -1019,52 +1218,57 @@ class _HomeScreenState extends State<HomeScreen>
|
|||||||
overflow: TextOverflow.ellipsis,
|
overflow: TextOverflow.ellipsis,
|
||||||
),
|
),
|
||||||
const SizedBox(height: 2),
|
const SizedBox(height: 2),
|
||||||
Row(
|
GestureDetector(
|
||||||
mainAxisSize: MainAxisSize.min,
|
onTap: () =>
|
||||||
children: [
|
_showDeviceInfoSheet(context, deviceInfo),
|
||||||
Icon(
|
child: Row(
|
||||||
isTcpConnected
|
mainAxisSize: MainAxisSize.min,
|
||||||
? Icons.wifi_rounded
|
children: [
|
||||||
: Icons.bluetooth_connected_rounded,
|
Icon(
|
||||||
size: 13,
|
isTcpConnected
|
||||||
color: signalColor,
|
? Icons.wifi_rounded
|
||||||
),
|
: Icons.bluetooth_connected_rounded,
|
||||||
if (!isTcpConnected &&
|
size: 13,
|
||||||
deviceInfo.signalRssi != null) ...[
|
|
||||||
const SizedBox(width: 4),
|
|
||||||
_buildMiniSignalBars(
|
|
||||||
activeBars: BatteryDisplayHelper.getSignalBars(
|
|
||||||
deviceInfo.signalRssi!,
|
|
||||||
),
|
|
||||||
color: signalColor,
|
color: signalColor,
|
||||||
),
|
),
|
||||||
],
|
if (!isTcpConnected &&
|
||||||
if (deviceInfo.batteryPercent != null) ...[
|
deviceInfo.signalRssi != null) ...[
|
||||||
const SizedBox(width: 8),
|
const SizedBox(width: 4),
|
||||||
Icon(
|
_buildMiniSignalBars(
|
||||||
BatteryDisplayHelper.getBatteryIcon(
|
activeBars:
|
||||||
deviceInfo.batteryPercent!,
|
BatteryDisplayHelper.getSignalBars(
|
||||||
|
deviceInfo.signalRssi!,
|
||||||
|
),
|
||||||
|
color: signalColor,
|
||||||
),
|
),
|
||||||
size: 13,
|
],
|
||||||
color:
|
if (deviceInfo.batteryPercent != null) ...[
|
||||||
BatteryDisplayHelper.getBatteryColor(
|
const SizedBox(width: 8),
|
||||||
deviceInfo.batteryPercent!,
|
Icon(
|
||||||
),
|
BatteryDisplayHelper.getBatteryIcon(
|
||||||
),
|
deviceInfo.batteryPercent!,
|
||||||
const SizedBox(width: 2),
|
),
|
||||||
Text(
|
size: 13,
|
||||||
'${deviceInfo.batteryPercent!.round()}%',
|
|
||||||
style: TextStyle(
|
|
||||||
fontSize: 10,
|
|
||||||
fontWeight: FontWeight.w600,
|
|
||||||
color:
|
color:
|
||||||
BatteryDisplayHelper.getBatteryColor(
|
BatteryDisplayHelper.getBatteryColor(
|
||||||
deviceInfo.batteryPercent!,
|
deviceInfo.batteryPercent!,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
const SizedBox(width: 2),
|
||||||
|
Text(
|
||||||
|
'${deviceInfo.batteryPercent!.round()}%',
|
||||||
|
style: TextStyle(
|
||||||
|
fontSize: 10,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
color:
|
||||||
|
BatteryDisplayHelper.getBatteryColor(
|
||||||
|
deviceInfo.batteryPercent!,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
],
|
],
|
||||||
],
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
@@ -1162,9 +1366,9 @@ class _HomeScreenState extends State<HomeScreen>
|
|||||||
);
|
);
|
||||||
},
|
},
|
||||||
child: _buildCompactActivityIndicator(
|
child: _buildCompactActivityIndicator(
|
||||||
rxActive: provider.rxActivity,
|
rxActive: provider.rxActivity,
|
||||||
txActive: provider.txActivity,
|
txActive: provider.txActivity,
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
else
|
else
|
||||||
const SizedBox(width: 24),
|
const SizedBox(width: 24),
|
||||||
|
|||||||
@@ -27,7 +27,6 @@ T? _maybeProvider<T>(BuildContext context) {
|
|||||||
|
|
||||||
class LiveTrafficScreen extends StatefulWidget {
|
class LiveTrafficScreen extends StatefulWidget {
|
||||||
final List<BlePacketLog> Function() logReader;
|
final List<BlePacketLog> Function() logReader;
|
||||||
final int Function()? rxCountReader;
|
|
||||||
final Listenable? refreshListenable;
|
final Listenable? refreshListenable;
|
||||||
final DateTime Function() now;
|
final DateTime Function() now;
|
||||||
final VoidCallback? openPacketLogs;
|
final VoidCallback? openPacketLogs;
|
||||||
@@ -35,7 +34,6 @@ class LiveTrafficScreen extends StatefulWidget {
|
|||||||
const LiveTrafficScreen({
|
const LiveTrafficScreen({
|
||||||
super.key,
|
super.key,
|
||||||
required this.logReader,
|
required this.logReader,
|
||||||
this.rxCountReader,
|
|
||||||
this.refreshListenable,
|
this.refreshListenable,
|
||||||
DateTime Function()? now,
|
DateTime Function()? now,
|
||||||
this.openPacketLogs,
|
this.openPacketLogs,
|
||||||
@@ -49,7 +47,6 @@ class LiveTrafficScreen extends StatefulWidget {
|
|||||||
return LiveTrafficScreen(
|
return LiveTrafficScreen(
|
||||||
key: key,
|
key: key,
|
||||||
logReader: () => provider.bleService.packetLogs,
|
logReader: () => provider.bleService.packetLogs,
|
||||||
rxCountReader: () => provider.rxPacketCount,
|
|
||||||
refreshListenable: provider,
|
refreshListenable: provider,
|
||||||
openPacketLogs: openPacketLogs,
|
openPacketLogs: openPacketLogs,
|
||||||
);
|
);
|
||||||
@@ -118,15 +115,17 @@ class _LiveTrafficScreenState extends State<LiveTrafficScreen> {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
|
final logs = widget.logReader();
|
||||||
|
final totalRxDataCount = LiveTrafficSummary.countRxDataLogs(logs);
|
||||||
final unfilteredSnapshot = LiveTrafficSummary.fromLogs(
|
final unfilteredSnapshot = LiveTrafficSummary.fromLogs(
|
||||||
widget.logReader(),
|
logs,
|
||||||
now: widget.now(),
|
now: widget.now(),
|
||||||
clearedAt: _clearedAt,
|
clearedAt: _clearedAt,
|
||||||
preferredHashSize: _preferredHashSize,
|
preferredHashSize: _preferredHashSize,
|
||||||
window: _selectedWindow,
|
window: _selectedWindow,
|
||||||
);
|
);
|
||||||
final snapshot = LiveTrafficSummary.fromLogs(
|
final snapshot = LiveTrafficSummary.fromLogs(
|
||||||
widget.logReader(),
|
logs,
|
||||||
now: widget.now(),
|
now: widget.now(),
|
||||||
clearedAt: _clearedAt,
|
clearedAt: _clearedAt,
|
||||||
preferredHashSize: _preferredHashSize,
|
preferredHashSize: _preferredHashSize,
|
||||||
@@ -177,7 +176,7 @@ class _LiveTrafficScreenState extends State<LiveTrafficScreen> {
|
|||||||
children: [
|
children: [
|
||||||
_SummaryPanel(
|
_SummaryPanel(
|
||||||
snapshot: snapshot,
|
snapshot: snapshot,
|
||||||
totalRxCount: widget.rxCountReader?.call(),
|
totalRxCount: totalRxDataCount,
|
||||||
routeHashCounts: routeHashCounts,
|
routeHashCounts: routeHashCounts,
|
||||||
onWindowTap: () => _showWindowPicker(context),
|
onWindowTap: () => _showWindowPicker(context),
|
||||||
),
|
),
|
||||||
@@ -306,8 +305,48 @@ class _SummaryPanel extends StatelessWidget {
|
|||||||
LiveTrafficBusyness.active => 'Active',
|
LiveTrafficBusyness.active => 'Active',
|
||||||
LiveTrafficBusyness.busy => 'Busy',
|
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(
|
return Container(
|
||||||
|
width: double.infinity,
|
||||||
padding: const EdgeInsets.all(16),
|
padding: const EdgeInsets.all(16),
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
gradient: LinearGradient(
|
gradient: LinearGradient(
|
||||||
@@ -346,44 +385,26 @@ class _SummaryPanel extends StatelessWidget {
|
|||||||
],
|
],
|
||||||
),
|
),
|
||||||
const SizedBox(height: 14),
|
const SizedBox(height: 14),
|
||||||
Wrap(
|
LayoutBuilder(
|
||||||
spacing: 10,
|
builder: (context, constraints) {
|
||||||
runSpacing: 10,
|
const spacing = 10.0;
|
||||||
children: [
|
const minTileWidth = 150.0;
|
||||||
_MetricTile(
|
final columns =
|
||||||
label: AppLocalizations.of(context)!.rxPackets,
|
((constraints.maxWidth + spacing) / (minTileWidth + spacing))
|
||||||
value: '${snapshot.rxCount}',
|
.floor()
|
||||||
subtitle: totalRxCount == null
|
.clamp(1, metrics.length);
|
||||||
? _windowSummaryLabel(snapshot.windowDuration)
|
final tileWidth =
|
||||||
: 'Device total $totalRxCount',
|
(constraints.maxWidth - (spacing * (columns - 1))) / columns;
|
||||||
),
|
|
||||||
_MetricTile(
|
return Wrap(
|
||||||
label: AppLocalizations.of(context)!.rssi,
|
spacing: spacing,
|
||||||
value: snapshot.latestRssiDbm == null
|
runSpacing: spacing,
|
||||||
? 'No RX data'
|
children: [
|
||||||
: '${snapshot.latestRssiDbm} dBm',
|
for (final metric in metrics)
|
||||||
subtitle: snapshot.avgRssiDbm == null
|
SizedBox(width: tileWidth, child: metric),
|
||||||
? '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',
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
@@ -525,12 +546,14 @@ String _windowSummaryLabel(Duration duration) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
class _MetricTile extends StatelessWidget {
|
class _MetricTile extends StatelessWidget {
|
||||||
|
final Key? tileKey;
|
||||||
final String label;
|
final String label;
|
||||||
final String value;
|
final String value;
|
||||||
final String subtitle;
|
final String subtitle;
|
||||||
final String? footer;
|
final String? footer;
|
||||||
|
|
||||||
const _MetricTile({
|
const _MetricTile({
|
||||||
|
this.tileKey,
|
||||||
required this.label,
|
required this.label,
|
||||||
required this.value,
|
required this.value,
|
||||||
required this.subtitle,
|
required this.subtitle,
|
||||||
@@ -540,7 +563,7 @@ class _MetricTile extends StatelessWidget {
|
|||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return Container(
|
return Container(
|
||||||
width: 160,
|
key: tileKey,
|
||||||
height: 136,
|
height: 136,
|
||||||
padding: const EdgeInsets.all(12),
|
padding: const EdgeInsets.all(12),
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
@@ -949,7 +972,6 @@ class _LiveTrafficCard extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class _LiveTrafficPacketDetails {
|
class _LiveTrafficPacketDetails {
|
||||||
@@ -1105,7 +1127,6 @@ class _PacketInfoLine extends StatelessWidget {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
class _GeoPoint {
|
class _GeoPoint {
|
||||||
final double latitude;
|
final double latitude;
|
||||||
final double longitude;
|
final double longitude;
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ import '../services/voice_recorder_service.dart';
|
|||||||
import '../services/voice_codec_service.dart';
|
import '../services/voice_codec_service.dart';
|
||||||
import '../utils/toast_logger.dart';
|
import '../utils/toast_logger.dart';
|
||||||
import '../utils/key_comparison.dart';
|
import '../utils/key_comparison.dart';
|
||||||
|
import '../utils/contact_sorting.dart';
|
||||||
import '../utils/voice_message_parser.dart';
|
import '../utils/voice_message_parser.dart';
|
||||||
import '../utils/image_message_parser.dart';
|
import '../utils/image_message_parser.dart';
|
||||||
import '../utils/tictactoe_message_parser.dart';
|
import '../utils/tictactoe_message_parser.dart';
|
||||||
@@ -299,27 +300,27 @@ class _MessagesTabState extends State<MessagesTab> {
|
|||||||
final contactsProvider = context.read<ContactsProvider>();
|
final contactsProvider = context.read<ContactsProvider>();
|
||||||
final normalizedQuery = query.trim().toLowerCase();
|
final normalizedQuery = query.trim().toLowerCase();
|
||||||
final contacts =
|
final contacts =
|
||||||
contactsProvider.contacts
|
contactsProvider.chatContacts.where((contact) {
|
||||||
.where((contact) => contact.type == ContactType.chat)
|
if (normalizedQuery.isEmpty) return true;
|
||||||
.where((contact) {
|
return contact.displayName.toLowerCase().contains(normalizedQuery);
|
||||||
if (normalizedQuery.isEmpty) return true;
|
}).toList()..sort((a, b) {
|
||||||
return contact.displayName.toLowerCase().contains(
|
final primary = compareContactsByFavouriteThenLastSeen(a, b);
|
||||||
normalizedQuery,
|
if (primary != 0) {
|
||||||
);
|
return primary;
|
||||||
})
|
}
|
||||||
.toList()
|
|
||||||
..sort((a, b) {
|
final aName = a.displayName.toLowerCase();
|
||||||
final aName = a.displayName.toLowerCase();
|
final bName = b.displayName.toLowerCase();
|
||||||
final bName = b.displayName.toLowerCase();
|
final aStarts =
|
||||||
final aStarts =
|
normalizedQuery.isNotEmpty && aName.startsWith(normalizedQuery);
|
||||||
normalizedQuery.isNotEmpty && aName.startsWith(normalizedQuery);
|
final bStarts =
|
||||||
final bStarts =
|
normalizedQuery.isNotEmpty && bName.startsWith(normalizedQuery);
|
||||||
normalizedQuery.isNotEmpty && bName.startsWith(normalizedQuery);
|
if (aStarts != bStarts) {
|
||||||
if (aStarts != bStarts) {
|
return aStarts ? -1 : 1;
|
||||||
return aStarts ? -1 : 1;
|
}
|
||||||
}
|
|
||||||
return aName.compareTo(bName);
|
return compareContactsByDisplayName(a, b);
|
||||||
});
|
});
|
||||||
|
|
||||||
return contacts.take(8).toList(growable: false);
|
return contacts.take(8).toList(growable: false);
|
||||||
}
|
}
|
||||||
@@ -408,16 +409,33 @@ class _MessagesTabState extends State<MessagesTab> {
|
|||||||
final contactsProvider = context.read<ContactsProvider>();
|
final contactsProvider = context.read<ContactsProvider>();
|
||||||
final messagesProvider = context.read<MessagesProvider>();
|
final messagesProvider = context.read<MessagesProvider>();
|
||||||
|
|
||||||
// Filter contacts by type
|
final contacts = List<Contact>.from(contactsProvider.chatContacts)
|
||||||
final contacts = contactsProvider.contacts
|
..sort((a, b) {
|
||||||
.where((c) => c.type == ContactType.chat)
|
final primary = compareContactsByFavouriteThenLastSeen(a, b);
|
||||||
.toList();
|
if (primary != 0) {
|
||||||
final rooms = contactsProvider.contacts
|
return primary;
|
||||||
.where((c) => c.type == ContactType.room)
|
}
|
||||||
.toList();
|
|
||||||
final channels = contactsProvider.contacts
|
return compareContactsByDisplayName(a, b);
|
||||||
.where((c) => c.type == ContactType.channel)
|
});
|
||||||
.toList();
|
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(
|
showModalBottomSheet(
|
||||||
context: context,
|
context: context,
|
||||||
@@ -534,7 +552,10 @@ class _MessagesTabState extends State<MessagesTab> {
|
|||||||
}).firstOrNull;
|
}).firstOrNull;
|
||||||
|
|
||||||
if (recipient == null) {
|
if (recipient == null) {
|
||||||
ToastLogger.error(context, AppLocalizations.of(context)!.cannotReplyContactNotFound);
|
ToastLogger.error(
|
||||||
|
context,
|
||||||
|
AppLocalizations.of(context)!.cannotReplyContactNotFound,
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -563,13 +584,19 @@ class _MessagesTabState extends State<MessagesTab> {
|
|||||||
} else {
|
} else {
|
||||||
final senderPrefix = message.senderPublicKeyPrefix;
|
final senderPrefix = message.senderPublicKeyPrefix;
|
||||||
if (senderPrefix == null || senderPrefix.length < 6) {
|
if (senderPrefix == null || senderPrefix.length < 6) {
|
||||||
ToastLogger.error(context, AppLocalizations.of(context)!.cannotReplySenderMissing);
|
ToastLogger.error(
|
||||||
|
context,
|
||||||
|
AppLocalizations.of(context)!.cannotReplySenderMissing,
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
recipient = contactsProvider.findContactByPrefix(senderPrefix);
|
recipient = contactsProvider.findContactByPrefix(senderPrefix);
|
||||||
if (recipient == null) {
|
if (recipient == null) {
|
||||||
ToastLogger.error(context, AppLocalizations.of(context)!.cannotReplyContactNotFound);
|
ToastLogger.error(
|
||||||
|
context,
|
||||||
|
AppLocalizations.of(context)!.cannotReplyContactNotFound,
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -640,7 +667,6 @@ class _MessagesTabState extends State<MessagesTab> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
_textController.clear();
|
_textController.clear();
|
||||||
_focusNode.unfocus();
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Check destination type and send accordingly
|
// Check destination type and send accordingly
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import '../models/contact.dart';
|
|||||||
import '../providers/connection_provider.dart';
|
import '../providers/connection_provider.dart';
|
||||||
import '../providers/contacts_provider.dart';
|
import '../providers/contacts_provider.dart';
|
||||||
import '../providers/sensors_provider.dart';
|
import '../providers/sensors_provider.dart';
|
||||||
|
import '../widgets/sensors/bthome_met_history_sheet.dart';
|
||||||
import '../widgets/sensors/sensor_telemetry_card.dart';
|
import '../widgets/sensors/sensor_telemetry_card.dart';
|
||||||
import '../l10n/app_localizations.dart';
|
import '../l10n/app_localizations.dart';
|
||||||
|
|
||||||
@@ -100,7 +101,10 @@ class _SensorsTabState extends State<SensorsTab> {
|
|||||||
Future<void> _showAddSensorSheet(BuildContext context) async {
|
Future<void> _showAddSensorSheet(BuildContext context) async {
|
||||||
final sensorsProvider = context.read<SensorsProvider>();
|
final sensorsProvider = context.read<SensorsProvider>();
|
||||||
final contactsProvider = context.read<ContactsProvider>();
|
final contactsProvider = context.read<ContactsProvider>();
|
||||||
final candidates = sensorsProvider.availableCandidates(contactsProvider);
|
final candidates = sensorsProvider.availableCandidates(
|
||||||
|
contactsProvider,
|
||||||
|
connectionProvider: context.read<ConnectionProvider>(),
|
||||||
|
);
|
||||||
|
|
||||||
await showModalBottomSheet<void>(
|
await showModalBottomSheet<void>(
|
||||||
context: context,
|
context: context,
|
||||||
@@ -127,7 +131,11 @@ class _SensorsTabState extends State<SensorsTab> {
|
|||||||
'Add sensor node',
|
'Add sensor node',
|
||||||
style: TextStyle(fontWeight: FontWeight.bold),
|
style: TextStyle(fontWeight: FontWeight.bold),
|
||||||
),
|
),
|
||||||
subtitle: Text(AppLocalizations.of(context)!.pickARelayOrNodeToWatchInSensors),
|
subtitle: Text(
|
||||||
|
AppLocalizations.of(
|
||||||
|
context,
|
||||||
|
)!.pickARelayOrNodeToWatchInSensors,
|
||||||
|
),
|
||||||
),
|
),
|
||||||
...candidates.map(
|
...candidates.map(
|
||||||
(contact) => ListTile(
|
(contact) => ListTile(
|
||||||
@@ -275,58 +283,141 @@ class _SensorsTabState extends State<SensorsTab> {
|
|||||||
onPressed: () => _showAddSensorSheet(context),
|
onPressed: () => _showAddSensorSheet(context),
|
||||||
child: const Icon(Icons.add),
|
child: const Icon(Icons.add),
|
||||||
),
|
),
|
||||||
body: Consumer2<SensorsProvider, ContactsProvider>(
|
body: Consumer3<SensorsProvider, ContactsProvider, ConnectionProvider>(
|
||||||
builder: (context, sensorsProvider, contactsProvider, child) {
|
builder:
|
||||||
final watchedKeys = sensorsProvider.watchedSensorKeys;
|
(
|
||||||
|
context,
|
||||||
|
sensorsProvider,
|
||||||
|
contactsProvider,
|
||||||
|
connectionProvider,
|
||||||
|
child,
|
||||||
|
) {
|
||||||
|
final displayKeys = sensorsProvider.displaySensorKeys(
|
||||||
|
contactsProvider: contactsProvider,
|
||||||
|
connectionProvider: connectionProvider,
|
||||||
|
);
|
||||||
|
final hasPersistedSensors =
|
||||||
|
sensorsProvider.watchedSensorKeys.isNotEmpty;
|
||||||
|
|
||||||
return RefreshIndicator(
|
Widget buildSensorCard(String key, int index) {
|
||||||
onRefresh: () => _refreshAll(context),
|
final contact = sensorsProvider.contactForDisplay(
|
||||||
child: ListView(
|
key,
|
||||||
padding: const EdgeInsets.fromLTRB(16, 16, 16, 96),
|
contactsProvider: contactsProvider,
|
||||||
children: [
|
connectionProvider: connectionProvider,
|
||||||
if (watchedKeys.isEmpty)
|
);
|
||||||
const _EmptySensorsState()
|
final availableFieldKeys = sensorMetricKeysFor(contact);
|
||||||
else
|
final visibleFields = sensorsProvider.effectiveVisibleFieldsFor(
|
||||||
...watchedKeys.map((key) {
|
key,
|
||||||
Contact? contact;
|
availableFieldKeys,
|
||||||
for (final entry in contactsProvider.contacts) {
|
);
|
||||||
if (entry.publicKeyHex == key) {
|
|
||||||
contact = entry;
|
return Padding(
|
||||||
break;
|
key: ValueKey<String>('sensor_card_$key'),
|
||||||
}
|
padding: EdgeInsets.only(
|
||||||
}
|
bottom: index == displayKeys.length - 1 ? 0 : 12,
|
||||||
final availableFieldKeys = sensorMetricKeysFor(contact);
|
),
|
||||||
final visibleFields = sensorsProvider
|
child: Row(
|
||||||
.effectiveVisibleFieldsFor(key, availableFieldKeys);
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
return SensorTelemetryCard(
|
children: [
|
||||||
contact: contact,
|
Expanded(
|
||||||
state: sensorsProvider.stateFor(key),
|
child: SensorTelemetryCard(
|
||||||
visibleFields: visibleFields,
|
contact: contact,
|
||||||
fieldOrder: sensorsProvider.metricOrderFor(
|
state: sensorsProvider.stateFor(key),
|
||||||
key,
|
visibleFields: visibleFields,
|
||||||
availableFieldKeys,
|
fieldOrder: sensorsProvider.metricOrderFor(
|
||||||
|
key,
|
||||||
|
availableFieldKeys,
|
||||||
|
),
|
||||||
|
labelOverrides: sensorsProvider.labelOverridesFor(
|
||||||
|
key,
|
||||||
|
),
|
||||||
|
fieldSpans: {
|
||||||
|
for (final field in visibleFields)
|
||||||
|
field: sensorsProvider.fieldSpanFor(key, field),
|
||||||
|
},
|
||||||
|
onRemove: hasPersistedSensors
|
||||||
|
? () async {
|
||||||
|
await sensorsProvider.removeSensor(key);
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
onCustomize: () =>
|
||||||
|
_showMetricSelector(context, key, contact),
|
||||||
|
onShowMetHistory: (contact) =>
|
||||||
|
showBTHomeMetHistorySheet(
|
||||||
|
context,
|
||||||
|
contact: contact,
|
||||||
|
),
|
||||||
|
onRefresh: () => sensorsProvider.refreshSensor(
|
||||||
|
publicKeyHex: key,
|
||||||
|
contactsProvider: contactsProvider,
|
||||||
|
connectionProvider: connectionProvider,
|
||||||
|
),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
labelOverrides: sensorsProvider.labelOverridesFor(key),
|
if (hasPersistedSensors) ...[
|
||||||
fieldSpans: {
|
const SizedBox(width: 8),
|
||||||
for (final field in visibleFields)
|
Padding(
|
||||||
field: sensorsProvider.fieldSpanFor(key, field),
|
padding: const EdgeInsets.only(top: 20),
|
||||||
},
|
child: ReorderableDragStartListener(
|
||||||
onRemove: () async {
|
index: index,
|
||||||
await sensorsProvider.removeSensor(key);
|
child: Tooltip(
|
||||||
},
|
message: 'Move card',
|
||||||
onCustomize: () =>
|
child: Container(
|
||||||
_showMetricSelector(context, key, contact),
|
decoration: BoxDecoration(
|
||||||
onRefresh: () => sensorsProvider.refreshSensor(
|
color: Theme.of(
|
||||||
publicKeyHex: key,
|
context,
|
||||||
contactsProvider: contactsProvider,
|
).colorScheme.surfaceContainerHighest,
|
||||||
connectionProvider: context.read<ConnectionProvider>(),
|
borderRadius: BorderRadius.circular(12),
|
||||||
|
),
|
||||||
|
padding: const EdgeInsets.symmetric(
|
||||||
|
horizontal: 8,
|
||||||
|
vertical: 12,
|
||||||
|
),
|
||||||
|
child: Icon(
|
||||||
|
Icons.drag_indicator,
|
||||||
|
color: Theme.of(
|
||||||
|
context,
|
||||||
|
).colorScheme.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return RefreshIndicator(
|
||||||
|
onRefresh: () => _refreshAll(context),
|
||||||
|
child: displayKeys.isEmpty
|
||||||
|
? ListView(
|
||||||
|
physics: const AlwaysScrollableScrollPhysics(),
|
||||||
|
padding: const EdgeInsets.fromLTRB(16, 16, 16, 96),
|
||||||
|
children: const [_EmptySensorsState()],
|
||||||
|
)
|
||||||
|
: hasPersistedSensors
|
||||||
|
? ReorderableListView.builder(
|
||||||
|
buildDefaultDragHandles: false,
|
||||||
|
physics: const AlwaysScrollableScrollPhysics(),
|
||||||
|
padding: const EdgeInsets.fromLTRB(16, 16, 16, 96),
|
||||||
|
itemCount: displayKeys.length,
|
||||||
|
onReorder: (oldIndex, newIndex) =>
|
||||||
|
sensorsProvider.reorderSensors(oldIndex, newIndex),
|
||||||
|
itemBuilder: (context, index) =>
|
||||||
|
buildSensorCard(displayKeys[index], index),
|
||||||
|
)
|
||||||
|
: ListView(
|
||||||
|
physics: const AlwaysScrollableScrollPhysics(),
|
||||||
|
padding: const EdgeInsets.fromLTRB(16, 16, 16, 96),
|
||||||
|
children: [
|
||||||
|
for (var i = 0; i < displayKeys.length; i++)
|
||||||
|
buildSensorCard(displayKeys[i], i),
|
||||||
|
],
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}),
|
},
|
||||||
],
|
|
||||||
),
|
|
||||||
);
|
|
||||||
},
|
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -406,6 +497,12 @@ class _SensorCustomizeView extends StatelessWidget {
|
|||||||
labelOverrides: sensorsProvider.labelOverridesFor(
|
labelOverrides: sensorsProvider.labelOverridesFor(
|
||||||
publicKeyHex,
|
publicKeyHex,
|
||||||
),
|
),
|
||||||
|
onShowMetHistory: contact == null
|
||||||
|
? null
|
||||||
|
: (contact) => showBTHomeMetHistorySheet(
|
||||||
|
context,
|
||||||
|
contact: contact,
|
||||||
|
),
|
||||||
fieldSpans: {
|
fieldSpans: {
|
||||||
for (final field in visibleFields)
|
for (final field in visibleFields)
|
||||||
field: sensorsProvider.fieldSpanFor(publicKeyHex, field),
|
field: sensorsProvider.fieldSpanFor(publicKeyHex, field),
|
||||||
@@ -876,55 +973,8 @@ class _EmptySensorsState extends StatefulWidget {
|
|||||||
}
|
}
|
||||||
|
|
||||||
class _EmptySensorsStateState extends State<_EmptySensorsState> {
|
class _EmptySensorsStateState extends State<_EmptySensorsState> {
|
||||||
bool _discoveryTriggered = false;
|
|
||||||
bool _discoveryInProgress = false;
|
|
||||||
|
|
||||||
@override
|
|
||||||
void initState() {
|
|
||||||
super.initState();
|
|
||||||
// Auto-trigger sensor discovery when the empty state is shown
|
|
||||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
|
||||||
_autoDiscover();
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _autoDiscover() async {
|
|
||||||
if (_discoveryTriggered || !mounted) return;
|
|
||||||
final connectionProvider = context.read<ConnectionProvider>();
|
|
||||||
if (!connectionProvider.deviceInfo.isConnected) return;
|
|
||||||
|
|
||||||
_discoveryTriggered = true;
|
|
||||||
setState(() => _discoveryInProgress = true);
|
|
||||||
try {
|
|
||||||
await connectionProvider.discoverNodeType(advertType: 4);
|
|
||||||
} finally {
|
|
||||||
if (mounted) setState(() => _discoveryInProgress = false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _discoverSensors() async {
|
|
||||||
if (_discoveryInProgress || !mounted) return;
|
|
||||||
final connectionProvider = context.read<ConnectionProvider>();
|
|
||||||
if (!connectionProvider.deviceInfo.isConnected) return;
|
|
||||||
|
|
||||||
setState(() => _discoveryInProgress = true);
|
|
||||||
try {
|
|
||||||
await connectionProvider.discoverNodeType(advertType: 4);
|
|
||||||
if (mounted) {
|
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
|
||||||
SnackBar(content: Text(AppLocalizations.of(context)!.sensorDiscoverySent)),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
if (mounted) setState(() => _discoveryInProgress = false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final isConnected =
|
|
||||||
context.watch<ConnectionProvider>().deviceInfo.isConnected;
|
|
||||||
|
|
||||||
return Padding(
|
return Padding(
|
||||||
padding: const EdgeInsets.symmetric(vertical: 64),
|
padding: const EdgeInsets.symmetric(vertical: 64),
|
||||||
child: Column(
|
child: Column(
|
||||||
@@ -951,29 +1001,10 @@ class _EmptySensorsStateState extends State<_EmptySensorsState> {
|
|||||||
const Padding(
|
const Padding(
|
||||||
padding: EdgeInsets.symmetric(horizontal: 24),
|
padding: EdgeInsets.symmetric(horizontal: 24),
|
||||||
child: Text(
|
child: Text(
|
||||||
'Use + to add discovered relays or nodes. Pull down to refresh telemetry after adding them.',
|
'Use + to add discovered relays or nodes. Your device will appear here automatically when available.',
|
||||||
textAlign: TextAlign.center,
|
textAlign: TextAlign.center,
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(height: 20),
|
|
||||||
FilledButton.icon(
|
|
||||||
onPressed: isConnected && !_discoveryInProgress
|
|
||||||
? _discoverSensors
|
|
||||||
: null,
|
|
||||||
icon: _discoveryInProgress
|
|
||||||
? const SizedBox(
|
|
||||||
width: 16,
|
|
||||||
height: 16,
|
|
||||||
child: CircularProgressIndicator(
|
|
||||||
strokeWidth: 2,
|
|
||||||
color: Colors.white,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
: const Icon(Icons.sensors_outlined),
|
|
||||||
label: Text(_discoveryInProgress
|
|
||||||
? 'Discovering...'
|
|
||||||
: 'Discover Sensors'),
|
|
||||||
),
|
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -190,9 +190,11 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
|||||||
_isDeveloperModeEnabled = false;
|
_isDeveloperModeEnabled = false;
|
||||||
_versionTapCount = 0;
|
_versionTapCount = 0;
|
||||||
});
|
});
|
||||||
ScaffoldMessenger.of(
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
context,
|
SnackBar(
|
||||||
).showSnackBar(SnackBar(content: Text(AppLocalizations.of(context)!.developerModeDisabled)));
|
content: Text(AppLocalizations.of(context)!.developerModeDisabled),
|
||||||
|
),
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -204,9 +206,11 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
|||||||
_isDeveloperModeEnabled = true;
|
_isDeveloperModeEnabled = true;
|
||||||
_versionTapCount = 0;
|
_versionTapCount = 0;
|
||||||
});
|
});
|
||||||
ScaffoldMessenger.of(
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
context,
|
SnackBar(
|
||||||
).showSnackBar(SnackBar(content: Text(AppLocalizations.of(context)!.developerModeEnabled)));
|
content: Text(AppLocalizations.of(context)!.developerModeEnabled),
|
||||||
|
),
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -559,7 +563,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
|||||||
if (mounted) {
|
if (mounted) {
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
SnackBar(
|
SnackBar(
|
||||||
content: Text(AppLocalizations.of(context)!.updateCheckIsOnlyAvailableOnAndroid),
|
content: Text(
|
||||||
|
AppLocalizations.of(context)!.updateCheckIsOnlyAvailableOnAndroid,
|
||||||
|
),
|
||||||
backgroundColor: Colors.orange,
|
backgroundColor: Colors.orange,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
@@ -584,7 +590,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
|||||||
if (!updateInfo.isAvailable) {
|
if (!updateInfo.isAvailable) {
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
SnackBar(
|
SnackBar(
|
||||||
content: Text(AppLocalizations.of(context)!.youAreRunningTheLatestVersion),
|
content: Text(
|
||||||
|
AppLocalizations.of(context)!.youAreRunningTheLatestVersion,
|
||||||
|
),
|
||||||
backgroundColor: Colors.green,
|
backgroundColor: Colors.green,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
@@ -594,7 +602,11 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
|||||||
if (updateInfo.downloadUrl == null) {
|
if (updateInfo.downloadUrl == null) {
|
||||||
ScaffoldMessenger.of(context).showSnackBar(
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
SnackBar(
|
SnackBar(
|
||||||
content: Text(AppLocalizations.of(context)!.updateAvailableButDownloadUrlNotFound),
|
content: Text(
|
||||||
|
AppLocalizations.of(
|
||||||
|
context,
|
||||||
|
)!.updateAvailableButDownloadUrlNotFound,
|
||||||
|
),
|
||||||
backgroundColor: Colors.orange,
|
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'),
|
_buildSectionHeader('Messaging'),
|
||||||
_buildSettingsCard([
|
_buildSettingsCard([
|
||||||
ListTile(
|
ListTile(
|
||||||
@@ -1205,7 +1311,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
|||||||
Consumer<AppProvider>(
|
Consumer<AppProvider>(
|
||||||
builder: (context, appProvider, child) => SwitchListTile(
|
builder: (context, appProvider, child) => SwitchListTile(
|
||||||
secondary: Icon(Icons.route),
|
secondary: Icon(Icons.route),
|
||||||
title: Text(AppLocalizations.of(context)!.nearestRepeaterFallback),
|
title: Text(
|
||||||
|
AppLocalizations.of(context)!.nearestRepeaterFallback,
|
||||||
|
),
|
||||||
subtitle: const Text(
|
subtitle: const Text(
|
||||||
'After normal retries fail, try one final resend through the nearest repeater',
|
'After normal retries fail, try one final resend through the nearest repeater',
|
||||||
),
|
),
|
||||||
@@ -1234,7 +1342,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
|||||||
'Clear Messages',
|
'Clear Messages',
|
||||||
style: TextStyle(color: Colors.red),
|
style: TextStyle(color: Colors.red),
|
||||||
),
|
),
|
||||||
subtitle: Text(AppLocalizations.of(context)!.deleteAllStoredMessageHistory),
|
subtitle: Text(
|
||||||
|
AppLocalizations.of(context)!.deleteAllStoredMessageHistory,
|
||||||
|
),
|
||||||
onTap: _clearMessages,
|
onTap: _clearMessages,
|
||||||
),
|
),
|
||||||
Consumer<AppProvider>(
|
Consumer<AppProvider>(
|
||||||
@@ -1344,7 +1454,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
|||||||
builder: (context, drawingProvider, child) => SwitchListTile(
|
builder: (context, drawingProvider, child) => SwitchListTile(
|
||||||
secondary: Icon(Icons.fmd_good_outlined),
|
secondary: Icon(Icons.fmd_good_outlined),
|
||||||
title: Text(AppLocalizations.of(context)!.showSarMarkersLabel),
|
title: Text(AppLocalizations.of(context)!.showSarMarkersLabel),
|
||||||
subtitle: Text(AppLocalizations.of(context)!.displaySarMarkersOnTheMainMap),
|
subtitle: Text(
|
||||||
|
AppLocalizations.of(context)!.displaySarMarkersOnTheMainMap,
|
||||||
|
),
|
||||||
value: drawingProvider.showSarMarkers,
|
value: drawingProvider.showSarMarkers,
|
||||||
onChanged: (value) {
|
onChanged: (value) {
|
||||||
drawingProvider.toggleSarMarkers();
|
drawingProvider.toggleSarMarkers();
|
||||||
@@ -1354,7 +1466,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
|||||||
Consumer<MapProvider>(
|
Consumer<MapProvider>(
|
||||||
builder: (context, mapProvider, child) => SwitchListTile(
|
builder: (context, mapProvider, child) => SwitchListTile(
|
||||||
secondary: Icon(Icons.timeline),
|
secondary: Icon(Icons.timeline),
|
||||||
title: Text(AppLocalizations.of(context)!.showAllContactTrailsLabel),
|
title: Text(
|
||||||
|
AppLocalizations.of(context)!.showAllContactTrailsLabel,
|
||||||
|
),
|
||||||
subtitle: const Text(
|
subtitle: const Text(
|
||||||
'Display location trails for all contacts that have history',
|
'Display location trails for all contacts that have history',
|
||||||
),
|
),
|
||||||
@@ -1420,7 +1534,11 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
|||||||
builder: (context, appProvider, child) => SwitchListTile(
|
builder: (context, appProvider, child) => SwitchListTile(
|
||||||
secondary: Icon(Icons.compress),
|
secondary: Icon(Icons.compress),
|
||||||
title: Text(AppLocalizations.of(context)!.voiceCompressor),
|
title: Text(AppLocalizations.of(context)!.voiceCompressor),
|
||||||
subtitle: Text(AppLocalizations.of(context)!.balancesQuietAndLoudSpeechLevels),
|
subtitle: Text(
|
||||||
|
AppLocalizations.of(
|
||||||
|
context,
|
||||||
|
)!.balancesQuietAndLoudSpeechLevels,
|
||||||
|
),
|
||||||
value: appProvider.isVoiceCompressorEnabled,
|
value: appProvider.isVoiceCompressorEnabled,
|
||||||
onChanged: (value) async {
|
onChanged: (value) async {
|
||||||
await appProvider.toggleVoiceCompressorEnabled(value);
|
await appProvider.toggleVoiceCompressorEnabled(value);
|
||||||
@@ -1431,7 +1549,11 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
|||||||
builder: (context, appProvider, child) => SwitchListTile(
|
builder: (context, appProvider, child) => SwitchListTile(
|
||||||
secondary: Icon(Icons.speed),
|
secondary: Icon(Icons.speed),
|
||||||
title: Text(AppLocalizations.of(context)!.voiceLimiter),
|
title: Text(AppLocalizations.of(context)!.voiceLimiter),
|
||||||
subtitle: Text(AppLocalizations.of(context)!.preventsClippingPeaksBeforeEncoding),
|
subtitle: Text(
|
||||||
|
AppLocalizations.of(
|
||||||
|
context,
|
||||||
|
)!.preventsClippingPeaksBeforeEncoding,
|
||||||
|
),
|
||||||
value: appProvider.isVoiceLimiterEnabled,
|
value: appProvider.isVoiceLimiterEnabled,
|
||||||
onChanged: (value) async {
|
onChanged: (value) async {
|
||||||
await appProvider.toggleVoiceLimiterEnabled(value);
|
await appProvider.toggleVoiceLimiterEnabled(value);
|
||||||
@@ -1442,7 +1564,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
|||||||
builder: (context, appProvider, child) => SwitchListTile(
|
builder: (context, appProvider, child) => SwitchListTile(
|
||||||
secondary: Icon(Icons.auto_fix_high),
|
secondary: Icon(Icons.auto_fix_high),
|
||||||
title: Text(AppLocalizations.of(context)!.micAutoGain),
|
title: Text(AppLocalizations.of(context)!.micAutoGain),
|
||||||
subtitle: Text(AppLocalizations.of(context)!.letsTheRecorderAdjustInputLevel),
|
subtitle: Text(
|
||||||
|
AppLocalizations.of(context)!.letsTheRecorderAdjustInputLevel,
|
||||||
|
),
|
||||||
value: appProvider.isVoiceAutoGainEnabled,
|
value: appProvider.isVoiceAutoGainEnabled,
|
||||||
onChanged: (value) async {
|
onChanged: (value) async {
|
||||||
await appProvider.toggleVoiceAutoGainEnabled(value);
|
await appProvider.toggleVoiceAutoGainEnabled(value);
|
||||||
@@ -1478,7 +1602,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
|||||||
Consumer<AppProvider>(
|
Consumer<AppProvider>(
|
||||||
builder: (context, appProvider, child) => SwitchListTile(
|
builder: (context, appProvider, child) => SwitchListTile(
|
||||||
secondary: Icon(Icons.content_cut),
|
secondary: Icon(Icons.content_cut),
|
||||||
title: Text(AppLocalizations.of(context)!.trimSilenceInVoiceMessages),
|
title: Text(
|
||||||
|
AppLocalizations.of(context)!.trimSilenceInVoiceMessages,
|
||||||
|
),
|
||||||
subtitle: const Text(
|
subtitle: const Text(
|
||||||
'Removes long silent parts before sending voice',
|
'Removes long silent parts before sending voice',
|
||||||
),
|
),
|
||||||
@@ -1648,7 +1774,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
|||||||
),
|
),
|
||||||
ListTile(
|
ListTile(
|
||||||
leading: Icon(Icons.timer),
|
leading: Icon(Icons.timer),
|
||||||
title: Text(AppLocalizations.of(context)!.activeuseUpdateInterval),
|
title: Text(
|
||||||
|
AppLocalizations.of(context)!.activeuseUpdateInterval,
|
||||||
|
),
|
||||||
subtitle: Text('$_fastLocationActiveCadenceSeconds s'),
|
subtitle: Text('$_fastLocationActiveCadenceSeconds s'),
|
||||||
trailing: const Icon(Icons.chevron_right),
|
trailing: const Icon(Icons.chevron_right),
|
||||||
onTap: _editFastLocationActiveCadence,
|
onTap: _editFastLocationActiveCadence,
|
||||||
|
|||||||
143
lib/services/bthome_met_history.dart
Normal file
143
lib/services/bthome_met_history.dart
Normal file
@@ -0,0 +1,143 @@
|
|||||||
|
import '../models/contact.dart';
|
||||||
|
|
||||||
|
enum BTHomeMetMeasurement {
|
||||||
|
temperature(1, 'Temperature', '°C'),
|
||||||
|
humidity(2, 'Humidity', '%'),
|
||||||
|
windSpeed(3, 'Wind speed', 'm/s'),
|
||||||
|
gust(4, 'Wind gust', 'm/s'),
|
||||||
|
rain(5, 'Rain', 'mm');
|
||||||
|
|
||||||
|
const BTHomeMetMeasurement(this.id, this.label, this.unit);
|
||||||
|
|
||||||
|
final int id;
|
||||||
|
final String label;
|
||||||
|
final String unit;
|
||||||
|
|
||||||
|
static BTHomeMetMeasurement? fromId(int id) {
|
||||||
|
for (final value in BTHomeMetMeasurement.values) {
|
||||||
|
if (value.id == id) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class BTHomeMetHistoryPage {
|
||||||
|
const BTHomeMetHistoryPage({
|
||||||
|
required this.measurement,
|
||||||
|
required this.page,
|
||||||
|
required this.values,
|
||||||
|
});
|
||||||
|
|
||||||
|
final BTHomeMetMeasurement measurement;
|
||||||
|
final int page;
|
||||||
|
final List<double> values;
|
||||||
|
|
||||||
|
double? get latest => values.isEmpty ? null : values.last;
|
||||||
|
double? get minimum => values.isEmpty
|
||||||
|
? null
|
||||||
|
: values.reduce((left, right) => left < right ? left : right);
|
||||||
|
double? get maximum => values.isEmpty
|
||||||
|
? null
|
||||||
|
: values.reduce((left, right) => left > right ? left : right);
|
||||||
|
}
|
||||||
|
|
||||||
|
class BTHomeMetHistoryFormatException implements Exception {
|
||||||
|
const BTHomeMetHistoryFormatException(this.message);
|
||||||
|
|
||||||
|
final String message;
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() => message;
|
||||||
|
}
|
||||||
|
|
||||||
|
class BTHomeMetHistoryParser {
|
||||||
|
static BTHomeMetHistoryPage parse(String text) {
|
||||||
|
final parts = text
|
||||||
|
.trim()
|
||||||
|
.split(',')
|
||||||
|
.map((part) => part.trim())
|
||||||
|
.toList(growable: false);
|
||||||
|
if (parts.length < 3) {
|
||||||
|
throw const BTHomeMetHistoryFormatException(
|
||||||
|
'MET history response is too short.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
final measurementId = int.tryParse(parts[0]);
|
||||||
|
final page = int.tryParse(parts[1]);
|
||||||
|
final count = int.tryParse(parts[2]);
|
||||||
|
if (measurementId == null || page == null || count == null) {
|
||||||
|
throw const BTHomeMetHistoryFormatException(
|
||||||
|
'MET history header is invalid.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
final measurement = BTHomeMetMeasurement.fromId(measurementId);
|
||||||
|
if (measurement == null) {
|
||||||
|
throw BTHomeMetHistoryFormatException(
|
||||||
|
'Unsupported MET history measurement id: $measurementId',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (count < 0) {
|
||||||
|
throw const BTHomeMetHistoryFormatException(
|
||||||
|
'MET history sample count is invalid.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (parts.length != count + 3) {
|
||||||
|
throw BTHomeMetHistoryFormatException(
|
||||||
|
'MET history sample count mismatch: expected $count values, got ${parts.length - 3}.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
final values = <double>[];
|
||||||
|
for (final part in parts.skip(3)) {
|
||||||
|
final value = double.tryParse(part);
|
||||||
|
if (value == null) {
|
||||||
|
throw BTHomeMetHistoryFormatException(
|
||||||
|
'Invalid MET history sample value: $part',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
values.add(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
return BTHomeMetHistoryPage(
|
||||||
|
measurement: measurement,
|
||||||
|
page: page,
|
||||||
|
values: List<double>.unmodifiable(values),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
List<BTHomeMetMeasurement> bTHomeMetMeasurementsForContact(Contact? contact) {
|
||||||
|
final telemetry = contact?.telemetry;
|
||||||
|
if (telemetry == null) {
|
||||||
|
return const <BTHomeMetMeasurement>[];
|
||||||
|
}
|
||||||
|
|
||||||
|
final measurements = <BTHomeMetMeasurement>[
|
||||||
|
if (telemetry.temperature != null) BTHomeMetMeasurement.temperature,
|
||||||
|
if (telemetry.humidity != null) BTHomeMetMeasurement.humidity,
|
||||||
|
];
|
||||||
|
|
||||||
|
final extraSensorData = telemetry.extraSensorData;
|
||||||
|
if (extraSensorData != null) {
|
||||||
|
if (extraSensorData.keys.any(
|
||||||
|
(key) => key.startsWith('speed_') || key.startsWith('signed_speed_'),
|
||||||
|
)) {
|
||||||
|
measurements.add(BTHomeMetMeasurement.windSpeed);
|
||||||
|
}
|
||||||
|
if (extraSensorData.keys.any((key) => key.startsWith('gust_'))) {
|
||||||
|
measurements.add(BTHomeMetMeasurement.gust);
|
||||||
|
}
|
||||||
|
if (extraSensorData.keys.any((key) => key.startsWith('rain_'))) {
|
||||||
|
measurements.add(BTHomeMetMeasurement.rain);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return List<BTHomeMetMeasurement>.unmodifiable(measurements);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool supportsBTHomeMetHistory(Contact? contact) =>
|
||||||
|
bTHomeMetMeasurementsForContact(contact).isNotEmpty;
|
||||||
@@ -141,6 +141,18 @@ class LiveTrafficSummary {
|
|||||||
|
|
||||||
const 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(
|
static LiveTrafficSnapshot fromLogs(
|
||||||
Iterable<BlePacketLog> logs, {
|
Iterable<BlePacketLog> logs, {
|
||||||
required DateTime now,
|
required DateTime now,
|
||||||
@@ -154,15 +166,14 @@ class LiveTrafficSummary {
|
|||||||
? clearedAt
|
? clearedAt
|
||||||
: windowStart;
|
: windowStart;
|
||||||
|
|
||||||
final recentLogs = logs
|
final recentLogs =
|
||||||
.where(
|
logs
|
||||||
(log) =>
|
.where(
|
||||||
log.direction == PacketDirection.rx &&
|
(log) =>
|
||||||
log.responseCode == logRxDataResponseCode &&
|
isRxDataLog(log) && !log.timestamp.isBefore(effectiveStart),
|
||||||
!log.timestamp.isBefore(effectiveStart),
|
)
|
||||||
)
|
.toList()
|
||||||
.toList()
|
..sort((a, b) => a.timestamp.compareTo(b.timestamp));
|
||||||
..sort((a, b) => a.timestamp.compareTo(b.timestamp));
|
|
||||||
|
|
||||||
final entries = <LiveTrafficEntry>[];
|
final entries = <LiveTrafficEntry>[];
|
||||||
for (final log in recentLogs) {
|
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;
|
const txCount = 0;
|
||||||
final totalCount = rxCount;
|
final totalCount = rxCount;
|
||||||
final packetsPerMinute =
|
final packetsPerMinute =
|
||||||
@@ -233,7 +246,9 @@ class LiveTrafficSummary {
|
|||||||
avgRssiDbm: rssiCount == 0 ? null : rssiSum / rssiCount,
|
avgRssiDbm: rssiCount == 0 ? null : rssiSum / rssiCount,
|
||||||
latestRssiDbm: latestRssiDbm,
|
latestRssiDbm: latestRssiDbm,
|
||||||
multiHopCount: multiHopCount,
|
multiHopCount: multiHopCount,
|
||||||
avgHopCount: hopCountSamples == 0 ? null : hopCountTotal / hopCountSamples,
|
avgHopCount: hopCountSamples == 0
|
||||||
|
? null
|
||||||
|
: hopCountTotal / hopCountSamples,
|
||||||
visibleEntries: visibleEntries,
|
visibleEntries: visibleEntries,
|
||||||
busyness: _busynessForPacketsPerMinute(packetsPerMinute),
|
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 {
|
class ProfileManager with ChangeNotifier {
|
||||||
static const String _profilesKey = 'profiles_library';
|
static const String _profilesKey = 'profiles_library';
|
||||||
static const String activeProfileIdKey = 'profiles_active_profile_id';
|
static const String activeProfileIdKey = 'profiles_active_profile_id';
|
||||||
|
static const String _deviceProfileDefaultsKey =
|
||||||
|
'profiles_device_active_profile_ids';
|
||||||
static const String _transferHistoryKey = 'profiles_transfer_history';
|
static const String _transferHistoryKey = 'profiles_transfer_history';
|
||||||
|
|
||||||
final List<ConfigProfile> _customProfiles = <ConfigProfile>[];
|
final List<ConfigProfile> _customProfiles = <ConfigProfile>[];
|
||||||
final List<ProfileTransferRecord> _transferHistory =
|
final List<ProfileTransferRecord> _transferHistory =
|
||||||
<ProfileTransferRecord>[];
|
<ProfileTransferRecord>[];
|
||||||
|
final Map<String, String> _deviceProfileDefaults = <String, String>{};
|
||||||
bool _isInitialized = false;
|
bool _isInitialized = false;
|
||||||
bool _profilesEnabled = false;
|
bool _profilesEnabled = false;
|
||||||
String _activeProfileId = ConfigProfile.defaultProfileId;
|
String _activeProfileId = ConfigProfile.defaultProfileId;
|
||||||
@@ -37,6 +40,19 @@ class ProfileManager with ChangeNotifier {
|
|||||||
_activeProfileId =
|
_activeProfileId =
|
||||||
prefs.getString(activeProfileIdKey) ?? ConfigProfile.defaultProfileId;
|
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);
|
final profilesJson = prefs.getString(_profilesKey);
|
||||||
if (profilesJson != null && profilesJson.isNotEmpty) {
|
if (profilesJson != null && profilesJson.isNotEmpty) {
|
||||||
final decoded = jsonDecode(profilesJson) as List<dynamic>;
|
final decoded = jsonDecode(profilesJson) as List<dynamic>;
|
||||||
@@ -90,9 +106,37 @@ class ProfileManager with ChangeNotifier {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Future<void> setActiveProfileId(String id) async {
|
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;
|
_activeProfileId = id;
|
||||||
final prefs = await SharedPreferences.getInstance();
|
final prefs = await SharedPreferences.getInstance();
|
||||||
await prefs.setString(activeProfileIdKey, id);
|
await prefs.setString(activeProfileIdKey, id);
|
||||||
|
if (deviceKey != null && deviceKey.isNotEmpty) {
|
||||||
|
_deviceProfileDefaults[deviceKey] = id;
|
||||||
|
await prefs.setString(
|
||||||
|
_deviceProfileDefaultsKey,
|
||||||
|
jsonEncode(_deviceProfileDefaults),
|
||||||
|
);
|
||||||
|
}
|
||||||
ProfileStorageScope.setScope(
|
ProfileStorageScope.setScope(
|
||||||
profilesEnabled: _profilesEnabled,
|
profilesEnabled: _profilesEnabled,
|
||||||
activeProfileId: _activeProfileId,
|
activeProfileId: _activeProfileId,
|
||||||
|
|||||||
@@ -14,11 +14,14 @@ import '../providers/drawing_provider.dart';
|
|||||||
import '../providers/map_provider.dart';
|
import '../providers/map_provider.dart';
|
||||||
import '../providers/messages_provider.dart';
|
import '../providers/messages_provider.dart';
|
||||||
import '../providers/sensors_provider.dart';
|
import '../providers/sensors_provider.dart';
|
||||||
|
import '../providers/voice_provider.dart';
|
||||||
|
import '../providers/image_provider.dart' as ip;
|
||||||
import 'app_config_snapshot_service.dart';
|
import 'app_config_snapshot_service.dart';
|
||||||
import 'contact_storage_service.dart';
|
import 'contact_storage_service.dart';
|
||||||
import 'device_config_applicator.dart';
|
import 'device_config_applicator.dart';
|
||||||
import 'message_storage_service.dart';
|
import 'message_storage_service.dart';
|
||||||
import 'profile_manager.dart';
|
import 'profile_manager.dart';
|
||||||
|
import 'profile_device_key_resolver.dart';
|
||||||
import 'profiles_feature_service.dart';
|
import 'profiles_feature_service.dart';
|
||||||
import 'map_workspace_snapshot_service.dart';
|
import 'map_workspace_snapshot_service.dart';
|
||||||
|
|
||||||
@@ -32,6 +35,8 @@ class ProfileWorkspaceCoordinator {
|
|||||||
required this.mapProvider,
|
required this.mapProvider,
|
||||||
required this.drawingProvider,
|
required this.drawingProvider,
|
||||||
required this.channelsProvider,
|
required this.channelsProvider,
|
||||||
|
required this.voiceProvider,
|
||||||
|
required this.imageProvider,
|
||||||
required this.appProvider,
|
required this.appProvider,
|
||||||
AppConfigSnapshotService? appConfigSnapshotService,
|
AppConfigSnapshotService? appConfigSnapshotService,
|
||||||
MapWorkspaceSnapshotService? mapWorkspaceSnapshotService,
|
MapWorkspaceSnapshotService? mapWorkspaceSnapshotService,
|
||||||
@@ -57,12 +62,15 @@ class ProfileWorkspaceCoordinator {
|
|||||||
final MapProvider mapProvider;
|
final MapProvider mapProvider;
|
||||||
final DrawingProvider drawingProvider;
|
final DrawingProvider drawingProvider;
|
||||||
final ChannelsProvider channelsProvider;
|
final ChannelsProvider channelsProvider;
|
||||||
|
final VoiceProvider voiceProvider;
|
||||||
|
final ip.ImageProvider imageProvider;
|
||||||
final AppProvider appProvider;
|
final AppProvider appProvider;
|
||||||
final AppConfigSnapshotService _appConfigSnapshotService;
|
final AppConfigSnapshotService _appConfigSnapshotService;
|
||||||
final MapWorkspaceSnapshotService _mapWorkspaceSnapshotService;
|
final MapWorkspaceSnapshotService _mapWorkspaceSnapshotService;
|
||||||
final DeviceConfigApplicator _deviceConfigApplicator;
|
final DeviceConfigApplicator _deviceConfigApplicator;
|
||||||
final MessageStorageService _messageStorageService;
|
final MessageStorageService _messageStorageService;
|
||||||
final ContactStorageService _contactStorageService;
|
final ContactStorageService _contactStorageService;
|
||||||
|
Future<void>? _deviceProfileSyncFuture;
|
||||||
|
|
||||||
Future<void> setProfilesEnabled(bool enabled) async {
|
Future<void> setProfilesEnabled(bool enabled) async {
|
||||||
final wasEnabled = profileManager.profilesEnabled;
|
final wasEnabled = profileManager.profilesEnabled;
|
||||||
@@ -77,6 +85,7 @@ class ProfileWorkspaceCoordinator {
|
|||||||
activeProfileId: enabled ? profileManager.activeProfileId : 'default',
|
activeProfileId: enabled ? profileManager.activeProfileId : 'default',
|
||||||
);
|
);
|
||||||
if (enabled) {
|
if (enabled) {
|
||||||
|
await _ensureProfileForCurrentDevice();
|
||||||
if (wasEnabled) {
|
if (wasEnabled) {
|
||||||
await openProfile(profileManager.activeProfileId);
|
await openProfile(profileManager.activeProfileId);
|
||||||
} else {
|
} else {
|
||||||
@@ -181,9 +190,13 @@ class ProfileWorkspaceCoordinator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Future<void> openProfile(String profileId) async {
|
Future<void> openProfile(String profileId) async {
|
||||||
|
final deviceKey = _currentDeviceProfileKey;
|
||||||
await _saveActiveCustomProfileSnapshot();
|
await _saveActiveCustomProfileSnapshot();
|
||||||
await connectionProvider.disconnect();
|
await connectionProvider.disconnect();
|
||||||
await profileManager.setActiveProfileId(profileId);
|
await profileManager.setActiveProfileIdForDevice(
|
||||||
|
profileId,
|
||||||
|
deviceKey: deviceKey,
|
||||||
|
);
|
||||||
await _switchRuntimeScope(profileId);
|
await _switchRuntimeScope(profileId);
|
||||||
|
|
||||||
final profile = await resolveProfile(profileId);
|
final profile = await resolveProfile(profileId);
|
||||||
@@ -271,6 +284,112 @@ class ProfileWorkspaceCoordinator {
|
|||||||
return imported;
|
return imported;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<void> syncActiveProfileForCurrentDevice() async {
|
||||||
|
if (!profileManager.profilesEnabled) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
final inFlightSync = _deviceProfileSyncFuture;
|
||||||
|
if (inFlightSync != null) {
|
||||||
|
await inFlightSync;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
final syncFuture = _syncActiveProfileForCurrentDeviceInternal();
|
||||||
|
_deviceProfileSyncFuture = syncFuture;
|
||||||
|
try {
|
||||||
|
await syncFuture;
|
||||||
|
} finally {
|
||||||
|
if (identical(_deviceProfileSyncFuture, syncFuture)) {
|
||||||
|
_deviceProfileSyncFuture = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _syncActiveProfileForCurrentDeviceInternal() async {
|
||||||
|
final deviceKey = _currentDeviceProfileKey;
|
||||||
|
if (deviceKey == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
final profile = await _ensureProfileForCurrentDevice();
|
||||||
|
final targetProfileId = profile.id;
|
||||||
|
if (targetProfileId == profileManager.activeProfileId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await _persistCurrentState();
|
||||||
|
await profileManager.setActiveProfileIdForDevice(
|
||||||
|
targetProfileId,
|
||||||
|
deviceKey: deviceKey,
|
||||||
|
);
|
||||||
|
await _switchRuntimeScope(targetProfileId);
|
||||||
|
|
||||||
|
await _appConfigSnapshotService.apply(
|
||||||
|
profile.sections.appSettings,
|
||||||
|
appProvider,
|
||||||
|
);
|
||||||
|
await _mapWorkspaceSnapshotService.apply(
|
||||||
|
profile.sections.mapWorkspace,
|
||||||
|
mapProvider: mapProvider,
|
||||||
|
drawingProvider: drawingProvider,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<ConfigProfile> _ensureProfileForCurrentDevice() async {
|
||||||
|
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 {
|
Future<void> _switchRuntimeScope(String profileId) async {
|
||||||
final runtimeProfilesEnabled = profileManager.profilesEnabled;
|
final runtimeProfilesEnabled = profileManager.profilesEnabled;
|
||||||
ProfileStorageScope.setScope(
|
ProfileStorageScope.setScope(
|
||||||
@@ -287,6 +406,8 @@ class ProfileWorkspaceCoordinator {
|
|||||||
await sensorsProvider.reloadProfileScopedState();
|
await sensorsProvider.reloadProfileScopedState();
|
||||||
await drawingProvider.reloadProfileScopedState();
|
await drawingProvider.reloadProfileScopedState();
|
||||||
await mapProvider.reloadProfileScopedState();
|
await mapProvider.reloadProfileScopedState();
|
||||||
|
await voiceProvider.reloadProfileScopedState();
|
||||||
|
await imageProvider.reloadProfileScopedState();
|
||||||
await appProvider.reloadProfileScopedSettings();
|
await appProvider.reloadProfileScopedSettings();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ class ProfilesFeatureService {
|
|||||||
|
|
||||||
static Future<bool> isEnabled() async {
|
static Future<bool> isEnabled() async {
|
||||||
final prefs = await SharedPreferences.getInstance();
|
final prefs = await SharedPreferences.getInstance();
|
||||||
return prefs.getBool(enabledKey) ?? false;
|
return prefs.getBool(enabledKey) ?? true;
|
||||||
}
|
}
|
||||||
|
|
||||||
static Future<void> setEnabled(bool enabled) async {
|
static Future<void> setEnabled(bool enabled) async {
|
||||||
@@ -15,7 +15,7 @@ class ProfilesFeatureService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
class ProfileStorageScope {
|
class ProfileStorageScope {
|
||||||
static bool _profilesEnabled = false;
|
static bool _profilesEnabled = true;
|
||||||
static String _activeProfileId = 'default';
|
static String _activeProfileId = 'default';
|
||||||
|
|
||||||
static Future<void> bootstrap({
|
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
File diff suppressed because it is too large
Load Diff
@@ -106,7 +106,10 @@ class SpectrumScanPanel extends StatelessWidget {
|
|||||||
color: theme.colorScheme.primary,
|
color: theme.colorScheme.primary,
|
||||||
label: AppLocalizations.of(context)!.quiet,
|
label: AppLocalizations.of(context)!.quiet,
|
||||||
),
|
),
|
||||||
_LegendChip(color: Colors.orange, label: AppLocalizations.of(context)!.moderate),
|
_LegendChip(
|
||||||
|
color: Colors.orange,
|
||||||
|
label: AppLocalizations.of(context)!.moderate,
|
||||||
|
),
|
||||||
_LegendChip(
|
_LegendChip(
|
||||||
color: theme.colorScheme.error,
|
color: theme.colorScheme.error,
|
||||||
label: AppLocalizations.of(context)!.busy,
|
label: AppLocalizations.of(context)!.busy,
|
||||||
@@ -147,7 +150,7 @@ class SpectrumScanPanel extends StatelessWidget {
|
|||||||
width: double.infinity,
|
width: double.infinity,
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
|
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
color: theme.colorScheme.surface.withValues(alpha: 0.7),
|
color: theme.colorScheme.surfaceContainerLow,
|
||||||
borderRadius: BorderRadius.circular(12),
|
borderRadius: BorderRadius.circular(12),
|
||||||
border: Border.all(color: theme.colorScheme.outlineVariant),
|
border: Border.all(color: theme.colorScheme.outlineVariant),
|
||||||
),
|
),
|
||||||
@@ -303,12 +306,7 @@ class _FrequencyRangePreview extends StatelessWidget {
|
|||||||
height: 108,
|
height: 108,
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
borderRadius: BorderRadius.circular(16),
|
borderRadius: BorderRadius.circular(16),
|
||||||
gradient: LinearGradient(
|
color: scheme.surfaceContainerLow,
|
||||||
colors: [
|
|
||||||
scheme.surface,
|
|
||||||
scheme.surfaceContainerHighest.withValues(alpha: 0.9),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
border: Border.all(color: scheme.outlineVariant),
|
border: Border.all(color: scheme.outlineVariant),
|
||||||
),
|
),
|
||||||
child: Stack(
|
child: Stack(
|
||||||
@@ -322,13 +320,7 @@ class _FrequencyRangePreview extends StatelessWidget {
|
|||||||
child: DecoratedBox(
|
child: DecoratedBox(
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
borderRadius: BorderRadius.circular(12),
|
borderRadius: BorderRadius.circular(12),
|
||||||
gradient: LinearGradient(
|
color: scheme.surfaceContainerHigh,
|
||||||
colors: [
|
|
||||||
scheme.primary.withValues(alpha: 0.12),
|
|
||||||
scheme.tertiary.withValues(alpha: 0.08),
|
|
||||||
scheme.primary.withValues(alpha: 0.12),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -341,7 +333,7 @@ class _FrequencyRangePreview extends StatelessWidget {
|
|||||||
child: DecoratedBox(
|
child: DecoratedBox(
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
borderRadius: BorderRadius.circular(12),
|
borderRadius: BorderRadius.circular(12),
|
||||||
color: scheme.primary.withValues(alpha: 0.20),
|
color: scheme.primaryContainer,
|
||||||
border: Border.all(color: scheme.primary),
|
border: Border.all(color: scheme.primary),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -355,7 +347,7 @@ class _FrequencyRangePreview extends StatelessWidget {
|
|||||||
child: DecoratedBox(
|
child: DecoratedBox(
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
borderRadius: BorderRadius.circular(999),
|
borderRadius: BorderRadius.circular(999),
|
||||||
color: scheme.tertiary.withValues(alpha: 0.32),
|
color: scheme.tertiaryContainer,
|
||||||
border: Border.all(color: scheme.tertiary),
|
border: Border.all(color: scheme.tertiary),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import 'package:latlong2/latlong.dart';
|
|||||||
import '../../../l10n/app_localizations.dart';
|
import '../../../l10n/app_localizations.dart';
|
||||||
import '../../../models/contact.dart';
|
import '../../../models/contact.dart';
|
||||||
import '../../../models/sar_marker.dart';
|
import '../../../models/sar_marker.dart';
|
||||||
|
import 'compass_math.dart';
|
||||||
|
|
||||||
/// Header component for the compass dialog showing compass rose,
|
/// Header component for the compass dialog showing compass rose,
|
||||||
/// heading, elevation, accuracy, and current location in multiple formats.
|
/// 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)!;
|
final l10n = AppLocalizations.of(context)!;
|
||||||
return Row(
|
return Row(
|
||||||
mainAxisAlignment: MainAxisAlignment.spaceAround,
|
mainAxisAlignment: MainAxisAlignment.spaceAround,
|
||||||
@@ -90,17 +95,13 @@ class CompassHeader extends StatelessWidget {
|
|||||||
_buildInfoCard(
|
_buildInfoCard(
|
||||||
context,
|
context,
|
||||||
l10n.elevation,
|
l10n.elevation,
|
||||||
position?.altitude != null
|
position?.altitude != null ? '${position!.altitude.round()}m' : '--',
|
||||||
? '${position!.altitude.round()}m'
|
|
||||||
: '--',
|
|
||||||
Icons.terrain,
|
Icons.terrain,
|
||||||
),
|
),
|
||||||
_buildInfoCard(
|
_buildInfoCard(
|
||||||
context,
|
context,
|
||||||
l10n.accuracy,
|
l10n.accuracy,
|
||||||
position?.accuracy != null
|
position?.accuracy != null ? '±${position!.accuracy.round()}m' : '--',
|
||||||
? '±${position!.accuracy.round()}m'
|
|
||||||
: '--',
|
|
||||||
Icons.gps_fixed,
|
Icons.gps_fixed,
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
@@ -108,21 +109,22 @@ class CompassHeader extends StatelessWidget {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Widget _buildInfoCard(
|
Widget _buildInfoCard(
|
||||||
BuildContext context, String label, String value, IconData icon) {
|
BuildContext context,
|
||||||
|
String label,
|
||||||
|
String value,
|
||||||
|
IconData icon,
|
||||||
|
) {
|
||||||
return Column(
|
return Column(
|
||||||
children: [
|
children: [
|
||||||
Icon(icon, size: 20, color: Theme.of(context).colorScheme.primary),
|
Icon(icon, size: 20, color: Theme.of(context).colorScheme.primary),
|
||||||
const SizedBox(height: 4),
|
const SizedBox(height: 4),
|
||||||
Text(
|
Text(
|
||||||
value,
|
value,
|
||||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
style: Theme.of(
|
||||||
fontWeight: FontWeight.bold,
|
context,
|
||||||
),
|
).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold),
|
||||||
),
|
|
||||||
Text(
|
|
||||||
label,
|
|
||||||
style: Theme.of(context).textTheme.bodySmall,
|
|
||||||
),
|
),
|
||||||
|
Text(label, style: Theme.of(context).textTheme.bodySmall),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -193,11 +195,16 @@ class _LargeCompassPainter extends CustomPainter {
|
|||||||
|
|
||||||
// Draw degree markers
|
// Draw degree markers
|
||||||
for (int i = 0; i < 360; i += 10) {
|
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 isCardinal = i % 90 == 0;
|
||||||
final isMajor = i % 30 == 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(
|
final start = Offset(
|
||||||
center.dx + startRadius * cos(angle),
|
center.dx + startRadius * cos(angle),
|
||||||
center.dy + startRadius * sin(angle),
|
center.dy + startRadius * sin(angle),
|
||||||
@@ -218,7 +225,10 @@ class _LargeCompassPainter extends CustomPainter {
|
|||||||
final textPainter = TextPainter(textDirection: TextDirection.ltr);
|
final textPainter = TextPainter(textDirection: TextDirection.ltr);
|
||||||
final directions = ['N', 'E', 'S', 'W'];
|
final directions = ['N', 'E', 'S', 'W'];
|
||||||
for (int i = 0; i < 4; i++) {
|
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 x = center.dx + (radius - 35) * cos(angle);
|
||||||
final y = center.dy + (radius - 35) * sin(angle);
|
final y = center.dy + (radius - 35) * sin(angle);
|
||||||
|
|
||||||
@@ -243,20 +253,25 @@ class _LargeCompassPainter extends CustomPainter {
|
|||||||
final contactsWithDistance = contacts
|
final contactsWithDistance = contacts
|
||||||
.where((c) => c.displayLocation != null)
|
.where((c) => c.displayLocation != null)
|
||||||
.map((contact) {
|
.map((contact) {
|
||||||
final bearing = _calculateBearing(
|
final bearing = _calculateBearing(
|
||||||
currentPosition!.latitude,
|
currentPosition!.latitude,
|
||||||
currentPosition!.longitude,
|
currentPosition!.longitude,
|
||||||
contact.displayLocation!.latitude,
|
contact.displayLocation!.latitude,
|
||||||
contact.displayLocation!.longitude,
|
contact.displayLocation!.longitude,
|
||||||
);
|
);
|
||||||
final distance = _calculateDistance(
|
final distance = _calculateDistance(
|
||||||
currentPosition!.latitude,
|
currentPosition!.latitude,
|
||||||
currentPosition!.longitude,
|
currentPosition!.longitude,
|
||||||
contact.displayLocation!.latitude,
|
contact.displayLocation!.latitude,
|
||||||
contact.displayLocation!.longitude,
|
contact.displayLocation!.longitude,
|
||||||
);
|
);
|
||||||
return {'contact': contact, 'bearing': bearing, 'distance': distance};
|
return {
|
||||||
}).toList();
|
'contact': contact,
|
||||||
|
'bearing': bearing,
|
||||||
|
'distance': distance,
|
||||||
|
};
|
||||||
|
})
|
||||||
|
.toList();
|
||||||
|
|
||||||
if (contactsWithDistance.isEmpty) return;
|
if (contactsWithDistance.isEmpty) return;
|
||||||
|
|
||||||
@@ -277,7 +292,8 @@ class _LargeCompassPainter extends CustomPainter {
|
|||||||
double normalizedDistance = (distance / baseDistance).clamp(0.0, 1.0);
|
double normalizedDistance = (distance / baseDistance).clamp(0.0, 1.0);
|
||||||
|
|
||||||
// Calculate contact position radius (from center to rim based on distance)
|
// 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
|
// Position of contact dot
|
||||||
final dotX = center.dx + contactRadius * cos(angle);
|
final dotX = center.dx + contactRadius * cos(angle);
|
||||||
@@ -288,11 +304,7 @@ class _LargeCompassPainter extends CustomPainter {
|
|||||||
..color = Colors.lightBlue.withValues(alpha: 0.3)
|
..color = Colors.lightBlue.withValues(alpha: 0.3)
|
||||||
..style = PaintingStyle.stroke
|
..style = PaintingStyle.stroke
|
||||||
..strokeWidth = 1.5;
|
..strokeWidth = 1.5;
|
||||||
canvas.drawLine(
|
canvas.drawLine(center, Offset(dotX, dotY), linePaint);
|
||||||
center,
|
|
||||||
Offset(dotX, dotY),
|
|
||||||
linePaint,
|
|
||||||
);
|
|
||||||
|
|
||||||
// Draw contact dot (size varies with zoom)
|
// Draw contact dot (size varies with zoom)
|
||||||
final dotSize = (6.0 * (1.0 + zoomLevel * 0.3)).clamp(4.0, 12.0);
|
final dotSize = (6.0 * (1.0 + zoomLevel * 0.3)).clamp(4.0, 12.0);
|
||||||
@@ -341,7 +353,10 @@ class _LargeCompassPainter extends CustomPainter {
|
|||||||
|
|
||||||
textPainter.paint(
|
textPainter.paint(
|
||||||
canvas,
|
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)
|
..color = markerColor.withValues(alpha: 0.3)
|
||||||
..style = PaintingStyle.stroke
|
..style = PaintingStyle.stroke
|
||||||
..strokeWidth = 2;
|
..strokeWidth = 2;
|
||||||
canvas.drawLine(
|
canvas.drawLine(center, Offset(dotX, dotY), linePaint);
|
||||||
center,
|
|
||||||
Offset(dotX, dotY),
|
|
||||||
linePaint,
|
|
||||||
);
|
|
||||||
|
|
||||||
// Draw SAR marker dot (slightly larger than contacts)
|
// Draw SAR marker dot (slightly larger than contacts)
|
||||||
final dotSize = (8.0 * (1.0 + zoomLevel * 0.3)).clamp(6.0, 14.0);
|
final dotSize = (8.0 * (1.0 + zoomLevel * 0.3)).clamp(6.0, 14.0);
|
||||||
@@ -472,7 +483,10 @@ class _LargeCompassPainter extends CustomPainter {
|
|||||||
|
|
||||||
textPainter.paint(
|
textPainter.paint(
|
||||||
canvas,
|
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);
|
canvas.drawPath(path, indicatorPaint);
|
||||||
}
|
}
|
||||||
|
|
||||||
double _calculateBearing(
|
double _calculateBearing(double lat1, double lon1, double lat2, double lon2) {
|
||||||
double lat1, double lon1, double lat2, double lon2) {
|
|
||||||
final dLon = (lon2 - lon1) * pi / 180;
|
final dLon = (lon2 - lon1) * pi / 180;
|
||||||
final lat1Rad = lat1 * pi / 180;
|
final lat1Rad = lat1 * pi / 180;
|
||||||
final lat2Rad = lat2 * pi / 180;
|
final lat2Rad = lat2 * pi / 180;
|
||||||
|
|
||||||
final y = sin(dLon) * cos(lat2Rad);
|
final y = sin(dLon) * cos(lat2Rad);
|
||||||
final x = cos(lat1Rad) * sin(lat2Rad) -
|
final x =
|
||||||
sin(lat1Rad) * cos(lat2Rad) * cos(dLon);
|
cos(lat1Rad) * sin(lat2Rad) - sin(lat1Rad) * cos(lat2Rad) * cos(dLon);
|
||||||
|
|
||||||
final bearing = atan2(y, x) * 180 / pi;
|
final bearing = atan2(y, x) * 180 / pi;
|
||||||
return (bearing + 360) % 360;
|
return (bearing + 360) % 360;
|
||||||
}
|
}
|
||||||
|
|
||||||
double _calculateDistance(
|
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
|
const R = 6371000; // Earth's radius in meters
|
||||||
final dLat = (lat2 - lat1) * pi / 180;
|
final dLat = (lat2 - lat1) * pi / 180;
|
||||||
final dLon = (lon2 - lon1) * 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(lat1 * pi / 180) *
|
||||||
cos(lat2 * pi / 180) *
|
cos(lat2 * pi / 180) *
|
||||||
sin(dLon / 2) *
|
sin(dLon / 2) *
|
||||||
@@ -572,7 +590,8 @@ class _LocationFormatToggleState extends State<_LocationFormatToggle> {
|
|||||||
final String displayText;
|
final String displayText;
|
||||||
|
|
||||||
if (_showDMS) {
|
if (_showDMS) {
|
||||||
displayText = '${_formatDMS(position.latitude, true)} ${_formatDMS(position.longitude, false)}';
|
displayText =
|
||||||
|
'${_formatDMS(position.latitude, true)} ${_formatDMS(position.longitude, false)}';
|
||||||
} else {
|
} else {
|
||||||
displayText = l10n.latLonFormat(
|
displayText = l10n.latLonFormat(
|
||||||
position.latitude.toStringAsFixed(5),
|
position.latitude.toStringAsFixed(5),
|
||||||
@@ -598,9 +617,9 @@ class _LocationFormatToggleState extends State<_LocationFormatToggle> {
|
|||||||
displayText,
|
displayText,
|
||||||
textAlign: TextAlign.center,
|
textAlign: TextAlign.center,
|
||||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||||
fontWeight: FontWeight.w600,
|
fontWeight: FontWeight.w600,
|
||||||
fontFamily: 'monospace',
|
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 'dart:math';
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
import 'compass/compass_math.dart';
|
||||||
|
|
||||||
class CompassWidget extends StatelessWidget {
|
class CompassWidget extends StatelessWidget {
|
||||||
final double heading;
|
final double heading;
|
||||||
@@ -21,9 +22,9 @@ class CompassWidget extends StatelessWidget {
|
|||||||
child: Stack(
|
child: Stack(
|
||||||
alignment: Alignment.center,
|
alignment: Alignment.center,
|
||||||
children: [
|
children: [
|
||||||
// Compass rose background - rotates to show true north at top
|
// Rotate the rose opposite the heading under the fixed needle.
|
||||||
Transform.rotate(
|
Transform.rotate(
|
||||||
angle: heading * pi / 180,
|
angle: compassRoseRotationRadians(heading),
|
||||||
child: CustomPaint(
|
child: CustomPaint(
|
||||||
size: const Size(40, 40),
|
size: const Size(40, 40),
|
||||||
painter: _CompassRosePainter(),
|
painter: _CompassRosePainter(),
|
||||||
@@ -76,9 +77,7 @@ class _CompassRosePainter extends CustomPainter {
|
|||||||
canvas.drawCircle(center, radius, paint);
|
canvas.drawCircle(center, radius, paint);
|
||||||
|
|
||||||
// Draw cardinal direction markers
|
// Draw cardinal direction markers
|
||||||
final textPainter = TextPainter(
|
final textPainter = TextPainter(textDirection: TextDirection.ltr);
|
||||||
textDirection: TextDirection.ltr,
|
|
||||||
);
|
|
||||||
|
|
||||||
final directions = ['N', 'E', 'S', 'W'];
|
final directions = ['N', 'E', 'S', 'W'];
|
||||||
for (int i = 0; i < 4; i++) {
|
for (int i = 0; i < 4; i++) {
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:flutter/services.dart';
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:flutter/gestures.dart';
|
||||||
import 'package:latlong2/latlong.dart';
|
import 'package:latlong2/latlong.dart';
|
||||||
import 'package:share_plus/share_plus.dart';
|
import 'package:share_plus/share_plus.dart';
|
||||||
import 'package:provider/provider.dart';
|
import 'package:provider/provider.dart';
|
||||||
|
import 'package:url_launcher/url_launcher.dart';
|
||||||
import '../../models/contact.dart';
|
import '../../models/contact.dart';
|
||||||
import '../../models/message.dart';
|
import '../../models/message.dart';
|
||||||
import '../../models/sar_marker.dart';
|
import '../../models/sar_marker.dart';
|
||||||
@@ -31,6 +33,7 @@ import '../../l10n/app_localizations.dart';
|
|||||||
import '../../utils/message_extensions.dart';
|
import '../../utils/message_extensions.dart';
|
||||||
import '../../utils/log_rx_route_decoder.dart';
|
import '../../utils/log_rx_route_decoder.dart';
|
||||||
import '../../models/message_transfer_details.dart';
|
import '../../models/message_transfer_details.dart';
|
||||||
|
import '../../screens/add_contact_screen.dart';
|
||||||
import 'voice_message_bubble.dart';
|
import 'voice_message_bubble.dart';
|
||||||
import 'image_message_bubble.dart';
|
import 'image_message_bubble.dart';
|
||||||
import 'tictactoe_message_bubble.dart';
|
import 'tictactoe_message_bubble.dart';
|
||||||
@@ -72,9 +75,28 @@ class MessageBubble extends StatefulWidget {
|
|||||||
}
|
}
|
||||||
|
|
||||||
class _MessageBubbleState extends State<MessageBubble> {
|
class _MessageBubbleState extends State<MessageBubble> {
|
||||||
|
static const int _meshcoreAdvertMinBytes = 98;
|
||||||
static final RegExp _mentionPattern = RegExp(r'@\[(.+?)\]');
|
static final RegExp _mentionPattern = RegExp(r'@\[(.+?)\]');
|
||||||
|
static final RegExp _linkPattern = RegExp(
|
||||||
|
r'(?:(?:https?:\/\/)|(?:www\.)|(?:meshcore:\/\/))[^\s<]+',
|
||||||
|
caseSensitive: false,
|
||||||
|
);
|
||||||
|
static final RegExp _rawMeshcoreAdvertPattern = RegExp(
|
||||||
|
r'(?<![0-9a-fA-F])[0-9a-fA-F]{196,}(?![0-9a-fA-F])',
|
||||||
|
);
|
||||||
|
static final RegExp _messageTokenPattern = RegExp(
|
||||||
|
r'@\[(.+?)\]|(?:(?:https?:\/\/)|(?:www\.)|(?:meshcore:\/\/))[^\s<]+|(?<![0-9a-fA-F])[0-9a-fA-F]{196,}(?![0-9a-fA-F])',
|
||||||
|
caseSensitive: false,
|
||||||
|
);
|
||||||
bool _isExpanded = false;
|
bool _isExpanded = false;
|
||||||
bool _showReceivedStats = false;
|
bool _showReceivedStats = false;
|
||||||
|
final List<TapGestureRecognizer> _linkRecognizers = [];
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_disposeLinkRecognizers();
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void didUpdateWidget(MessageBubble oldWidget) {
|
void didUpdateWidget(MessageBubble oldWidget) {
|
||||||
@@ -100,14 +122,108 @@ class _MessageBubbleState extends State<MessageBubble> {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void _disposeLinkRecognizers() {
|
||||||
|
for (final recognizer in _linkRecognizers) {
|
||||||
|
recognizer.dispose();
|
||||||
|
}
|
||||||
|
_linkRecognizers.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
String _trimTrailingUrlPunctuation(String value) {
|
||||||
|
var trimmed = value;
|
||||||
|
while (trimmed.isNotEmpty) {
|
||||||
|
final lastChar = trimmed[trimmed.length - 1];
|
||||||
|
final shouldTrim = switch (lastChar) {
|
||||||
|
'.' || ',' || '!' || '?' || ':' || ';' => true,
|
||||||
|
')' => '('.allMatches(trimmed).length < ')'.allMatches(trimmed).length,
|
||||||
|
']' => '['.allMatches(trimmed).length < ']'.allMatches(trimmed).length,
|
||||||
|
'}' => '{'.allMatches(trimmed).length < '}'.allMatches(trimmed).length,
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
if (!shouldTrim) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
trimmed = trimmed.substring(0, trimmed.length - 1);
|
||||||
|
}
|
||||||
|
return trimmed;
|
||||||
|
}
|
||||||
|
|
||||||
|
Uri? _parseMessageLink(String value) {
|
||||||
|
final trimmed = _trimTrailingUrlPunctuation(value);
|
||||||
|
if (trimmed.isEmpty) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_isRawMeshcoreAdvert(trimmed)) {
|
||||||
|
return Uri.parse('meshcore://$trimmed');
|
||||||
|
}
|
||||||
|
|
||||||
|
final normalized = trimmed.startsWith('www.')
|
||||||
|
? 'https://$trimmed'
|
||||||
|
: trimmed;
|
||||||
|
final uri = Uri.tryParse(normalized);
|
||||||
|
if (uri == null || !uri.hasScheme || uri.host.isEmpty) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return uri;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool _isRawMeshcoreAdvert(String value) {
|
||||||
|
if (!_rawMeshcoreAdvertPattern.hasMatch(value)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return value.length.isEven && value.length >= _meshcoreAdvertMinBytes * 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _openMessageLink(String rawUrl) async {
|
||||||
|
final uri = _parseMessageLink(rawUrl);
|
||||||
|
if (uri == null) {
|
||||||
|
ToastLogger.error(context, 'Invalid link');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (uri.scheme.toLowerCase() == 'meshcore') {
|
||||||
|
if (!mounted) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await Navigator.of(context).push(
|
||||||
|
MaterialPageRoute(
|
||||||
|
builder: (context) => AddContactScreen(initialAdvert: rawUrl),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (!await canLaunchUrl(uri)) {
|
||||||
|
if (!mounted) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
ToastLogger.error(context, 'Cannot open link');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await launchUrl(uri, mode: LaunchMode.externalApplication);
|
||||||
|
} catch (error) {
|
||||||
|
if (!mounted) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
ToastLogger.error(context, 'Failed to open link');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Widget _buildMessageTextContent(String text, TextStyle? baseBodyStyle) {
|
Widget _buildMessageTextContent(String text, TextStyle? baseBodyStyle) {
|
||||||
final matches = _mentionPattern.allMatches(text).toList();
|
_disposeLinkRecognizers();
|
||||||
|
|
||||||
|
final matches = _messageTokenPattern.allMatches(text).toList();
|
||||||
if (matches.isEmpty) {
|
if (matches.isEmpty) {
|
||||||
return Text(text, style: baseBodyStyle);
|
return Text(text, style: baseBodyStyle);
|
||||||
}
|
}
|
||||||
|
|
||||||
final textColor =
|
final textColor =
|
||||||
baseBodyStyle?.color ?? Theme.of(context).colorScheme.onSurface;
|
baseBodyStyle?.color ?? Theme.of(context).colorScheme.onSurface;
|
||||||
|
final linkColor = Theme.of(context).colorScheme.primary;
|
||||||
final mentionFontSize = (baseBodyStyle?.fontSize ?? 14) - 1;
|
final mentionFontSize = (baseBodyStyle?.fontSize ?? 14) - 1;
|
||||||
final backgroundColor = Theme.of(
|
final backgroundColor = Theme.of(
|
||||||
context,
|
context,
|
||||||
@@ -129,8 +245,9 @@ class _MessageBubbleState extends State<MessageBubble> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
final rawMatch = match.group(0) ?? '';
|
||||||
final mentionName = match.group(1)?.trim() ?? '';
|
final mentionName = match.group(1)?.trim() ?? '';
|
||||||
if (mentionName.isNotEmpty) {
|
if (_mentionPattern.hasMatch(rawMatch) && mentionName.isNotEmpty) {
|
||||||
spans.add(
|
spans.add(
|
||||||
WidgetSpan(
|
WidgetSpan(
|
||||||
alignment: PlaceholderAlignment.middle,
|
alignment: PlaceholderAlignment.middle,
|
||||||
@@ -154,8 +271,34 @@ class _MessageBubbleState extends State<MessageBubble> {
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
} else if (_linkPattern.hasMatch(rawMatch) ||
|
||||||
|
_isRawMeshcoreAdvert(rawMatch)) {
|
||||||
|
final trimmedUrl = _trimTrailingUrlPunctuation(rawMatch);
|
||||||
|
final trailingText = rawMatch.substring(trimmedUrl.length);
|
||||||
|
final uri = _parseMessageLink(rawMatch);
|
||||||
|
if (uri != null) {
|
||||||
|
final recognizer = TapGestureRecognizer()
|
||||||
|
..onTap = () => _openMessageLink(rawMatch);
|
||||||
|
_linkRecognizers.add(recognizer);
|
||||||
|
spans.add(
|
||||||
|
TextSpan(
|
||||||
|
text: trimmedUrl,
|
||||||
|
style: baseBodyStyle?.copyWith(
|
||||||
|
color: linkColor,
|
||||||
|
decoration: TextDecoration.underline,
|
||||||
|
decorationColor: linkColor,
|
||||||
|
),
|
||||||
|
recognizer: recognizer,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
if (trailingText.isNotEmpty) {
|
||||||
|
spans.add(TextSpan(text: trailingText, style: baseBodyStyle));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
spans.add(TextSpan(text: rawMatch, style: baseBodyStyle));
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
spans.add(TextSpan(text: match.group(0), style: baseBodyStyle));
|
spans.add(TextSpan(text: rawMatch, style: baseBodyStyle));
|
||||||
}
|
}
|
||||||
|
|
||||||
cursor = match.end;
|
cursor = match.end;
|
||||||
@@ -174,15 +317,22 @@ class _MessageBubbleState extends State<MessageBubble> {
|
|||||||
!widget.message.isSystemMessage) {
|
!widget.message.isSystemMessage) {
|
||||||
context.read<MessagesProvider>().markAsRead(widget.message.id);
|
context.read<MessagesProvider>().markAsRead(widget.message.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!widget.isCompact && !isSarMarker && !isDrawing) {
|
|
||||||
setState(() {
|
|
||||||
_showReceivedStats = !_showReceivedStats;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
widget.onTap?.call();
|
widget.onTap?.call();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void _handleBubbleDoubleTap({
|
||||||
|
required bool isSarMarker,
|
||||||
|
required bool isDrawing,
|
||||||
|
}) {
|
||||||
|
if (widget.isCompact || isSarMarker || isDrawing) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setState(() {
|
||||||
|
_showReceivedStats = !_showReceivedStats;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
Future<void> _retryFailedMessage(
|
Future<void> _retryFailedMessage(
|
||||||
BuildContext context,
|
BuildContext context,
|
||||||
Message failedMessage,
|
Message failedMessage,
|
||||||
@@ -684,7 +834,10 @@ class _MessageBubbleState extends State<MessageBubble> {
|
|||||||
|
|
||||||
void copyField(String value) {
|
void copyField(String value) {
|
||||||
Clipboard.setData(ClipboardData(text: value));
|
Clipboard.setData(ClipboardData(text: value));
|
||||||
ToastLogger.success(context, AppLocalizations.of(context)!.textCopiedToClipboard);
|
ToastLogger.success(
|
||||||
|
context,
|
||||||
|
AppLocalizations.of(context)!.textCopiedToClipboard,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
showModalBottomSheet(
|
showModalBottomSheet(
|
||||||
@@ -812,7 +965,9 @@ class _MessageBubbleState extends State<MessageBubble> {
|
|||||||
),
|
),
|
||||||
_detailRow(
|
_detailRow(
|
||||||
sheetContext,
|
sheetContext,
|
||||||
label: AppLocalizations.of(context)!.receivedRfc3339,
|
label: AppLocalizations.of(
|
||||||
|
context,
|
||||||
|
)!.receivedRfc3339,
|
||||||
value: _formatRfc3339(widget.message.receivedAt),
|
value: _formatRfc3339(widget.message.receivedAt),
|
||||||
onCopy: () => copyField(
|
onCopy: () => copyField(
|
||||||
_formatRfc3339(widget.message.receivedAt),
|
_formatRfc3339(widget.message.receivedAt),
|
||||||
@@ -821,14 +976,18 @@ class _MessageBubbleState extends State<MessageBubble> {
|
|||||||
if (widget.message.expectedAckTag != null)
|
if (widget.message.expectedAckTag != null)
|
||||||
_detailRow(
|
_detailRow(
|
||||||
sheetContext,
|
sheetContext,
|
||||||
label: AppLocalizations.of(context)!.expectedAckTag,
|
label: AppLocalizations.of(
|
||||||
|
context,
|
||||||
|
)!.expectedAckTag,
|
||||||
value: widget.message.expectedAckTag!
|
value: widget.message.expectedAckTag!
|
||||||
.toString(),
|
.toString(),
|
||||||
),
|
),
|
||||||
if (receptionDetails?.senderToReceiptMs != null)
|
if (receptionDetails?.senderToReceiptMs != null)
|
||||||
_detailRow(
|
_detailRow(
|
||||||
sheetContext,
|
sheetContext,
|
||||||
label: AppLocalizations.of(context)!.senderToReceipt,
|
label: AppLocalizations.of(
|
||||||
|
context,
|
||||||
|
)!.senderToReceipt,
|
||||||
value: _formatDurationMs(
|
value: _formatDurationMs(
|
||||||
receptionDetails!.senderToReceiptMs!,
|
receptionDetails!.senderToReceiptMs!,
|
||||||
),
|
),
|
||||||
@@ -836,7 +995,9 @@ class _MessageBubbleState extends State<MessageBubble> {
|
|||||||
if (receptionDetails?.estimatedTransmitMs != null)
|
if (receptionDetails?.estimatedTransmitMs != null)
|
||||||
_detailRow(
|
_detailRow(
|
||||||
sheetContext,
|
sheetContext,
|
||||||
label: AppLocalizations.of(context)!.estimatedTx,
|
label: AppLocalizations.of(
|
||||||
|
context,
|
||||||
|
)!.estimatedTx,
|
||||||
value: _formatDurationMs(
|
value: _formatDurationMs(
|
||||||
receptionDetails!.estimatedTransmitMs!,
|
receptionDetails!.estimatedTransmitMs!,
|
||||||
),
|
),
|
||||||
@@ -844,7 +1005,9 @@ class _MessageBubbleState extends State<MessageBubble> {
|
|||||||
if (receptionDetails?.postTransmitDelayMs != null)
|
if (receptionDetails?.postTransmitDelayMs != null)
|
||||||
_detailRow(
|
_detailRow(
|
||||||
sheetContext,
|
sheetContext,
|
||||||
label: AppLocalizations.of(context)!.posttxDelay,
|
label: AppLocalizations.of(
|
||||||
|
context,
|
||||||
|
)!.posttxDelay,
|
||||||
value: _formatDurationMs(
|
value: _formatDurationMs(
|
||||||
receptionDetails!.postTransmitDelayMs!,
|
receptionDetails!.postTransmitDelayMs!,
|
||||||
),
|
),
|
||||||
@@ -852,7 +1015,9 @@ class _MessageBubbleState extends State<MessageBubble> {
|
|||||||
if (widget.receivedCopies > 1)
|
if (widget.receivedCopies > 1)
|
||||||
_detailRow(
|
_detailRow(
|
||||||
sheetContext,
|
sheetContext,
|
||||||
label: AppLocalizations.of(context)!.receivedCopies,
|
label: AppLocalizations.of(
|
||||||
|
context,
|
||||||
|
)!.receivedCopies,
|
||||||
value: '${widget.receivedCopies}',
|
value: '${widget.receivedCopies}',
|
||||||
),
|
),
|
||||||
if (widget.message.suggestedTimeoutMs != null)
|
if (widget.message.suggestedTimeoutMs != null)
|
||||||
@@ -883,7 +1048,9 @@ class _MessageBubbleState extends State<MessageBubble> {
|
|||||||
if (widget.message.retryAttempt > 0)
|
if (widget.message.retryAttempt > 0)
|
||||||
_detailRow(
|
_detailRow(
|
||||||
sheetContext,
|
sheetContext,
|
||||||
label: AppLocalizations.of(context)!.retryAttempt,
|
label: AppLocalizations.of(
|
||||||
|
context,
|
||||||
|
)!.retryAttempt,
|
||||||
value: '${widget.message.retryAttempt}/4',
|
value: '${widget.message.retryAttempt}/4',
|
||||||
),
|
),
|
||||||
if (widget.message.lastRetryAt != null)
|
if (widget.message.lastRetryAt != null)
|
||||||
@@ -900,21 +1067,27 @@ class _MessageBubbleState extends State<MessageBubble> {
|
|||||||
if (widget.message.usedFloodFallback)
|
if (widget.message.usedFloodFallback)
|
||||||
_detailRow(
|
_detailRow(
|
||||||
sheetContext,
|
sheetContext,
|
||||||
label: AppLocalizations.of(context)!.floodFallback,
|
label: AppLocalizations.of(
|
||||||
|
context,
|
||||||
|
)!.floodFallback,
|
||||||
value: AppLocalizations.of(context)!.yes,
|
value: AppLocalizations.of(context)!.yes,
|
||||||
),
|
),
|
||||||
if (routeMetadata?.canonicalPath
|
if (routeMetadata?.canonicalPath
|
||||||
case final routePath?)
|
case final routePath?)
|
||||||
_detailRow(
|
_detailRow(
|
||||||
sheetContext,
|
sheetContext,
|
||||||
label: AppLocalizations.of(context)!.selectedPath,
|
label: AppLocalizations.of(
|
||||||
|
context,
|
||||||
|
)!.selectedPath,
|
||||||
value: routePath,
|
value: routePath,
|
||||||
onCopy: () => copyField(routePath),
|
onCopy: () => copyField(routePath),
|
||||||
),
|
),
|
||||||
if (retryResult != null)
|
if (retryResult != null)
|
||||||
_detailRow(
|
_detailRow(
|
||||||
sheetContext,
|
sheetContext,
|
||||||
label: AppLocalizations.of(context)!.retryResult,
|
label: AppLocalizations.of(
|
||||||
|
context,
|
||||||
|
)!.retryResult,
|
||||||
value: retryResult,
|
value: retryResult,
|
||||||
),
|
),
|
||||||
if (packetPathHex != null)
|
if (packetPathHex != null)
|
||||||
@@ -964,7 +1137,9 @@ class _MessageBubbleState extends State<MessageBubble> {
|
|||||||
if (recipientPrefixHex != null)
|
if (recipientPrefixHex != null)
|
||||||
_detailRow(
|
_detailRow(
|
||||||
sheetContext,
|
sheetContext,
|
||||||
label: AppLocalizations.of(context)!.recipientKey,
|
label: AppLocalizations.of(
|
||||||
|
context,
|
||||||
|
)!.recipientKey,
|
||||||
value: recipientPrefixHex,
|
value: recipientPrefixHex,
|
||||||
onCopy: () => copyField(recipientPrefixHex),
|
onCopy: () => copyField(recipientPrefixHex),
|
||||||
),
|
),
|
||||||
@@ -994,7 +1169,9 @@ class _MessageBubbleState extends State<MessageBubble> {
|
|||||||
if (voiceSession != null)
|
if (voiceSession != null)
|
||||||
_detailRow(
|
_detailRow(
|
||||||
sheetContext,
|
sheetContext,
|
||||||
label: AppLocalizations.of(context)!.sessionProgress,
|
label: AppLocalizations.of(
|
||||||
|
context,
|
||||||
|
)!.sessionProgress,
|
||||||
value:
|
value:
|
||||||
'${voiceSession.receivedCount}/${voiceSession.total} segments',
|
'${voiceSession.receivedCount}/${voiceSession.total} segments',
|
||||||
),
|
),
|
||||||
@@ -1009,14 +1186,18 @@ class _MessageBubbleState extends State<MessageBubble> {
|
|||||||
if (transferDetails != null)
|
if (transferDetails != null)
|
||||||
_detailRow(
|
_detailRow(
|
||||||
sheetContext,
|
sheetContext,
|
||||||
label: AppLocalizations.of(context)!.transfers,
|
label: AppLocalizations.of(
|
||||||
|
context,
|
||||||
|
)!.transfers,
|
||||||
value: '${transferDetails.totalTransfers}',
|
value: '${transferDetails.totalTransfers}',
|
||||||
),
|
),
|
||||||
if (transferDetails != null &&
|
if (transferDetails != null &&
|
||||||
transferDetails.downloaders.isNotEmpty)
|
transferDetails.downloaders.isNotEmpty)
|
||||||
_detailRow(
|
_detailRow(
|
||||||
sheetContext,
|
sheetContext,
|
||||||
label: AppLocalizations.of(context)!.downloadedBy,
|
label: AppLocalizations.of(
|
||||||
|
context,
|
||||||
|
)!.downloadedBy,
|
||||||
value: _formatDownloaderSummary(
|
value: _formatDownloaderSummary(
|
||||||
transferDetails,
|
transferDetails,
|
||||||
),
|
),
|
||||||
@@ -1024,7 +1205,9 @@ class _MessageBubbleState extends State<MessageBubble> {
|
|||||||
if (voiceTxEstimate > Duration.zero)
|
if (voiceTxEstimate > Duration.zero)
|
||||||
_detailRow(
|
_detailRow(
|
||||||
sheetContext,
|
sheetContext,
|
||||||
label: AppLocalizations.of(context)!.estimatedTx,
|
label: AppLocalizations.of(
|
||||||
|
context,
|
||||||
|
)!.estimatedTx,
|
||||||
value: voiceTxEstimate.inSeconds < 60
|
value: voiceTxEstimate.inSeconds < 60
|
||||||
? '~${voiceTxEstimate.inSeconds}s'
|
? '~${voiceTxEstimate.inSeconds}s'
|
||||||
: '~${voiceTxEstimate.inMinutes}m ${voiceTxEstimate.inSeconds % 60}s',
|
: '~${voiceTxEstimate.inMinutes}m ${voiceTxEstimate.inSeconds % 60}s',
|
||||||
@@ -1075,14 +1258,18 @@ class _MessageBubbleState extends State<MessageBubble> {
|
|||||||
if (transferDetails != null)
|
if (transferDetails != null)
|
||||||
_detailRow(
|
_detailRow(
|
||||||
sheetContext,
|
sheetContext,
|
||||||
label: AppLocalizations.of(context)!.transfers,
|
label: AppLocalizations.of(
|
||||||
|
context,
|
||||||
|
)!.transfers,
|
||||||
value: '${transferDetails.totalTransfers}',
|
value: '${transferDetails.totalTransfers}',
|
||||||
),
|
),
|
||||||
if (transferDetails != null &&
|
if (transferDetails != null &&
|
||||||
transferDetails.downloaders.isNotEmpty)
|
transferDetails.downloaders.isNotEmpty)
|
||||||
_detailRow(
|
_detailRow(
|
||||||
sheetContext,
|
sheetContext,
|
||||||
label: AppLocalizations.of(context)!.downloadedBy,
|
label: AppLocalizations.of(
|
||||||
|
context,
|
||||||
|
)!.downloadedBy,
|
||||||
value: _formatDownloaderSummary(
|
value: _formatDownloaderSummary(
|
||||||
transferDetails,
|
transferDetails,
|
||||||
),
|
),
|
||||||
@@ -1090,7 +1277,9 @@ class _MessageBubbleState extends State<MessageBubble> {
|
|||||||
if (imageTxEstimate > Duration.zero)
|
if (imageTxEstimate > Duration.zero)
|
||||||
_detailRow(
|
_detailRow(
|
||||||
sheetContext,
|
sheetContext,
|
||||||
label: AppLocalizations.of(context)!.estimatedTx,
|
label: AppLocalizations.of(
|
||||||
|
context,
|
||||||
|
)!.estimatedTx,
|
||||||
value: imageTxEstimate.inSeconds < 60
|
value: imageTxEstimate.inSeconds < 60
|
||||||
? '~${imageTxEstimate.inSeconds}s'
|
? '~${imageTxEstimate.inSeconds}s'
|
||||||
: '~${imageTxEstimate.inMinutes}m ${imageTxEstimate.inSeconds % 60}s',
|
: '~${imageTxEstimate.inMinutes}m ${imageTxEstimate.inSeconds % 60}s',
|
||||||
@@ -1438,7 +1627,10 @@ class _MessageBubbleState extends State<MessageBubble> {
|
|||||||
|
|
||||||
// Share the location
|
// Share the location
|
||||||
SharePlus.instance.share(
|
SharePlus.instance.share(
|
||||||
ShareParams(text: shareText, subject: AppLocalizations.of(context)!.sarLocationShare),
|
ShareParams(
|
||||||
|
text: shareText,
|
||||||
|
subject: AppLocalizations.of(context)!.sarLocationShare,
|
||||||
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1890,6 +2082,10 @@ class _MessageBubbleState extends State<MessageBubble> {
|
|||||||
isSarMarker: isSarMarker,
|
isSarMarker: isSarMarker,
|
||||||
isDrawing: message.isDrawing,
|
isDrawing: message.isDrawing,
|
||||||
),
|
),
|
||||||
|
onDoubleTap: () => _handleBubbleDoubleTap(
|
||||||
|
isSarMarker: isSarMarker,
|
||||||
|
isDrawing: message.isDrawing,
|
||||||
|
),
|
||||||
onLongPress: widget.isCompact
|
onLongPress: widget.isCompact
|
||||||
? null
|
? null
|
||||||
: () => _showMessageOptions(context),
|
: () => _showMessageOptions(context),
|
||||||
@@ -2779,10 +2975,8 @@ class _MessageBubbleState extends State<MessageBubble> {
|
|||||||
);
|
);
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
if (shouldShowSentChannelStats(
|
if (_showReceivedStats &&
|
||||||
message,
|
shouldShowSentChannelStats(message)) ...[
|
||||||
showReceivedStats: _showReceivedStats,
|
|
||||||
)) ...[
|
|
||||||
const SizedBox(height: 6),
|
const SizedBox(height: 6),
|
||||||
buildChannelEchoStatus(context, message),
|
buildChannelEchoStatus(context, message),
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import '../../models/message_route_metadata.dart';
|
|||||||
import '../../models/path_selection.dart';
|
import '../../models/path_selection.dart';
|
||||||
import '../../models/message_reception_details.dart';
|
import '../../models/message_reception_details.dart';
|
||||||
import '../../providers/messages_provider.dart';
|
import '../../providers/messages_provider.dart';
|
||||||
|
import '../../utils/link_quality.dart';
|
||||||
|
|
||||||
IconData getDeliveryStatusIcon(MessageDeliveryStatus status) {
|
IconData getDeliveryStatusIcon(MessageDeliveryStatus status) {
|
||||||
switch (status) {
|
switch (status) {
|
||||||
@@ -91,10 +92,7 @@ Widget buildChannelEchoStatus(BuildContext context, Message message) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
bool shouldShowSentChannelStats(
|
bool shouldShowSentChannelStats(Message message) {
|
||||||
Message message, {
|
|
||||||
required bool showReceivedStats,
|
|
||||||
}) {
|
|
||||||
if (!message.isSentMessage || !message.isChannelMessage) {
|
if (!message.isSentMessage || !message.isChannelMessage) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -104,7 +102,7 @@ bool shouldShowSentChannelStats(
|
|||||||
message.lastEchoRssiDbm != null ||
|
message.lastEchoRssiDbm != null ||
|
||||||
message.lastEchoSnrRaw != null ||
|
message.lastEchoSnrRaw != null ||
|
||||||
message.expectedAckTag != null;
|
message.expectedAckTag != null;
|
||||||
return showReceivedStats && hasSignalData;
|
return hasSignalData;
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget buildReceivedSignalStatus(
|
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
819
lib/widgets/sensors/bthome_met_history_sheet.dart
Normal file
819
lib/widgets/sensors/bthome_met_history_sheet.dart
Normal file
@@ -0,0 +1,819 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'dart:math' as math;
|
||||||
|
|
||||||
|
import 'package:fl_chart/fl_chart.dart';
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:meshcore_client/meshcore_client.dart' show Message;
|
||||||
|
import 'package:provider/provider.dart';
|
||||||
|
|
||||||
|
import '../../models/contact.dart';
|
||||||
|
import '../../providers/connection_provider.dart';
|
||||||
|
import '../../services/bthome_met_history.dart';
|
||||||
|
|
||||||
|
Future<void> showBTHomeMetHistorySheet(
|
||||||
|
BuildContext context, {
|
||||||
|
required Contact contact,
|
||||||
|
}) {
|
||||||
|
return showModalBottomSheet<void>(
|
||||||
|
context: context,
|
||||||
|
isScrollControlled: true,
|
||||||
|
showDragHandle: true,
|
||||||
|
builder: (sheetContext) => _BTHomeMetHistorySheet(contact: contact),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
class _BTHomeMetHistorySheet extends StatefulWidget {
|
||||||
|
const _BTHomeMetHistorySheet({required this.contact});
|
||||||
|
|
||||||
|
final Contact contact;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<_BTHomeMetHistorySheet> createState() => _BTHomeMetHistorySheetState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _BTHomeMetHistorySheetState extends State<_BTHomeMetHistorySheet> {
|
||||||
|
late final List<BTHomeMetMeasurement> _availableMeasurements;
|
||||||
|
late BTHomeMetMeasurement _selectedMeasurement;
|
||||||
|
BTHomeMetHistoryPage? _history;
|
||||||
|
bool _loading = true;
|
||||||
|
String? _error;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
_availableMeasurements = bTHomeMetMeasurementsForContact(widget.contact);
|
||||||
|
_selectedMeasurement = _availableMeasurements.isEmpty
|
||||||
|
? BTHomeMetMeasurement.temperature
|
||||||
|
: _availableMeasurements.first;
|
||||||
|
if (_availableMeasurements.isEmpty) {
|
||||||
|
_loading = false;
|
||||||
|
_error = 'No BTHome MET-compatible telemetry is available for this node.';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
unawaited(_loadHistory(measurement: _selectedMeasurement, page: 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _loadHistory({
|
||||||
|
required BTHomeMetMeasurement measurement,
|
||||||
|
required int page,
|
||||||
|
}) async {
|
||||||
|
final connectionProvider = context.read<ConnectionProvider>();
|
||||||
|
final previousOnMessageReceived = connectionProvider.onMessageReceived;
|
||||||
|
String? responseText;
|
||||||
|
|
||||||
|
void onMessage(Message message) {
|
||||||
|
previousOnMessageReceived?.call(message);
|
||||||
|
if (_matchesContact(message)) {
|
||||||
|
responseText = message.text;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
connectionProvider.onMessageReceived = onMessage;
|
||||||
|
|
||||||
|
if (mounted) {
|
||||||
|
setState(() {
|
||||||
|
_loading = true;
|
||||||
|
_error = null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
final sent = await connectionProvider.sendTextMessage(
|
||||||
|
contactPublicKey: widget.contact.publicKey,
|
||||||
|
text: 'bthome met history ${measurement.id} $page',
|
||||||
|
);
|
||||||
|
if (!sent) {
|
||||||
|
throw Exception('Failed to send MET history request.');
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var i = 0; i < 30; i++) {
|
||||||
|
await Future.delayed(const Duration(milliseconds: 500));
|
||||||
|
if (responseText != null) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
final text = responseText?.trim();
|
||||||
|
if (text == null || text.isEmpty) {
|
||||||
|
throw TimeoutException('No response from sensor.');
|
||||||
|
}
|
||||||
|
if (_looksLikeError(text)) {
|
||||||
|
throw Exception(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
final history = BTHomeMetHistoryParser.parse(text);
|
||||||
|
if (!mounted) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setState(() {
|
||||||
|
_selectedMeasurement = measurement;
|
||||||
|
_history = history;
|
||||||
|
_loading = false;
|
||||||
|
_error = null;
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
if (!mounted) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setState(() {
|
||||||
|
_selectedMeasurement = measurement;
|
||||||
|
_history = null;
|
||||||
|
_loading = false;
|
||||||
|
_error = _formatError(error);
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
if (identical(connectionProvider.onMessageReceived, onMessage)) {
|
||||||
|
connectionProvider.onMessageReceived = previousOnMessageReceived;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool _matchesContact(Message message) {
|
||||||
|
final prefix = message.senderPublicKeyPrefix;
|
||||||
|
if (prefix == null ||
|
||||||
|
prefix.length < 6 ||
|
||||||
|
widget.contact.publicKey.length < 6) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
for (var i = 0; i < 6; i++) {
|
||||||
|
if (prefix[i] != widget.contact.publicKey[i]) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool _looksLikeError(String text) {
|
||||||
|
final lower = text.toLowerCase();
|
||||||
|
return lower.startsWith('err') ||
|
||||||
|
lower.contains('unknown') ||
|
||||||
|
lower.contains('unsupported');
|
||||||
|
}
|
||||||
|
|
||||||
|
String _formatError(Object error) {
|
||||||
|
if (error is TimeoutException) {
|
||||||
|
return error.message ?? 'Timed out waiting for MET history.';
|
||||||
|
}
|
||||||
|
return error.toString().replaceFirst('Exception: ', '');
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final height = MediaQuery.of(context).size.height * 0.8;
|
||||||
|
final history = _history;
|
||||||
|
|
||||||
|
return SafeArea(
|
||||||
|
child: SizedBox(
|
||||||
|
height: height,
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
Expanded(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
'MET history',
|
||||||
|
style: theme.textTheme.titleLarge?.copyWith(
|
||||||
|
fontWeight: FontWeight.w700,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Text(
|
||||||
|
widget.contact.displayName,
|
||||||
|
style: theme.textTheme.bodyMedium?.copyWith(
|
||||||
|
color: theme.colorScheme.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
IconButton(
|
||||||
|
onPressed: () => Navigator.of(context).pop(),
|
||||||
|
icon: const Icon(Icons.close),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
Wrap(
|
||||||
|
spacing: 8,
|
||||||
|
runSpacing: 8,
|
||||||
|
children: _availableMeasurements
|
||||||
|
.map(
|
||||||
|
(measurement) => ChoiceChip(
|
||||||
|
label: Text(measurement.label),
|
||||||
|
selected: measurement == _selectedMeasurement,
|
||||||
|
onSelected: (selected) {
|
||||||
|
if (!selected || _loading) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
unawaited(
|
||||||
|
_loadHistory(measurement: measurement, page: 0),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.toList(growable: false),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
OutlinedButton.icon(
|
||||||
|
onPressed: _loading || (history?.page ?? 0) == 0
|
||||||
|
? null
|
||||||
|
: () => unawaited(
|
||||||
|
_loadHistory(
|
||||||
|
measurement: _selectedMeasurement,
|
||||||
|
page: history!.page - 1,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
icon: const Icon(Icons.chevron_left),
|
||||||
|
label: const Text('Newer'),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
OutlinedButton.icon(
|
||||||
|
onPressed:
|
||||||
|
_loading ||
|
||||||
|
history == null ||
|
||||||
|
history.values.length < 12
|
||||||
|
? null
|
||||||
|
: () => unawaited(
|
||||||
|
_loadHistory(
|
||||||
|
measurement: _selectedMeasurement,
|
||||||
|
page: history.page + 1,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
icon: const Icon(Icons.chevron_right),
|
||||||
|
label: const Text('Older'),
|
||||||
|
),
|
||||||
|
const Spacer(),
|
||||||
|
if (_loading)
|
||||||
|
const SizedBox(
|
||||||
|
width: 18,
|
||||||
|
height: 18,
|
||||||
|
child: CircularProgressIndicator(strokeWidth: 2),
|
||||||
|
)
|
||||||
|
else
|
||||||
|
Text(
|
||||||
|
'Page ${history?.page ?? 0}',
|
||||||
|
style: theme.textTheme.bodySmall?.copyWith(
|
||||||
|
color: theme.colorScheme.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
Expanded(
|
||||||
|
child: SingleChildScrollView(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
if (_error != null)
|
||||||
|
_HistoryMessageCard(
|
||||||
|
icon: Icons.error_outline,
|
||||||
|
title: 'Could not load MET history',
|
||||||
|
body: _error!,
|
||||||
|
)
|
||||||
|
else if (_loading && history == null)
|
||||||
|
const _HistoryMessageCard(
|
||||||
|
icon: Icons.hourglass_top,
|
||||||
|
title: 'Loading',
|
||||||
|
body: 'Waiting for the sensor to reply.',
|
||||||
|
)
|
||||||
|
else if (history != null) ...[
|
||||||
|
_HistoryChartCard(history: history),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
_HistoryStatsGrid(history: history),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
_HistorySamplesCard(history: history),
|
||||||
|
],
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _HistoryChartCard extends StatelessWidget {
|
||||||
|
const _HistoryChartCard({required this.history});
|
||||||
|
|
||||||
|
final BTHomeMetHistoryPage history;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
return Container(
|
||||||
|
width: double.infinity,
|
||||||
|
padding: const EdgeInsets.all(16),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: theme.colorScheme.surfaceContainerLow,
|
||||||
|
borderRadius: BorderRadius.circular(24),
|
||||||
|
border: Border.all(
|
||||||
|
color: theme.colorScheme.outlineVariant.withValues(alpha: 0.4),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
history.measurement.label,
|
||||||
|
style: theme.textTheme.titleMedium?.copyWith(
|
||||||
|
fontWeight: FontWeight.w700,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 4),
|
||||||
|
Text(
|
||||||
|
'Samples are shown oldest to newest. Firmware replies do not include timestamps.',
|
||||||
|
style: theme.textTheme.bodySmall?.copyWith(
|
||||||
|
color: theme.colorScheme.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
SizedBox(
|
||||||
|
height: 180,
|
||||||
|
child: LineChart(_historyLineChartData(context, history: history)),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _HistoryStatsGrid extends StatelessWidget {
|
||||||
|
const _HistoryStatsGrid({required this.history});
|
||||||
|
|
||||||
|
final BTHomeMetHistoryPage history;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final measurement = history.measurement;
|
||||||
|
return LayoutBuilder(
|
||||||
|
builder: (context, constraints) {
|
||||||
|
final compact = constraints.maxWidth < 520;
|
||||||
|
final tiles = <Widget>[
|
||||||
|
_HistoryStatTile(
|
||||||
|
label: 'Latest',
|
||||||
|
value: _formatMeasurementValue(measurement, history.latest),
|
||||||
|
),
|
||||||
|
_HistoryStatTile(
|
||||||
|
label: 'Min',
|
||||||
|
value: _formatMeasurementValue(measurement, history.minimum),
|
||||||
|
),
|
||||||
|
_HistoryStatTile(
|
||||||
|
label: 'Max',
|
||||||
|
value: _formatMeasurementValue(measurement, history.maximum),
|
||||||
|
),
|
||||||
|
_HistoryStatTile(
|
||||||
|
label: 'Samples',
|
||||||
|
value: history.values.length.toString(),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
|
||||||
|
if (compact) {
|
||||||
|
return Column(
|
||||||
|
children: [
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
Expanded(child: tiles[0]),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Expanded(child: tiles[1]),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
Row(
|
||||||
|
children: [
|
||||||
|
Expanded(child: tiles[2]),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Expanded(child: tiles[3]),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Row(
|
||||||
|
children: [
|
||||||
|
Expanded(child: tiles[0]),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Expanded(child: tiles[1]),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Expanded(child: tiles[2]),
|
||||||
|
const SizedBox(width: 8),
|
||||||
|
Expanded(child: tiles[3]),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _HistoryStatTile extends StatelessWidget {
|
||||||
|
const _HistoryStatTile({required this.label, required this.value});
|
||||||
|
|
||||||
|
final String label;
|
||||||
|
final String value;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
return Container(
|
||||||
|
padding: const EdgeInsets.all(12),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.5),
|
||||||
|
borderRadius: BorderRadius.circular(18),
|
||||||
|
),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
label,
|
||||||
|
style: theme.textTheme.labelMedium?.copyWith(
|
||||||
|
color: theme.colorScheme.onSurfaceVariant,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 4),
|
||||||
|
Text(
|
||||||
|
value,
|
||||||
|
style: theme.textTheme.titleMedium?.copyWith(
|
||||||
|
fontWeight: FontWeight.w700,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _HistorySamplesCard extends StatelessWidget {
|
||||||
|
const _HistorySamplesCard({required this.history});
|
||||||
|
|
||||||
|
final BTHomeMetHistoryPage history;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
return Container(
|
||||||
|
width: double.infinity,
|
||||||
|
padding: const EdgeInsets.all(16),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: theme.colorScheme.surfaceContainerLow,
|
||||||
|
borderRadius: BorderRadius.circular(24),
|
||||||
|
border: Border.all(
|
||||||
|
color: theme.colorScheme.outlineVariant.withValues(alpha: 0.4),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
'Samples',
|
||||||
|
style: theme.textTheme.titleMedium?.copyWith(
|
||||||
|
fontWeight: FontWeight.w700,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 10),
|
||||||
|
Wrap(
|
||||||
|
spacing: 8,
|
||||||
|
runSpacing: 8,
|
||||||
|
children: history.values
|
||||||
|
.asMap()
|
||||||
|
.entries
|
||||||
|
.map((entry) {
|
||||||
|
final sampleIndex = entry.key + 1;
|
||||||
|
final isLatest = entry.key == history.values.length - 1;
|
||||||
|
return Container(
|
||||||
|
padding: const EdgeInsets.symmetric(
|
||||||
|
horizontal: 10,
|
||||||
|
vertical: 8,
|
||||||
|
),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: isLatest
|
||||||
|
? _historyColor(
|
||||||
|
history.measurement,
|
||||||
|
).withValues(alpha: 0.12)
|
||||||
|
: theme.colorScheme.surfaceContainerHighest
|
||||||
|
.withValues(alpha: 0.45),
|
||||||
|
borderRadius: BorderRadius.circular(14),
|
||||||
|
),
|
||||||
|
child: Text(
|
||||||
|
'$sampleIndex. ${_formatMeasurementValue(history.measurement, entry.value)}${isLatest ? ' latest' : ''}',
|
||||||
|
style: theme.textTheme.bodyMedium?.copyWith(
|
||||||
|
fontWeight: isLatest
|
||||||
|
? FontWeight.w700
|
||||||
|
: FontWeight.w500,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
})
|
||||||
|
.toList(growable: false),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _HistoryMessageCard extends StatelessWidget {
|
||||||
|
const _HistoryMessageCard({
|
||||||
|
required this.icon,
|
||||||
|
required this.title,
|
||||||
|
required this.body,
|
||||||
|
});
|
||||||
|
|
||||||
|
final IconData icon;
|
||||||
|
final String title;
|
||||||
|
final String body;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
return Container(
|
||||||
|
width: double.infinity,
|
||||||
|
padding: const EdgeInsets.all(16),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: theme.colorScheme.surfaceContainerLow,
|
||||||
|
borderRadius: BorderRadius.circular(24),
|
||||||
|
),
|
||||||
|
child: Row(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Icon(icon, color: theme.colorScheme.primary),
|
||||||
|
const SizedBox(width: 12),
|
||||||
|
Expanded(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Text(
|
||||||
|
title,
|
||||||
|
style: theme.textTheme.titleMedium?.copyWith(
|
||||||
|
fontWeight: FontWeight.w700,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(height: 4),
|
||||||
|
Text(body),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Color _historyColor(BTHomeMetMeasurement measurement) {
|
||||||
|
switch (measurement) {
|
||||||
|
case BTHomeMetMeasurement.temperature:
|
||||||
|
return const Color(0xFFC76821);
|
||||||
|
case BTHomeMetMeasurement.humidity:
|
||||||
|
return const Color(0xFF246BB2);
|
||||||
|
case BTHomeMetMeasurement.windSpeed:
|
||||||
|
return const Color(0xFF2B78A0);
|
||||||
|
case BTHomeMetMeasurement.gust:
|
||||||
|
return const Color(0xFF1E88A8);
|
||||||
|
case BTHomeMetMeasurement.rain:
|
||||||
|
return const Color(0xFF2C6BA0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String _formatMeasurementValue(BTHomeMetMeasurement measurement, num? value) {
|
||||||
|
if (value == null) {
|
||||||
|
return '--';
|
||||||
|
}
|
||||||
|
|
||||||
|
final digits = switch (measurement) {
|
||||||
|
BTHomeMetMeasurement.humidity => 0,
|
||||||
|
BTHomeMetMeasurement.temperature => 1,
|
||||||
|
BTHomeMetMeasurement.windSpeed => 1,
|
||||||
|
BTHomeMetMeasurement.gust => 1,
|
||||||
|
BTHomeMetMeasurement.rain => 1,
|
||||||
|
};
|
||||||
|
|
||||||
|
final text = value
|
||||||
|
.toStringAsFixed(digits)
|
||||||
|
.replaceFirst(RegExp(r'\.?0+$'), '');
|
||||||
|
return '$text${measurement.unit}';
|
||||||
|
}
|
||||||
|
|
||||||
|
LineChartData _historyLineChartData(
|
||||||
|
BuildContext context, {
|
||||||
|
required BTHomeMetHistoryPage history,
|
||||||
|
}) {
|
||||||
|
final theme = Theme.of(context);
|
||||||
|
final color = _historyColor(history.measurement);
|
||||||
|
final values = history.values;
|
||||||
|
final spots = values
|
||||||
|
.asMap()
|
||||||
|
.entries
|
||||||
|
.map((entry) => FlSpot(entry.key.toDouble(), entry.value))
|
||||||
|
.toList(growable: false);
|
||||||
|
final chartMinY = _historyChartMinY(history);
|
||||||
|
final chartMaxY = _historyChartMaxY(history);
|
||||||
|
final yInterval = _historyYAxisInterval(
|
||||||
|
measurement: history.measurement,
|
||||||
|
minY: chartMinY,
|
||||||
|
maxY: chartMaxY,
|
||||||
|
);
|
||||||
|
|
||||||
|
return LineChartData(
|
||||||
|
minX: 0,
|
||||||
|
maxX: values.length <= 1 ? 1.0 : (values.length - 1).toDouble(),
|
||||||
|
minY: chartMinY,
|
||||||
|
maxY: chartMaxY,
|
||||||
|
clipData: const FlClipData.all(),
|
||||||
|
lineTouchData: const LineTouchData(enabled: false),
|
||||||
|
gridData: FlGridData(
|
||||||
|
show: true,
|
||||||
|
drawVerticalLine: false,
|
||||||
|
horizontalInterval: yInterval,
|
||||||
|
getDrawingHorizontalLine: (value) => FlLine(
|
||||||
|
color: theme.colorScheme.outlineVariant.withValues(alpha: 0.28),
|
||||||
|
strokeWidth: 1,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
borderData: FlBorderData(show: false),
|
||||||
|
titlesData: FlTitlesData(
|
||||||
|
topTitles: const AxisTitles(sideTitles: SideTitles(showTitles: false)),
|
||||||
|
rightTitles: const AxisTitles(sideTitles: SideTitles(showTitles: false)),
|
||||||
|
leftTitles: AxisTitles(
|
||||||
|
sideTitles: SideTitles(
|
||||||
|
showTitles: true,
|
||||||
|
reservedSize: 42,
|
||||||
|
interval: yInterval,
|
||||||
|
getTitlesWidget: (value, meta) => SideTitleWidget(
|
||||||
|
meta: meta,
|
||||||
|
space: 8,
|
||||||
|
child: Text(
|
||||||
|
_formatHistoryAxisValue(history.measurement, value),
|
||||||
|
style: Theme.of(context).textTheme.labelSmall?.copyWith(
|
||||||
|
color: theme.colorScheme.onSurfaceVariant,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
bottomTitles: AxisTitles(
|
||||||
|
sideTitles: SideTitles(
|
||||||
|
showTitles: true,
|
||||||
|
reservedSize: 24,
|
||||||
|
interval: 1,
|
||||||
|
getTitlesWidget: (value, meta) {
|
||||||
|
final index = value.round();
|
||||||
|
if (value != index.toDouble() ||
|
||||||
|
!_shouldShowBottomSampleLabel(index, values.length)) {
|
||||||
|
return const SizedBox.shrink();
|
||||||
|
}
|
||||||
|
|
||||||
|
return SideTitleWidget(
|
||||||
|
meta: meta,
|
||||||
|
space: 6,
|
||||||
|
child: Text(
|
||||||
|
'${index + 1}',
|
||||||
|
style: Theme.of(context).textTheme.labelSmall?.copyWith(
|
||||||
|
color: theme.colorScheme.onSurfaceVariant,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
lineBarsData: [
|
||||||
|
LineChartBarData(
|
||||||
|
spots: spots,
|
||||||
|
color: color,
|
||||||
|
barWidth: 2.8,
|
||||||
|
isCurved: false,
|
||||||
|
isStrokeCapRound: true,
|
||||||
|
dotData: FlDotData(
|
||||||
|
show: true,
|
||||||
|
checkToShowDot: (spot, barData) =>
|
||||||
|
barData.spots.length <= 10 || spot == barData.spots.last,
|
||||||
|
getDotPainter: (spot, percent, barData, index) => FlDotCirclePainter(
|
||||||
|
radius: spot == barData.spots.last ? 4 : 2.5,
|
||||||
|
color: color,
|
||||||
|
strokeColor: theme.colorScheme.surface,
|
||||||
|
strokeWidth: 1.6,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
belowBarData: BarAreaData(
|
||||||
|
show: true,
|
||||||
|
gradient: LinearGradient(
|
||||||
|
begin: Alignment.topCenter,
|
||||||
|
end: Alignment.bottomCenter,
|
||||||
|
colors: [
|
||||||
|
color.withValues(alpha: 0.24),
|
||||||
|
color.withValues(alpha: 0.03),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
double _historyChartMinY(BTHomeMetHistoryPage history) {
|
||||||
|
final minValue = history.minimum ?? 0;
|
||||||
|
final maxValue = history.maximum ?? 0;
|
||||||
|
final spread = maxValue - minValue;
|
||||||
|
final padding = spread == 0
|
||||||
|
? _historyMinimumPadding(history.measurement, minValue)
|
||||||
|
: math.max(
|
||||||
|
spread * 0.18,
|
||||||
|
_historyMinimumPadding(history.measurement, minValue),
|
||||||
|
);
|
||||||
|
return minValue - padding;
|
||||||
|
}
|
||||||
|
|
||||||
|
double _historyChartMaxY(BTHomeMetHistoryPage history) {
|
||||||
|
final minValue = history.minimum ?? 0;
|
||||||
|
final maxValue = history.maximum ?? 0;
|
||||||
|
final spread = maxValue - minValue;
|
||||||
|
final padding = spread == 0
|
||||||
|
? _historyMinimumPadding(history.measurement, maxValue)
|
||||||
|
: math.max(
|
||||||
|
spread * 0.18,
|
||||||
|
_historyMinimumPadding(history.measurement, maxValue),
|
||||||
|
);
|
||||||
|
return maxValue + padding;
|
||||||
|
}
|
||||||
|
|
||||||
|
double _historyMinimumPadding(
|
||||||
|
BTHomeMetMeasurement measurement,
|
||||||
|
double reference,
|
||||||
|
) {
|
||||||
|
final scaled = math.max(reference.abs() * 0.05, 0.1);
|
||||||
|
return switch (measurement) {
|
||||||
|
BTHomeMetMeasurement.temperature => math.max(0.4, scaled),
|
||||||
|
BTHomeMetMeasurement.humidity => math.max(2.0, scaled),
|
||||||
|
BTHomeMetMeasurement.windSpeed => math.max(0.4, scaled),
|
||||||
|
BTHomeMetMeasurement.gust => math.max(0.4, scaled),
|
||||||
|
BTHomeMetMeasurement.rain => math.max(0.4, scaled),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
double _historyYAxisInterval({
|
||||||
|
required BTHomeMetMeasurement measurement,
|
||||||
|
required double minY,
|
||||||
|
required double maxY,
|
||||||
|
}) {
|
||||||
|
final span = maxY - minY;
|
||||||
|
if (span <= 0) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
final rough = span / 3;
|
||||||
|
return switch (measurement) {
|
||||||
|
BTHomeMetMeasurement.humidity => math.max(1, rough.round()).toDouble(),
|
||||||
|
BTHomeMetMeasurement.temperature => _niceStep(rough, minStep: 0.5),
|
||||||
|
BTHomeMetMeasurement.windSpeed => _niceStep(rough, minStep: 0.5),
|
||||||
|
BTHomeMetMeasurement.gust => _niceStep(rough, minStep: 0.5),
|
||||||
|
BTHomeMetMeasurement.rain => _niceStep(rough, minStep: 0.5),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
double _niceStep(double value, {required double minStep}) {
|
||||||
|
if (value <= minStep) {
|
||||||
|
return minStep;
|
||||||
|
}
|
||||||
|
|
||||||
|
final exponent = math
|
||||||
|
.pow(10.0, (math.log(value) / math.ln10).floor())
|
||||||
|
.toDouble();
|
||||||
|
final normalized = value / exponent;
|
||||||
|
final stepped = switch (normalized) {
|
||||||
|
< 1.5 => 1.0,
|
||||||
|
< 3.0 => 2.0,
|
||||||
|
< 7.0 => 5.0,
|
||||||
|
_ => 10.0,
|
||||||
|
};
|
||||||
|
return math.max(minStep, stepped * exponent);
|
||||||
|
}
|
||||||
|
|
||||||
|
String _formatHistoryAxisValue(BTHomeMetMeasurement measurement, double value) {
|
||||||
|
final digits = measurement == BTHomeMetMeasurement.humidity ? 0 : 1;
|
||||||
|
return value.toStringAsFixed(digits).replaceFirst(RegExp(r'\.?0+$'), '');
|
||||||
|
}
|
||||||
|
|
||||||
|
bool _shouldShowBottomSampleLabel(int index, int sampleCount) {
|
||||||
|
if (index < 0 || index >= sampleCount) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (sampleCount <= 3) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
final middle = (sampleCount - 1) ~/ 2;
|
||||||
|
return index == 0 || index == middle || index == sampleCount - 1;
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@ import 'package:latlong2/latlong.dart';
|
|||||||
import '../../l10n/app_localizations.dart';
|
import '../../l10n/app_localizations.dart';
|
||||||
import '../../models/contact.dart';
|
import '../../models/contact.dart';
|
||||||
import '../../providers/sensors_provider.dart';
|
import '../../providers/sensors_provider.dart';
|
||||||
|
import '../../services/bthome_met_history.dart';
|
||||||
import '../../utils/location_formats.dart';
|
import '../../utils/location_formats.dart';
|
||||||
|
|
||||||
class SensorMetricOption {
|
class SensorMetricOption {
|
||||||
@@ -207,9 +208,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) {
|
if (extraSensorData != null) {
|
||||||
for (final key in extraSensorData.keys) {
|
for (final key in extraSensorData.keys) {
|
||||||
if (_isTelemetryMetadataKey(key)) {
|
if (_isTelemetryMetadataKey(key) || coreFieldKeys.contains(key)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
final metricKey = _parseMetricKey(key);
|
final metricKey = _parseMetricKey(key);
|
||||||
@@ -276,14 +293,14 @@ SensorMetricCardData? _buildOptionPreviewCardData(
|
|||||||
);
|
);
|
||||||
case 'illuminance':
|
case 'illuminance':
|
||||||
final lux = _previewAsDouble(value);
|
final lux = _previewAsDouble(value);
|
||||||
|
final irradiance = lux == null
|
||||||
|
? null
|
||||||
|
: _previewFormatDaylightIrradiance(lux);
|
||||||
return SensorMetricCardData(
|
return SensorMetricCardData(
|
||||||
fieldKey: fieldKey,
|
fieldKey: fieldKey,
|
||||||
icon: Icons.light_mode_outlined,
|
icon: Icons.light_mode_outlined,
|
||||||
label: label,
|
label: label,
|
||||||
value: previewValue,
|
value: irradiance ?? previewValue,
|
||||||
secondaryValue: lux == null
|
|
||||||
? null
|
|
||||||
: '~${_formatPreviewNumber(_previewApproxDaylightIrradiance(lux), maxFractionDigits: 1)} W/m2 daylight',
|
|
||||||
accent: const Color(0xFFC17B1D),
|
accent: const Color(0xFFC17B1D),
|
||||||
channel: metricKey.channel,
|
channel: metricKey.channel,
|
||||||
);
|
);
|
||||||
@@ -660,6 +677,10 @@ double _previewApproxDaylightIrradiance(double lux) {
|
|||||||
return lux / 120.0;
|
return lux / 120.0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
String _previewFormatDaylightIrradiance(double lux) {
|
||||||
|
return '~${_formatPreviewNumber(_previewApproxDaylightIrradiance(lux), maxFractionDigits: 1)} W/m2';
|
||||||
|
}
|
||||||
|
|
||||||
String _previewFormatCardinalDirection(double degrees) {
|
String _previewFormatCardinalDirection(double degrees) {
|
||||||
const points = <String>['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'];
|
const points = <String>['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'];
|
||||||
final normalized = ((degrees % 360) + 360) % 360;
|
final normalized = ((degrees % 360) + 360) % 360;
|
||||||
@@ -685,7 +706,7 @@ String? _sensorMetricPreviewValue(String rawKey, dynamic value) {
|
|||||||
case 'illuminance':
|
case 'illuminance':
|
||||||
final lux = _previewAsDouble(value);
|
final lux = _previewAsDouble(value);
|
||||||
if (lux == null) return null;
|
if (lux == null) return null;
|
||||||
return '${_formatPreviewNumber(lux, maxFractionDigits: 0)} lx';
|
return _previewFormatDaylightIrradiance(lux);
|
||||||
|
|
||||||
case 'presence':
|
case 'presence':
|
||||||
final isPresent = _previewAsBool(value);
|
final isPresent = _previewAsBool(value);
|
||||||
@@ -1008,6 +1029,7 @@ class SensorTelemetryCard extends StatelessWidget {
|
|||||||
final Future<void> Function()? onRemove;
|
final Future<void> Function()? onRemove;
|
||||||
final Future<void> Function()? onRefresh;
|
final Future<void> Function()? onRefresh;
|
||||||
final VoidCallback? onCustomize;
|
final VoidCallback? onCustomize;
|
||||||
|
final Future<void> Function(Contact contact)? onShowMetHistory;
|
||||||
final EdgeInsetsGeometry margin;
|
final EdgeInsetsGeometry margin;
|
||||||
final String emptyMetricsMessage;
|
final String emptyMetricsMessage;
|
||||||
final Map<String, String> labelOverrides;
|
final Map<String, String> labelOverrides;
|
||||||
@@ -1022,6 +1044,7 @@ class SensorTelemetryCard extends StatelessWidget {
|
|||||||
this.onRemove,
|
this.onRemove,
|
||||||
this.onRefresh,
|
this.onRefresh,
|
||||||
this.onCustomize,
|
this.onCustomize,
|
||||||
|
this.onShowMetHistory,
|
||||||
this.margin = const EdgeInsets.only(bottom: 16),
|
this.margin = const EdgeInsets.only(bottom: 16),
|
||||||
this.emptyMetricsMessage =
|
this.emptyMetricsMessage =
|
||||||
'All fields are hidden. Use Visible fields to choose what to show.',
|
'All fields are hidden. Use Visible fields to choose what to show.',
|
||||||
@@ -1029,7 +1052,12 @@ class SensorTelemetryCard extends StatelessWidget {
|
|||||||
});
|
});
|
||||||
|
|
||||||
bool get _showsMenu =>
|
bool get _showsMenu =>
|
||||||
onRefresh != null || onCustomize != null || onRemove != null;
|
onRefresh != null ||
|
||||||
|
onCustomize != null ||
|
||||||
|
onRemove != null ||
|
||||||
|
(contact != null &&
|
||||||
|
onShowMetHistory != null &&
|
||||||
|
supportsBTHomeMetHistory(contact));
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
@@ -1139,6 +1167,10 @@ class SensorTelemetryCard extends StatelessWidget {
|
|||||||
await onRemove!();
|
await onRemove!();
|
||||||
} else if (value == 'customize' && onCustomize != null) {
|
} else if (value == 'customize' && onCustomize != null) {
|
||||||
onCustomize!();
|
onCustomize!();
|
||||||
|
} else if (value == 'met_history' &&
|
||||||
|
contact != null &&
|
||||||
|
onShowMetHistory != null) {
|
||||||
|
await onShowMetHistory!(contact!);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
itemBuilder: (context) {
|
itemBuilder: (context) {
|
||||||
@@ -1159,6 +1191,16 @@ class SensorTelemetryCard extends StatelessWidget {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
if (contact != null &&
|
||||||
|
onShowMetHistory != null &&
|
||||||
|
supportsBTHomeMetHistory(contact)) {
|
||||||
|
items.add(
|
||||||
|
const PopupMenuItem<String>(
|
||||||
|
value: 'met_history',
|
||||||
|
child: Text('MET history'),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
if (onRemove != null) {
|
if (onRemove != null) {
|
||||||
items.add(
|
items.add(
|
||||||
PopupMenuItem<String>(
|
PopupMenuItem<String>(
|
||||||
@@ -1201,6 +1243,11 @@ class SensorTelemetryCard extends StatelessWidget {
|
|||||||
metric.wide)
|
metric.wide)
|
||||||
? constraints.maxWidth
|
? constraints.maxWidth
|
||||||
: compactWidth,
|
: compactWidth,
|
||||||
|
onLongPress: onRefresh == null
|
||||||
|
? null
|
||||||
|
: () async {
|
||||||
|
await onRefresh!();
|
||||||
|
},
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
.toList(),
|
.toList(),
|
||||||
@@ -1425,9 +1472,7 @@ class SensorTelemetryCard extends StatelessWidget {
|
|||||||
fieldKey: _extraFieldKey(rawKey),
|
fieldKey: _extraFieldKey(rawKey),
|
||||||
icon: Icons.light_mode_outlined,
|
icon: Icons.light_mode_outlined,
|
||||||
label: label,
|
label: label,
|
||||||
value: '${_formatNumber(lux, maxFractionDigits: 0)} lx',
|
value: _formatDaylightIrradiance(lux),
|
||||||
secondaryValue:
|
|
||||||
'~${_formatNumber(_approxDaylightIrradiance(lux), maxFractionDigits: 1)} W/m2 daylight',
|
|
||||||
accent: const Color(0xFFC17B1D),
|
accent: const Color(0xFFC17B1D),
|
||||||
channel: metricKey.channel,
|
channel: metricKey.channel,
|
||||||
);
|
);
|
||||||
@@ -1944,6 +1989,10 @@ class SensorTelemetryCard extends StatelessWidget {
|
|||||||
return lux / 120.0;
|
return lux / 120.0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
String _formatDaylightIrradiance(double lux) {
|
||||||
|
return '~${_formatNumber(_approxDaylightIrradiance(lux), maxFractionDigits: 1)} W/m2';
|
||||||
|
}
|
||||||
|
|
||||||
String _formatCurrent(double amps) {
|
String _formatCurrent(double amps) {
|
||||||
final absolute = amps.abs();
|
final absolute = amps.abs();
|
||||||
if (absolute < 1.0) {
|
if (absolute < 1.0) {
|
||||||
@@ -2146,6 +2195,7 @@ class SensorMetricTile extends StatelessWidget {
|
|||||||
final double width;
|
final double width;
|
||||||
final String keyPrefix;
|
final String keyPrefix;
|
||||||
final bool allowMapPreview;
|
final bool allowMapPreview;
|
||||||
|
final GestureLongPressCallback? onLongPress;
|
||||||
|
|
||||||
const SensorMetricTile({
|
const SensorMetricTile({
|
||||||
super.key,
|
super.key,
|
||||||
@@ -2153,6 +2203,7 @@ class SensorMetricTile extends StatelessWidget {
|
|||||||
required this.width,
|
required this.width,
|
||||||
this.keyPrefix = 'sensor_metric',
|
this.keyPrefix = 'sensor_metric',
|
||||||
this.allowMapPreview = true,
|
this.allowMapPreview = true,
|
||||||
|
this.onLongPress,
|
||||||
});
|
});
|
||||||
|
|
||||||
Future<void> _showExpandedMap(BuildContext context) async {
|
Future<void> _showExpandedMap(BuildContext context) async {
|
||||||
@@ -2227,125 +2278,152 @@ class SensorMetricTile extends StatelessWidget {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return Container(
|
return Material(
|
||||||
key: ValueKey('${keyPrefix}_${data.fieldKey}'),
|
color: Colors.transparent,
|
||||||
width: width,
|
child: InkWell(
|
||||||
padding: const EdgeInsets.all(8),
|
key: ValueKey('${keyPrefix}_${data.fieldKey}'),
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: data.accent.withValues(alpha: 0.08),
|
|
||||||
borderRadius: BorderRadius.circular(22),
|
borderRadius: BorderRadius.circular(22),
|
||||||
border: Border.all(color: data.accent.withValues(alpha: 0.14)),
|
onLongPress: onLongPress,
|
||||||
),
|
child: Container(
|
||||||
child: data.mapLocation == null || !allowMapPreview
|
width: width,
|
||||||
? Row(
|
padding: const EdgeInsets.all(8),
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
decoration: BoxDecoration(
|
||||||
children: [
|
color: data.accent.withValues(alpha: 0.08),
|
||||||
_MetricIcon(accent: data.accent, icon: data.icon),
|
borderRadius: BorderRadius.circular(22),
|
||||||
const SizedBox(width: 10),
|
border: Border.all(color: data.accent.withValues(alpha: 0.14)),
|
||||||
Expanded(
|
),
|
||||||
child: _MetricText(data: data, keyPrefix: keyPrefix),
|
child: data.mapLocation == null || !allowMapPreview
|
||||||
),
|
? Stack(
|
||||||
],
|
children: [
|
||||||
)
|
Row(
|
||||||
: Column(
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
children: [
|
||||||
children: [
|
_MetricIcon(accent: data.accent, icon: data.icon),
|
||||||
Row(
|
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(
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
children: [
|
children: [
|
||||||
_MetricIcon(accent: data.accent, icon: data.icon),
|
Row(
|
||||||
const SizedBox(width: 10),
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
Expanded(
|
children: [
|
||||||
child: _MetricText(data: data, keyPrefix: keyPrefix),
|
_MetricIcon(accent: data.accent, icon: data.icon),
|
||||||
|
const SizedBox(width: 10),
|
||||||
|
Expanded(
|
||||||
|
child: _MetricText(data: data, keyPrefix: keyPrefix),
|
||||||
|
),
|
||||||
|
],
|
||||||
),
|
),
|
||||||
],
|
const SizedBox(height: 10),
|
||||||
),
|
Material(
|
||||||
const SizedBox(height: 10),
|
color: Colors.transparent,
|
||||||
Material(
|
child: InkWell(
|
||||||
color: Colors.transparent,
|
borderRadius: BorderRadius.circular(14),
|
||||||
child: InkWell(
|
onTap: () => _showExpandedMap(context),
|
||||||
borderRadius: BorderRadius.circular(14),
|
child: ClipRRect(
|
||||||
onTap: () => _showExpandedMap(context),
|
borderRadius: BorderRadius.circular(14),
|
||||||
child: ClipRRect(
|
child: SizedBox(
|
||||||
borderRadius: BorderRadius.circular(14),
|
height: 104,
|
||||||
child: SizedBox(
|
width: double.infinity,
|
||||||
height: 104,
|
child: Stack(
|
||||||
width: double.infinity,
|
|
||||||
child: Stack(
|
|
||||||
children: [
|
|
||||||
flutter_map.FlutterMap(
|
|
||||||
options: flutter_map.MapOptions(
|
|
||||||
initialCenter: data.mapLocation!,
|
|
||||||
initialZoom: 14,
|
|
||||||
interactionOptions:
|
|
||||||
const flutter_map.InteractionOptions(
|
|
||||||
flags: flutter_map.InteractiveFlag.none,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
children: [
|
children: [
|
||||||
flutter_map.TileLayer(
|
flutter_map.FlutterMap(
|
||||||
urlTemplate:
|
options: flutter_map.MapOptions(
|
||||||
'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
|
initialCenter: data.mapLocation!,
|
||||||
userAgentPackageName:
|
initialZoom: 14,
|
||||||
'com.meshcore.sar.meshcore_sar_app',
|
interactionOptions:
|
||||||
),
|
const flutter_map.InteractionOptions(
|
||||||
flutter_map.MarkerLayer(
|
flags:
|
||||||
markers: [
|
flutter_map.InteractiveFlag.none,
|
||||||
flutter_map.Marker(
|
),
|
||||||
point: data.mapLocation!,
|
),
|
||||||
width: 32,
|
children: [
|
||||||
height: 32,
|
flutter_map.TileLayer(
|
||||||
child: Icon(
|
urlTemplate:
|
||||||
Icons.location_on,
|
'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
|
||||||
color: data.accent,
|
userAgentPackageName:
|
||||||
size: 28,
|
'com.meshcore.sar.meshcore_sar_app',
|
||||||
),
|
),
|
||||||
|
flutter_map.MarkerLayer(
|
||||||
|
markers: [
|
||||||
|
flutter_map.Marker(
|
||||||
|
point: data.mapLocation!,
|
||||||
|
width: 32,
|
||||||
|
height: 32,
|
||||||
|
child: Icon(
|
||||||
|
Icons.location_on,
|
||||||
|
color: data.accent,
|
||||||
|
size: 28,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
|
Positioned(
|
||||||
|
right: 8,
|
||||||
|
bottom: 8,
|
||||||
|
child: Container(
|
||||||
|
padding: const EdgeInsets.symmetric(
|
||||||
|
horizontal: 6,
|
||||||
|
vertical: 3,
|
||||||
|
),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: Colors.black.withValues(
|
||||||
|
alpha: 0.55,
|
||||||
|
),
|
||||||
|
borderRadius: BorderRadius.circular(999),
|
||||||
|
),
|
||||||
|
child: const Row(
|
||||||
|
mainAxisSize: MainAxisSize.min,
|
||||||
|
children: [
|
||||||
|
Icon(
|
||||||
|
Icons.open_in_full,
|
||||||
|
size: 12,
|
||||||
|
color: Colors.white,
|
||||||
|
),
|
||||||
|
SizedBox(width: 4),
|
||||||
|
Text(
|
||||||
|
'Open map',
|
||||||
|
style: TextStyle(
|
||||||
|
color: Colors.white,
|
||||||
|
fontSize: 11,
|
||||||
|
fontWeight: FontWeight.w600,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
Positioned(
|
),
|
||||||
right: 8,
|
|
||||||
bottom: 8,
|
|
||||||
child: Container(
|
|
||||||
padding: const EdgeInsets.symmetric(
|
|
||||||
horizontal: 6,
|
|
||||||
vertical: 3,
|
|
||||||
),
|
|
||||||
decoration: BoxDecoration(
|
|
||||||
color: Colors.black.withValues(alpha: 0.55),
|
|
||||||
borderRadius: BorderRadius.circular(999),
|
|
||||||
),
|
|
||||||
child: const Row(
|
|
||||||
mainAxisSize: MainAxisSize.min,
|
|
||||||
children: [
|
|
||||||
Icon(
|
|
||||||
Icons.open_in_full,
|
|
||||||
size: 12,
|
|
||||||
color: Colors.white,
|
|
||||||
),
|
|
||||||
SizedBox(width: 4),
|
|
||||||
Text(
|
|
||||||
'Open map',
|
|
||||||
style: TextStyle(
|
|
||||||
color: Colors.white,
|
|
||||||
fontSize: 11,
|
|
||||||
fontWeight: FontWeight.w600,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
],
|
||||||
),
|
),
|
||||||
],
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2381,39 +2459,14 @@ class _MetricText extends StatelessWidget {
|
|||||||
return Column(
|
return Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
children: [
|
children: [
|
||||||
Row(
|
Text(
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
data.label,
|
||||||
children: [
|
maxLines: 1,
|
||||||
Expanded(
|
overflow: TextOverflow.ellipsis,
|
||||||
child: Text(
|
style: Theme.of(context).textTheme.labelMedium?.copyWith(
|
||||||
data.label,
|
color: data.accent,
|
||||||
maxLines: 1,
|
fontWeight: FontWeight.w700,
|
||||||
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,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
],
|
|
||||||
),
|
),
|
||||||
const SizedBox(height: 4),
|
const SizedBox(height: 4),
|
||||||
Text(
|
Text(
|
||||||
|
|||||||
@@ -9,6 +9,7 @@
|
|||||||
#include <audioplayers_linux/audioplayers_linux_plugin.h>
|
#include <audioplayers_linux/audioplayers_linux_plugin.h>
|
||||||
#include <file_selector_linux/file_selector_plugin.h>
|
#include <file_selector_linux/file_selector_plugin.h>
|
||||||
#include <flutter_avif_linux/flutter_avif_linux_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 <record_linux/record_linux_plugin.h>
|
||||||
#include <url_launcher_linux/url_launcher_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 =
|
g_autoptr(FlPluginRegistrar) flutter_avif_linux_registrar =
|
||||||
fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterAvifLinuxPlugin");
|
fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterAvifLinuxPlugin");
|
||||||
flutter_avif_linux_plugin_register_with_registrar(flutter_avif_linux_registrar);
|
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 =
|
g_autoptr(FlPluginRegistrar) record_linux_registrar =
|
||||||
fl_plugin_registry_get_registrar_for_plugin(registry, "RecordLinuxPlugin");
|
fl_plugin_registry_get_registrar_for_plugin(registry, "RecordLinuxPlugin");
|
||||||
record_linux_plugin_register_with_registrar(record_linux_registrar);
|
record_linux_plugin_register_with_registrar(record_linux_registrar);
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ list(APPEND FLUTTER_PLUGIN_LIST
|
|||||||
audioplayers_linux
|
audioplayers_linux
|
||||||
file_selector_linux
|
file_selector_linux
|
||||||
flutter_avif_linux
|
flutter_avif_linux
|
||||||
|
flutter_libserialport
|
||||||
record_linux
|
record_linux
|
||||||
url_launcher_linux
|
url_launcher_linux
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import file_picker
|
|||||||
import file_selector_macos
|
import file_selector_macos
|
||||||
import flutter_avif_macos
|
import flutter_avif_macos
|
||||||
import flutter_blue_plus_darwin
|
import flutter_blue_plus_darwin
|
||||||
|
import flutter_libserialport
|
||||||
import flutter_local_notifications
|
import flutter_local_notifications
|
||||||
import geolocator_apple
|
import geolocator_apple
|
||||||
import nsd_macos
|
import nsd_macos
|
||||||
@@ -30,6 +31,7 @@ func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
|
|||||||
FileSelectorPlugin.register(with: registry.registrar(forPlugin: "FileSelectorPlugin"))
|
FileSelectorPlugin.register(with: registry.registrar(forPlugin: "FileSelectorPlugin"))
|
||||||
FlutterAvifPlugin.register(with: registry.registrar(forPlugin: "FlutterAvifPlugin"))
|
FlutterAvifPlugin.register(with: registry.registrar(forPlugin: "FlutterAvifPlugin"))
|
||||||
FlutterBluePlusPlugin.register(with: registry.registrar(forPlugin: "FlutterBluePlusPlugin"))
|
FlutterBluePlusPlugin.register(with: registry.registrar(forPlugin: "FlutterBluePlusPlugin"))
|
||||||
|
FlutterLibserialportPlugin.register(with: registry.registrar(forPlugin: "FlutterLibserialportPlugin"))
|
||||||
FlutterLocalNotificationsPlugin.register(with: registry.registrar(forPlugin: "FlutterLocalNotificationsPlugin"))
|
FlutterLocalNotificationsPlugin.register(with: registry.registrar(forPlugin: "FlutterLocalNotificationsPlugin"))
|
||||||
GeolocatorPlugin.register(with: registry.registrar(forPlugin: "GeolocatorPlugin"))
|
GeolocatorPlugin.register(with: registry.registrar(forPlugin: "GeolocatorPlugin"))
|
||||||
NsdMacosPlugin.register(with: registry.registrar(forPlugin: "NsdMacosPlugin"))
|
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.
|
# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
|
||||||
ENV['COCOAPODS_DISABLE_STATS'] = 'true'
|
ENV['COCOAPODS_DISABLE_STATS'] = 'true'
|
||||||
@@ -38,6 +38,9 @@ end
|
|||||||
post_install do |installer|
|
post_install do |installer|
|
||||||
installer.pods_project.targets.each do |target|
|
installer.pods_project.targets.each do |target|
|
||||||
flutter_additional_macos_build_settings(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
|
# 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
|
# 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.
|
# all C source files from the macOS codec2_flutter build entirely.
|
||||||
|
|||||||
@@ -15,12 +15,16 @@ PODS:
|
|||||||
- flutter_blue_plus_darwin (0.0.2):
|
- flutter_blue_plus_darwin (0.0.2):
|
||||||
- Flutter
|
- Flutter
|
||||||
- FlutterMacOS
|
- FlutterMacOS
|
||||||
|
- flutter_libserialport (0.0.1):
|
||||||
|
- FlutterMacOS
|
||||||
|
- libserialport
|
||||||
- flutter_local_notifications (0.0.1):
|
- flutter_local_notifications (0.0.1):
|
||||||
- FlutterMacOS
|
- FlutterMacOS
|
||||||
- FlutterMacOS (1.0.0)
|
- FlutterMacOS (1.0.0)
|
||||||
- geolocator_apple (1.2.0):
|
- geolocator_apple (1.2.0):
|
||||||
- Flutter
|
- Flutter
|
||||||
- FlutterMacOS
|
- FlutterMacOS
|
||||||
|
- libserialport (0.1.1)
|
||||||
- nsd_macos (0.0.1):
|
- nsd_macos (0.0.1):
|
||||||
- FlutterMacOS
|
- FlutterMacOS
|
||||||
- package_info_plus (0.0.1):
|
- package_info_plus (0.0.1):
|
||||||
@@ -40,6 +44,8 @@ PODS:
|
|||||||
- FlutterMacOS
|
- FlutterMacOS
|
||||||
- url_launcher_macos (0.0.1):
|
- url_launcher_macos (0.0.1):
|
||||||
- FlutterMacOS
|
- FlutterMacOS
|
||||||
|
- wakelock_plus (0.0.1):
|
||||||
|
- FlutterMacOS
|
||||||
|
|
||||||
DEPENDENCIES:
|
DEPENDENCIES:
|
||||||
- audioplayers_darwin (from `Flutter/ephemeral/.symlinks/plugins/audioplayers_darwin/darwin`)
|
- 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`)
|
- 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_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_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`)
|
- flutter_local_notifications (from `Flutter/ephemeral/.symlinks/plugins/flutter_local_notifications/macos`)
|
||||||
- FlutterMacOS (from `Flutter/ephemeral`)
|
- FlutterMacOS (from `Flutter/ephemeral`)
|
||||||
- geolocator_apple (from `Flutter/ephemeral/.symlinks/plugins/geolocator_apple/darwin`)
|
- 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`)
|
- shared_preferences_foundation (from `Flutter/ephemeral/.symlinks/plugins/shared_preferences_foundation/darwin`)
|
||||||
- sqflite_darwin (from `Flutter/ephemeral/.symlinks/plugins/sqflite_darwin/darwin`)
|
- sqflite_darwin (from `Flutter/ephemeral/.symlinks/plugins/sqflite_darwin/darwin`)
|
||||||
- url_launcher_macos (from `Flutter/ephemeral/.symlinks/plugins/url_launcher_macos/macos`)
|
- 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:
|
EXTERNAL SOURCES:
|
||||||
audioplayers_darwin:
|
audioplayers_darwin:
|
||||||
@@ -76,6 +88,8 @@ EXTERNAL SOURCES:
|
|||||||
:path: Flutter/ephemeral/.symlinks/plugins/flutter_avif_macos/macos
|
:path: Flutter/ephemeral/.symlinks/plugins/flutter_avif_macos/macos
|
||||||
flutter_blue_plus_darwin:
|
flutter_blue_plus_darwin:
|
||||||
:path: Flutter/ephemeral/.symlinks/plugins/flutter_blue_plus_darwin/darwin
|
:path: Flutter/ephemeral/.symlinks/plugins/flutter_blue_plus_darwin/darwin
|
||||||
|
flutter_libserialport:
|
||||||
|
:path: Flutter/ephemeral/.symlinks/plugins/flutter_libserialport/macos
|
||||||
flutter_local_notifications:
|
flutter_local_notifications:
|
||||||
:path: Flutter/ephemeral/.symlinks/plugins/flutter_local_notifications/macos
|
:path: Flutter/ephemeral/.symlinks/plugins/flutter_local_notifications/macos
|
||||||
FlutterMacOS:
|
FlutterMacOS:
|
||||||
@@ -98,6 +112,8 @@ EXTERNAL SOURCES:
|
|||||||
:path: Flutter/ephemeral/.symlinks/plugins/sqflite_darwin/darwin
|
:path: Flutter/ephemeral/.symlinks/plugins/sqflite_darwin/darwin
|
||||||
url_launcher_macos:
|
url_launcher_macos:
|
||||||
:path: Flutter/ephemeral/.symlinks/plugins/url_launcher_macos/macos
|
:path: Flutter/ephemeral/.symlinks/plugins/url_launcher_macos/macos
|
||||||
|
wakelock_plus:
|
||||||
|
:path: Flutter/ephemeral/.symlinks/plugins/wakelock_plus/macos
|
||||||
|
|
||||||
SPEC CHECKSUMS:
|
SPEC CHECKSUMS:
|
||||||
audioplayers_darwin: 835ced6edd4c9fc8ebb0a7cc9e294a91d99917d5
|
audioplayers_darwin: 835ced6edd4c9fc8ebb0a7cc9e294a91d99917d5
|
||||||
@@ -107,9 +123,11 @@ SPEC CHECKSUMS:
|
|||||||
file_selector_macos: 9e9e068e90ebee155097d00e89ae91edb2374db7
|
file_selector_macos: 9e9e068e90ebee155097d00e89ae91edb2374db7
|
||||||
flutter_avif_macos: 9ed61d67adfbd6964eccb59971020fb55c31fc11
|
flutter_avif_macos: 9ed61d67adfbd6964eccb59971020fb55c31fc11
|
||||||
flutter_blue_plus_darwin: 20a08bfeaa0f7804d524858d3d8744bcc1b6dbc3
|
flutter_blue_plus_darwin: 20a08bfeaa0f7804d524858d3d8744bcc1b6dbc3
|
||||||
|
flutter_libserialport: 2c523cb8d8203fc6d1b0da88190da31ac970eb93
|
||||||
flutter_local_notifications: 1fc7ffb10a83d6a2eeeeddb152d43f1944b0aad0
|
flutter_local_notifications: 1fc7ffb10a83d6a2eeeeddb152d43f1944b0aad0
|
||||||
FlutterMacOS: d0db08ddef1a9af05a5ec4b724367152bb0500b1
|
FlutterMacOS: d0db08ddef1a9af05a5ec4b724367152bb0500b1
|
||||||
geolocator_apple: ab36aa0e8b7d7a2d7639b3b4e48308394e8cef5e
|
geolocator_apple: ab36aa0e8b7d7a2d7639b3b4e48308394e8cef5e
|
||||||
|
libserialport: 1cb25e66ef3c92a8e59c2ea3820302c3fa2268cd
|
||||||
nsd_macos: a472240e770b92f6c6df1022403aa29c90d012e3
|
nsd_macos: a472240e770b92f6c6df1022403aa29c90d012e3
|
||||||
package_info_plus: f0052d280d17aa382b932f399edf32507174e870
|
package_info_plus: f0052d280d17aa382b932f399edf32507174e870
|
||||||
path_provider_foundation: bb55f6dbba17d0dccd6737fe6f7f34fbd0376880
|
path_provider_foundation: bb55f6dbba17d0dccd6737fe6f7f34fbd0376880
|
||||||
@@ -118,7 +136,8 @@ SPEC CHECKSUMS:
|
|||||||
shared_preferences_foundation: 7036424c3d8ec98dfe75ff1667cb0cd531ec82bb
|
shared_preferences_foundation: 7036424c3d8ec98dfe75ff1667cb0cd531ec82bb
|
||||||
sqflite_darwin: 20b2a3a3b70e43edae938624ce550a3cbf66a3d0
|
sqflite_darwin: 20b2a3a3b70e43edae938624ce550a3cbf66a3d0
|
||||||
url_launcher_macos: f87a979182d112f911de6820aefddaf56ee9fbfd
|
url_launcher_macos: f87a979182d112f911de6820aefddaf56ee9fbfd
|
||||||
|
wakelock_plus: 917609be14d812ddd9e9528876538b2263aaa03b
|
||||||
|
|
||||||
PODFILE CHECKSUM: e3de8f2486e300492cc80a2fe0576e9d269ba22b
|
PODFILE CHECKSUM: 467066e8d30d1105257e0877b8cdd20642e7b3db
|
||||||
|
|
||||||
COCOAPODS: 1.16.2
|
COCOAPODS: 1.16.2
|
||||||
|
|||||||
@@ -557,7 +557,7 @@
|
|||||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||||
MACOSX_DEPLOYMENT_TARGET = 10.15;
|
MACOSX_DEPLOYMENT_TARGET = 26.0;
|
||||||
MTL_ENABLE_DEBUG_INFO = NO;
|
MTL_ENABLE_DEBUG_INFO = NO;
|
||||||
SDKROOT = macosx;
|
SDKROOT = macosx;
|
||||||
SWIFT_COMPILATION_MODE = wholemodule;
|
SWIFT_COMPILATION_MODE = wholemodule;
|
||||||
@@ -639,7 +639,7 @@
|
|||||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||||
MACOSX_DEPLOYMENT_TARGET = 10.15;
|
MACOSX_DEPLOYMENT_TARGET = 26.0;
|
||||||
MTL_ENABLE_DEBUG_INFO = YES;
|
MTL_ENABLE_DEBUG_INFO = YES;
|
||||||
ONLY_ACTIVE_ARCH = YES;
|
ONLY_ACTIVE_ARCH = YES;
|
||||||
SDKROOT = macosx;
|
SDKROOT = macosx;
|
||||||
@@ -689,7 +689,7 @@
|
|||||||
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
|
||||||
GCC_WARN_UNUSED_FUNCTION = YES;
|
GCC_WARN_UNUSED_FUNCTION = YES;
|
||||||
GCC_WARN_UNUSED_VARIABLE = YES;
|
GCC_WARN_UNUSED_VARIABLE = YES;
|
||||||
MACOSX_DEPLOYMENT_TARGET = 10.15;
|
MACOSX_DEPLOYMENT_TARGET = 26.0;
|
||||||
MTL_ENABLE_DEBUG_INFO = NO;
|
MTL_ENABLE_DEBUG_INFO = NO;
|
||||||
SDKROOT = macosx;
|
SDKROOT = macosx;
|
||||||
SWIFT_COMPILATION_MODE = wholemodule;
|
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">
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||||
<plist version="1.0">
|
<plist version="1.0">
|
||||||
<dict>
|
<dict>
|
||||||
<key>com.apple.security.app-sandbox</key>
|
|
||||||
<true/>
|
|
||||||
<key>com.apple.security.cs.allow-jit</key>
|
<key>com.apple.security.cs.allow-jit</key>
|
||||||
<true/>
|
<true/>
|
||||||
<key>com.apple.security.network.server</key>
|
|
||||||
<true/>
|
|
||||||
</dict>
|
</dict>
|
||||||
</plist>
|
</plist>
|
||||||
|
|||||||
@@ -24,10 +24,16 @@
|
|||||||
<false/>
|
<false/>
|
||||||
<key>LSMinimumSystemVersion</key>
|
<key>LSMinimumSystemVersion</key>
|
||||||
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
|
<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>
|
<key>NSHumanReadableCopyright</key>
|
||||||
<string>$(PRODUCT_COPYRIGHT)</string>
|
<string>$(PRODUCT_COPYRIGHT)</string>
|
||||||
<key>NSMainNibFile</key>
|
<key>NSMainNibFile</key>
|
||||||
<string>MainMenu</string>
|
<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>
|
<key>NSMicrophoneUsageDescription</key>
|
||||||
<string>MeshCore SAR needs microphone access to send voice messages over the mesh radio network during SAR operations</string>
|
<string>MeshCore SAR needs microphone access to send voice messages over the mesh radio network during SAR operations</string>
|
||||||
<key>NSPrincipalClass</key>
|
<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">
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||||
<plist version="1.0">
|
<plist version="1.0">
|
||||||
<dict>
|
<dict>
|
||||||
<key>com.apple.security.app-sandbox</key>
|
|
||||||
<true/>
|
|
||||||
</dict>
|
</dict>
|
||||||
</plist>
|
</plist>
|
||||||
|
|||||||
50
pubspec.lock
50
pubspec.lock
@@ -218,6 +218,22 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "7.0.3"
|
version: "7.0.3"
|
||||||
|
dylib:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: dylib
|
||||||
|
sha256: bf609b3eb6492a3309b3d1dbe8f83a4031de5535dd7686be33487051cc760bb0
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "0.3.3"
|
||||||
|
equatable:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: equatable
|
||||||
|
sha256: "3e0141505477fd8ad55d6eb4e7776d3fe8430be8e497ccb1521370c3f21a3e2b"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "2.0.8"
|
||||||
exif:
|
exif:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -298,6 +314,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "1.1.1"
|
version: "1.1.1"
|
||||||
|
fl_chart:
|
||||||
|
dependency: "direct main"
|
||||||
|
description:
|
||||||
|
name: fl_chart
|
||||||
|
sha256: b938f77d042cbcd822936a7a359a7235bad8bd72070de1f827efc2cc297ac888
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "1.2.0"
|
||||||
flutter:
|
flutter:
|
||||||
dependency: "direct main"
|
dependency: "direct main"
|
||||||
description: flutter
|
description: flutter
|
||||||
@@ -479,6 +503,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "0.14.4"
|
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:
|
flutter_lints:
|
||||||
dependency: "direct dev"
|
dependency: "direct dev"
|
||||||
description:
|
description:
|
||||||
@@ -759,6 +791,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "3.0.2"
|
version: "3.0.2"
|
||||||
|
libserialport:
|
||||||
|
dependency: transitive
|
||||||
|
description:
|
||||||
|
name: libserialport
|
||||||
|
sha256: "392e1592def65282429832ec66fa25e9e163d3b37716b97691482e2406720727"
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "0.3.0+1"
|
||||||
lints:
|
lints:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
@@ -788,7 +828,7 @@ packages:
|
|||||||
description:
|
description:
|
||||||
path: "."
|
path: "."
|
||||||
ref: main
|
ref: main
|
||||||
resolved-ref: abff892fac0dd0e8004bfa1f415df74b44b8eb52
|
resolved-ref: "3dbc82170583f616b590e5204a307a02f2b8833d"
|
||||||
url: "https://github.com/dz0ny/meshcore_client.git"
|
url: "https://github.com/dz0ny/meshcore_client.git"
|
||||||
source: git
|
source: git
|
||||||
version: "0.1.0"
|
version: "0.1.0"
|
||||||
@@ -1477,6 +1517,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "1.1.1"
|
version: "1.1.1"
|
||||||
|
webserial:
|
||||||
|
dependency: "direct main"
|
||||||
|
description:
|
||||||
|
name: webserial
|
||||||
|
sha256: b39c2175190ee1c75e996bf137bfee3e3e8fd06ee0ec24f0d3c10bdf7b323786
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "1.2.0"
|
||||||
win32:
|
win32:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
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
|
# 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
|
# 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.
|
# of the product and file versions while build-number is used as the build suffix.
|
||||||
version: 2026.0317.1+33
|
version: 2026.0321.1+37
|
||||||
|
|
||||||
environment:
|
environment:
|
||||||
sdk: ^3.9.2
|
sdk: ^3.9.2
|
||||||
@@ -71,6 +71,7 @@ dependencies:
|
|||||||
url: https://github.com/fleaflet/flutter_map.git
|
url: https://github.com/fleaflet/flutter_map.git
|
||||||
ref: master
|
ref: master
|
||||||
latlong2: ^0.9.0
|
latlong2: ^0.9.0
|
||||||
|
fl_chart: ^1.2.0
|
||||||
|
|
||||||
http: ^1.2.0
|
http: ^1.2.0
|
||||||
|
|
||||||
@@ -123,6 +124,8 @@ dependencies:
|
|||||||
nsd: ^4.0.3
|
nsd: ^4.0.3
|
||||||
usb_serial: ^0.5.2
|
usb_serial: ^0.5.2
|
||||||
web: ^1.1.1
|
web: ^1.1.1
|
||||||
|
flutter_libserialport: ^0.6.0
|
||||||
|
webserial: ^1.2.0
|
||||||
|
|
||||||
dev_dependencies:
|
dev_dependencies:
|
||||||
flutter_test:
|
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==');
|
||||||
|
});
|
||||||
|
}
|
||||||
25
test/providers/channels_provider_test.dart
Normal file
25
test/providers/channels_provider_test.dart
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:meshcore_sar_app/providers/channels_provider.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
group('ChannelsProvider device sync preparation', () {
|
||||||
|
test('clears runtime channel state before sync', () {
|
||||||
|
final provider = ChannelsProvider();
|
||||||
|
|
||||||
|
provider.addOrUpdateChannel(
|
||||||
|
index: 2,
|
||||||
|
name: 'Ops',
|
||||||
|
secret: Uint8List.fromList(List<int>.filled(16, 7)),
|
||||||
|
);
|
||||||
|
provider.selectChannel(2);
|
||||||
|
|
||||||
|
provider.prepareForDeviceSync();
|
||||||
|
|
||||||
|
expect(provider.channels, isEmpty);
|
||||||
|
expect(provider.selectedChannelIndex, 0);
|
||||||
|
expect(provider.selectedChannel, isNull);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
69
test/providers/contacts_provider_profile_scope_test.dart
Normal file
69
test/providers/contacts_provider_profile_scope_test.dart
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:meshcore_sar_app/models/contact.dart';
|
||||||
|
import 'package:meshcore_sar_app/providers/contacts_provider.dart';
|
||||||
|
import 'package:meshcore_sar_app/services/contact_storage_service.dart';
|
||||||
|
import 'package:meshcore_sar_app/services/profiles_feature_service.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
TestWidgetsFlutterBinding.ensureInitialized();
|
||||||
|
|
||||||
|
Contact createContact({required Uint8List key, required String name}) {
|
||||||
|
return Contact(
|
||||||
|
publicKey: key,
|
||||||
|
type: ContactType.chat,
|
||||||
|
flags: 0,
|
||||||
|
outPathLen: 0,
|
||||||
|
outPath: Uint8List(64),
|
||||||
|
advName: name,
|
||||||
|
lastAdvert: DateTime.now().millisecondsSinceEpoch ~/ 1000,
|
||||||
|
advLat: (46.0569 * 1e6).round(),
|
||||||
|
advLon: (14.5058 * 1e6).round(),
|
||||||
|
lastMod: DateTime.now().millisecondsSinceEpoch ~/ 1000,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
setUp(() {
|
||||||
|
SharedPreferences.setMockInitialValues({});
|
||||||
|
ProfileStorageScope.setScope(
|
||||||
|
profilesEnabled: true,
|
||||||
|
activeProfileId: 'default',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test(
|
||||||
|
'initializeEarly respects the active profile storage namespace',
|
||||||
|
() async {
|
||||||
|
final storage = ContactStorageService();
|
||||||
|
final defaultContact = createContact(
|
||||||
|
key: Uint8List.fromList(List<int>.filled(32, 1)),
|
||||||
|
name: 'Default Contact',
|
||||||
|
);
|
||||||
|
final alphaContact = createContact(
|
||||||
|
key: Uint8List.fromList(List<int>.filled(32, 2)),
|
||||||
|
name: 'Alpha Contact',
|
||||||
|
);
|
||||||
|
|
||||||
|
await storage.saveContacts([defaultContact]);
|
||||||
|
await storage.saveContacts([alphaContact], namespace: 'alpha');
|
||||||
|
|
||||||
|
ProfileStorageScope.setScope(
|
||||||
|
profilesEnabled: true,
|
||||||
|
activeProfileId: 'alpha',
|
||||||
|
);
|
||||||
|
|
||||||
|
final provider = ContactsProvider();
|
||||||
|
await provider.initializeEarly();
|
||||||
|
|
||||||
|
final names = provider.contacts
|
||||||
|
.where((contact) => !contact.isChannel)
|
||||||
|
.map((contact) => contact.advName)
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
expect(names, <String>['Alpha Contact']);
|
||||||
|
expect(provider.storageNamespace, 'alpha');
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -173,14 +173,8 @@ void main() {
|
|||||||
var updated = scopedProvider.findContactByKey(scopedKey)!;
|
var updated = scopedProvider.findContactByKey(scopedKey)!;
|
||||||
expect(updated.telemetry, isNotNull);
|
expect(updated.telemetry, isNotNull);
|
||||||
expect(updated.telemetry!.gpsLocation, isNull);
|
expect(updated.telemetry!.gpsLocation, isNull);
|
||||||
expect(
|
expect(updated.displayLocation!.latitude, closeTo(45.1234, 0.0001));
|
||||||
updated.displayLocation!.latitude,
|
expect(updated.displayLocation!.longitude, closeTo(13.8765, 0.0001));
|
||||||
closeTo(45.1234, 0.0001),
|
|
||||||
);
|
|
||||||
expect(
|
|
||||||
updated.displayLocation!.longitude,
|
|
||||||
closeTo(13.8765, 0.0001),
|
|
||||||
);
|
|
||||||
|
|
||||||
// Invalid 0,0 GPS frame should behave the same way.
|
// Invalid 0,0 GPS frame should behave the same way.
|
||||||
final invalidGps = CayenneLppParser.createGpsData(
|
final invalidGps = CayenneLppParser.createGpsData(
|
||||||
@@ -192,14 +186,8 @@ void main() {
|
|||||||
updated = scopedProvider.findContactByKey(scopedKey)!;
|
updated = scopedProvider.findContactByKey(scopedKey)!;
|
||||||
expect(updated.telemetry, isNotNull);
|
expect(updated.telemetry, isNotNull);
|
||||||
expect(updated.telemetry!.gpsLocation, isNull);
|
expect(updated.telemetry!.gpsLocation, isNull);
|
||||||
expect(
|
expect(updated.displayLocation!.latitude, closeTo(45.1234, 0.0001));
|
||||||
updated.displayLocation!.latitude,
|
expect(updated.displayLocation!.longitude, closeTo(13.8765, 0.0001));
|
||||||
closeTo(45.1234, 0.0001),
|
|
||||||
);
|
|
||||||
expect(
|
|
||||||
updated.displayLocation!.longitude,
|
|
||||||
closeTo(13.8765, 0.0001),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
@@ -337,95 +325,107 @@ void main() {
|
|||||||
expect(updated.telemetry!.extraSensorData, containsPair('co2', 415.0));
|
expect(updated.telemetry!.extraSensorData, containsPair('co2', 415.0));
|
||||||
});
|
});
|
||||||
|
|
||||||
test('retains scalar telemetry but wipes stale extra sensor fields on refresh', () {
|
test(
|
||||||
final fullTelemetry = ContactTelemetry(
|
'retains scalar telemetry but wipes stale extra sensor fields on refresh',
|
||||||
gpsLocation: const LatLng(46.0569, 14.5058),
|
() {
|
||||||
batteryPercentage: 54.0,
|
final fullTelemetry = ContactTelemetry(
|
||||||
batteryMilliVolts: 3780,
|
gpsLocation: const LatLng(46.0569, 14.5058),
|
||||||
temperature: 19.5,
|
batteryPercentage: 54.0,
|
||||||
timestamp: DateTime.now().subtract(const Duration(minutes: 2)),
|
batteryMilliVolts: 3780,
|
||||||
humidity: 58.0,
|
temperature: 19.5,
|
||||||
pressure: 1011.2,
|
timestamp: DateTime.now().subtract(const Duration(minutes: 2)),
|
||||||
extraSensorData: const {'pm25': 8.0},
|
humidity: 58.0,
|
||||||
);
|
pressure: 1011.2,
|
||||||
|
extraSensorData: const {'pm25': 8.0},
|
||||||
|
);
|
||||||
|
|
||||||
provider.addOrUpdateContact(
|
provider.addOrUpdateContact(
|
||||||
createContact(
|
createContact(
|
||||||
key: publicKey,
|
key: publicKey,
|
||||||
type: ContactType.chat,
|
type: ContactType.chat,
|
||||||
).copyWith(telemetry: fullTelemetry),
|
).copyWith(telemetry: fullTelemetry),
|
||||||
);
|
);
|
||||||
|
|
||||||
final batteryOnly = CayenneLppParser.createBatteryData(3.95);
|
final batteryOnly = CayenneLppParser.createBatteryData(3.95);
|
||||||
provider.updateTelemetry(publicKey.sublist(0, 6), batteryOnly);
|
provider.updateTelemetry(publicKey.sublist(0, 6), batteryOnly);
|
||||||
|
|
||||||
final updated = provider.findContactByKey(publicKey)!;
|
final updated = provider.findContactByKey(publicKey)!;
|
||||||
expect(updated.telemetry, isNotNull);
|
expect(updated.telemetry, isNotNull);
|
||||||
expect(updated.telemetry!.gpsLocation, isNull);
|
expect(updated.telemetry!.gpsLocation, isNull);
|
||||||
expect(updated.displayLocation, const LatLng(46.0569, 14.5058));
|
expect(updated.displayLocation, const LatLng(46.0569, 14.5058));
|
||||||
expect(updated.telemetry!.batteryMilliVolts, isNotNull);
|
expect(updated.telemetry!.batteryMilliVolts, isNotNull);
|
||||||
expect(updated.telemetry!.batteryPercentage, isNotNull);
|
expect(updated.telemetry!.batteryPercentage, isNotNull);
|
||||||
expect(updated.telemetry!.temperature, equals(19.5));
|
expect(updated.telemetry!.temperature, equals(19.5));
|
||||||
expect(updated.telemetry!.humidity, equals(58.0));
|
expect(updated.telemetry!.humidity, equals(58.0));
|
||||||
expect(updated.telemetry!.pressure, equals(1011.2));
|
expect(updated.telemetry!.pressure, equals(1011.2));
|
||||||
expect(
|
expect(
|
||||||
updated.telemetry!.extraSensorData,
|
updated.telemetry!.extraSensorData,
|
||||||
containsPair('__source_channel:battery', 0),
|
containsPair('__source_channel:battery', 0),
|
||||||
);
|
);
|
||||||
expect(
|
expect(
|
||||||
updated.telemetry!.extraSensorData,
|
updated.telemetry!.extraSensorData,
|
||||||
containsPair('__source_channel:voltage', 0),
|
containsPair('__source_channel:voltage', 0),
|
||||||
);
|
);
|
||||||
expect(updated.telemetry!.extraSensorData, isNot(contains('pm25')));
|
expect(updated.telemetry!.extraSensorData, isNot(contains('pm25')));
|
||||||
});
|
},
|
||||||
|
);
|
||||||
|
|
||||||
test('replaces old source-channel mappings when a metric moves channels', () {
|
test(
|
||||||
final initialTelemetry = ContactTelemetry(
|
'replaces old source-channel mappings when a metric moves channels',
|
||||||
gpsLocation: null,
|
() {
|
||||||
batteryPercentage: null,
|
final initialTelemetry = ContactTelemetry(
|
||||||
batteryMilliVolts: null,
|
gpsLocation: null,
|
||||||
temperature: 21.5,
|
batteryPercentage: null,
|
||||||
timestamp: DateTime.now().subtract(const Duration(minutes: 2)),
|
batteryMilliVolts: null,
|
||||||
humidity: null,
|
temperature: 21.5,
|
||||||
pressure: null,
|
timestamp: DateTime.now().subtract(const Duration(minutes: 2)),
|
||||||
extraSensorData: const {
|
humidity: null,
|
||||||
'__source_channel:temperature': 2,
|
pressure: null,
|
||||||
'temperature_2': 21.5,
|
extraSensorData: const {
|
||||||
'humidity_4': 66.0,
|
'__source_channel:temperature': 2,
|
||||||
},
|
'temperature_2': 21.5,
|
||||||
);
|
'humidity_4': 66.0,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
provider.addOrUpdateContact(
|
provider.addOrUpdateContact(
|
||||||
createContact(
|
createContact(
|
||||||
key: publicKey,
|
key: publicKey,
|
||||||
type: ContactType.chat,
|
type: ContactType.chat,
|
||||||
).copyWith(telemetry: initialTelemetry),
|
).copyWith(telemetry: initialTelemetry),
|
||||||
);
|
);
|
||||||
|
|
||||||
final movedChannelTelemetry = CayenneLppParser.createTemperatureData(
|
final movedChannelTelemetry = CayenneLppParser.createTemperatureData(
|
||||||
23.5,
|
23.5,
|
||||||
channel: 3,
|
channel: 3,
|
||||||
);
|
);
|
||||||
|
|
||||||
provider.updateTelemetry(publicKey.sublist(0, 6), movedChannelTelemetry);
|
provider.updateTelemetry(
|
||||||
|
publicKey.sublist(0, 6),
|
||||||
|
movedChannelTelemetry,
|
||||||
|
);
|
||||||
|
|
||||||
final updated = provider.findContactByKey(publicKey)!;
|
final updated = provider.findContactByKey(publicKey)!;
|
||||||
expect(updated.telemetry, isNotNull);
|
expect(updated.telemetry, isNotNull);
|
||||||
expect(updated.telemetry!.temperature, closeTo(23.5, 0.1));
|
expect(updated.telemetry!.temperature, closeTo(23.5, 0.1));
|
||||||
expect(
|
expect(
|
||||||
updated.telemetry!.extraSensorData,
|
updated.telemetry!.extraSensorData,
|
||||||
containsPair('__source_channel:temperature', 3),
|
containsPair('__source_channel:temperature', 3),
|
||||||
);
|
);
|
||||||
expect(
|
expect(
|
||||||
updated.telemetry!.extraSensorData,
|
updated.telemetry!.extraSensorData,
|
||||||
containsPair('temperature_3', closeTo(23.5, 0.1)),
|
containsPair('temperature_3', closeTo(23.5, 0.1)),
|
||||||
);
|
);
|
||||||
expect(
|
expect(
|
||||||
updated.telemetry!.extraSensorData,
|
updated.telemetry!.extraSensorData,
|
||||||
isNot(contains('temperature_2')),
|
isNot(contains('temperature_2')),
|
||||||
);
|
);
|
||||||
expect(updated.telemetry!.extraSensorData, isNot(contains('humidity_4')));
|
expect(
|
||||||
});
|
updated.telemetry!.extraSensorData,
|
||||||
|
isNot(contains('humidity_4')),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
test('builds message snapshot from latest valid telemetry', () {
|
test('builds message snapshot from latest valid telemetry', () {
|
||||||
final telemetryData = CayenneLppParser.createGpsData(
|
final telemetryData = CayenneLppParser.createGpsData(
|
||||||
@@ -870,6 +870,71 @@ void main() {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
group('ContactsProvider device sync preparation', () {
|
||||||
|
late ContactsProvider provider;
|
||||||
|
|
||||||
|
setUp(() {
|
||||||
|
SharedPreferences.setMockInitialValues({});
|
||||||
|
provider = ContactsProvider();
|
||||||
|
});
|
||||||
|
|
||||||
|
test(
|
||||||
|
'clears runtime contacts before sync without erasing persisted contacts or saved groups',
|
||||||
|
() async {
|
||||||
|
final key = createPublicKey(140);
|
||||||
|
final pendingKey = createPublicKey(180);
|
||||||
|
|
||||||
|
provider.addOrUpdateContact(
|
||||||
|
createContact(key: key, type: ContactType.chat, name: 'Synced Later'),
|
||||||
|
);
|
||||||
|
provider.addPendingAdvert(pendingKey);
|
||||||
|
await provider.addSavedGroupForFilter('teamMembers', 'alpha');
|
||||||
|
|
||||||
|
await provider.prepareForDeviceContactSync();
|
||||||
|
|
||||||
|
expect(provider.chatContacts, isEmpty);
|
||||||
|
expect(provider.pendingAdverts, isEmpty);
|
||||||
|
expect(provider.savedGroupsForSection('teamMembers'), hasLength(1));
|
||||||
|
|
||||||
|
final restored = ContactsProvider();
|
||||||
|
await restored.initializeEarly();
|
||||||
|
|
||||||
|
expect(
|
||||||
|
restored.chatContacts.map((contact) => contact.advName),
|
||||||
|
contains('Synced Later'),
|
||||||
|
);
|
||||||
|
expect(restored.savedGroupsForSection('teamMembers'), hasLength(1));
|
||||||
|
},
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
group('ContactsProvider self telemetry', () {
|
||||||
|
test(
|
||||||
|
'stores self telemetry without re-adding the device as a contact',
|
||||||
|
() async {
|
||||||
|
SharedPreferences.setMockInitialValues({});
|
||||||
|
final provider = ContactsProvider();
|
||||||
|
final selfKey = createPublicKey(200);
|
||||||
|
|
||||||
|
await provider.initialize(devicePublicKey: selfKey);
|
||||||
|
provider.updateTelemetry(
|
||||||
|
selfKey.sublist(0, 6),
|
||||||
|
CayenneLppParser.createTemperatureData(23.5, channel: 1),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(provider.selfTelemetry, isNotNull);
|
||||||
|
expect(provider.selfTelemetry!.temperature, closeTo(23.5, 0.1));
|
||||||
|
expect(provider.findContactByKey(selfKey), isNull);
|
||||||
|
expect(
|
||||||
|
provider.contacts.any(
|
||||||
|
(contact) => contact.publicKeyHex == publicKeyHex(selfKey),
|
||||||
|
),
|
||||||
|
isFalse,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
String publicKeyHex(Uint8List publicKey) {
|
String publicKeyHex(Uint8List publicKey) {
|
||||||
|
|||||||
134
test/providers/media_provider_profile_scope_test.dart
Normal file
134
test/providers/media_provider_profile_scope_test.dart
Normal file
@@ -0,0 +1,134 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:meshcore_sar_app/providers/image_provider.dart';
|
||||||
|
import 'package:meshcore_sar_app/providers/voice_provider.dart';
|
||||||
|
import 'package:meshcore_sar_app/services/profiles_feature_service.dart';
|
||||||
|
import 'package:meshcore_sar_app/services/voice_codec_service.dart';
|
||||||
|
import 'package:meshcore_sar_app/services/voice_player_service.dart';
|
||||||
|
import 'package:meshcore_sar_app/utils/image_message_parser.dart';
|
||||||
|
import 'package:meshcore_sar_app/utils/voice_message_parser.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
TestWidgetsFlutterBinding.ensureInitialized();
|
||||||
|
|
||||||
|
setUp(() {
|
||||||
|
SharedPreferences.setMockInitialValues({});
|
||||||
|
ProfileStorageScope.setScope(
|
||||||
|
profilesEnabled: true,
|
||||||
|
activeProfileId: 'alpha',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('VoiceProvider reloads profile-scoped sessions', () async {
|
||||||
|
final player = _FakeVoicePlayerService();
|
||||||
|
final provider = VoiceProvider(codec: VoiceCodecService(), player: player);
|
||||||
|
addTearDown(provider.dispose);
|
||||||
|
|
||||||
|
await provider.reloadProfileScopedState();
|
||||||
|
provider.registerEnvelope(
|
||||||
|
const VoiceEnvelope(
|
||||||
|
sessionId: 'a1b2c3d4',
|
||||||
|
mode: VoicePacketMode.mode1200,
|
||||||
|
total: 2,
|
||||||
|
durationMs: 1600,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await Future<void>.delayed(const Duration(milliseconds: 50));
|
||||||
|
|
||||||
|
ProfileStorageScope.setScope(
|
||||||
|
profilesEnabled: true,
|
||||||
|
activeProfileId: 'beta',
|
||||||
|
);
|
||||||
|
await provider.reloadProfileScopedState();
|
||||||
|
expect(provider.session('a1b2c3d4'), isNull);
|
||||||
|
|
||||||
|
ProfileStorageScope.setScope(
|
||||||
|
profilesEnabled: true,
|
||||||
|
activeProfileId: 'alpha',
|
||||||
|
);
|
||||||
|
await provider.reloadProfileScopedState();
|
||||||
|
expect(provider.session('a1b2c3d4'), isNotNull);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('ImageProvider reloads profile-scoped sessions', () async {
|
||||||
|
final provider = ImageProvider();
|
||||||
|
|
||||||
|
await provider.reloadProfileScopedState();
|
||||||
|
provider.registerEnvelope(
|
||||||
|
const ImageEnvelope(
|
||||||
|
sessionId: 'a1b2c3d4',
|
||||||
|
format: ImageFormat.avif,
|
||||||
|
total: 2,
|
||||||
|
width: 32,
|
||||||
|
height: 32,
|
||||||
|
sizeBytes: 8,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
provider.addFragment(
|
||||||
|
ImagePacket(
|
||||||
|
sessionId: 'a1b2c3d4',
|
||||||
|
format: ImageFormat.avif,
|
||||||
|
index: 0,
|
||||||
|
total: 2,
|
||||||
|
data: Uint8List.fromList([1, 2, 3, 4]),
|
||||||
|
),
|
||||||
|
width: 32,
|
||||||
|
height: 32,
|
||||||
|
);
|
||||||
|
await Future<void>.delayed(const Duration(milliseconds: 50));
|
||||||
|
|
||||||
|
ProfileStorageScope.setScope(
|
||||||
|
profilesEnabled: true,
|
||||||
|
activeProfileId: 'beta',
|
||||||
|
);
|
||||||
|
await provider.reloadProfileScopedState();
|
||||||
|
expect(provider.session('a1b2c3d4'), isNull);
|
||||||
|
|
||||||
|
ProfileStorageScope.setScope(
|
||||||
|
profilesEnabled: true,
|
||||||
|
activeProfileId: 'alpha',
|
||||||
|
);
|
||||||
|
await provider.reloadProfileScopedState();
|
||||||
|
expect(provider.session('a1b2c3d4'), isNotNull);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
class _FakeVoicePlayerService implements VoicePlayerService {
|
||||||
|
final StreamController<void> _events = StreamController<void>.broadcast();
|
||||||
|
bool _isPlaying = false;
|
||||||
|
|
||||||
|
@override
|
||||||
|
bool get isPlaying => _isPlaying;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Duration get position => Duration.zero;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Duration get duration => Duration.zero;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Stream<void> get events => _events.stream;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> play(Int16List pcmSamples, {required int sampleRateHz}) async {
|
||||||
|
_isPlaying = true;
|
||||||
|
_events.add(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> stop() async {
|
||||||
|
_isPlaying = false;
|
||||||
|
_events.add(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
_events.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
|
||||||
|
}
|
||||||
@@ -390,6 +390,38 @@ void main() {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('incoming contact messages dedupe by sender handle and text', () {
|
||||||
|
final provider = MessagesProvider();
|
||||||
|
|
||||||
|
provider.addMessage(
|
||||||
|
Message(
|
||||||
|
id: 'handle-1',
|
||||||
|
messageType: MessageType.contact,
|
||||||
|
pathLen: 1,
|
||||||
|
textType: MessageTextType.plain,
|
||||||
|
senderTimestamp: 1700000800,
|
||||||
|
text: 'same payload',
|
||||||
|
senderName: 'Radio Alpha',
|
||||||
|
receivedAt: DateTime.now(),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
provider.addMessage(
|
||||||
|
Message(
|
||||||
|
id: 'handle-2',
|
||||||
|
messageType: MessageType.contact,
|
||||||
|
pathLen: 2,
|
||||||
|
textType: MessageTextType.plain,
|
||||||
|
senderTimestamp: 1700000810,
|
||||||
|
text: 'same payload',
|
||||||
|
senderName: 'Radio Alpha',
|
||||||
|
receivedAt: DateTime.now(),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(provider.messages, hasLength(1));
|
||||||
|
expect(provider.messages.single.id, equals('handle-1'));
|
||||||
|
});
|
||||||
|
|
||||||
test('display list collapses stored duplicates and sums copy counts', () {
|
test('display list collapses stored duplicates and sums copy counts', () {
|
||||||
final provider = MessagesProvider();
|
final provider = MessagesProvider();
|
||||||
final sender = Uint8List.fromList([5, 4, 3, 2, 1, 0]);
|
final sender = Uint8List.fromList([5, 4, 3, 2, 1, 0]);
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import 'package:meshcore_sar_app/models/device_info.dart';
|
|||||||
import 'package:meshcore_sar_app/providers/connection_provider.dart';
|
import 'package:meshcore_sar_app/providers/connection_provider.dart';
|
||||||
import 'package:meshcore_sar_app/providers/contacts_provider.dart';
|
import 'package:meshcore_sar_app/providers/contacts_provider.dart';
|
||||||
import 'package:meshcore_sar_app/providers/sensors_provider.dart';
|
import 'package:meshcore_sar_app/providers/sensors_provider.dart';
|
||||||
|
import 'package:meshcore_sar_app/services/cayenne_lpp_parser.dart';
|
||||||
import 'package:meshcore_sar_app/services/profiles_feature_service.dart';
|
import 'package:meshcore_sar_app/services/profiles_feature_service.dart';
|
||||||
import 'package:shared_preferences/shared_preferences.dart';
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
|
||||||
@@ -19,10 +20,17 @@ class _FakeContactsProvider extends ContactsProvider {
|
|||||||
}
|
}
|
||||||
|
|
||||||
class _FakeConnectionProvider extends ConnectionProvider {
|
class _FakeConnectionProvider extends ConnectionProvider {
|
||||||
_FakeConnectionProvider({required bool isConnected})
|
_FakeConnectionProvider({
|
||||||
: _isConnected = isConnected;
|
required bool isConnected,
|
||||||
|
Uint8List? publicKey,
|
||||||
|
String? selfName,
|
||||||
|
}) : _isConnected = isConnected,
|
||||||
|
_publicKey = publicKey,
|
||||||
|
_selfName = selfName;
|
||||||
|
|
||||||
final bool _isConnected;
|
final bool _isConnected;
|
||||||
|
final Uint8List? _publicKey;
|
||||||
|
final String? _selfName;
|
||||||
|
|
||||||
int pingCalls = 0;
|
int pingCalls = 0;
|
||||||
|
|
||||||
@@ -31,6 +39,8 @@ class _FakeConnectionProvider extends ConnectionProvider {
|
|||||||
connectionState: _isConnected
|
connectionState: _isConnected
|
||||||
? ConnectionState.connected
|
? ConnectionState.connected
|
||||||
: ConnectionState.disconnected,
|
: ConnectionState.disconnected,
|
||||||
|
publicKey: _publicKey,
|
||||||
|
selfName: _selfName,
|
||||||
);
|
);
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@@ -65,9 +75,12 @@ void main() {
|
|||||||
expect(provider.isLoaded, isTrue);
|
expect(provider.isLoaded, isTrue);
|
||||||
}
|
}
|
||||||
|
|
||||||
Contact buildSensorContact() {
|
Contact buildSensorContact({
|
||||||
|
int firstByte = 0x44,
|
||||||
|
String name = 'WX Station',
|
||||||
|
}) {
|
||||||
final publicKey = Uint8List(32);
|
final publicKey = Uint8List(32);
|
||||||
publicKey[0] = 0x44;
|
publicKey[0] = firstByte;
|
||||||
|
|
||||||
return Contact(
|
return Contact(
|
||||||
publicKey: publicKey,
|
publicKey: publicKey,
|
||||||
@@ -75,7 +88,7 @@ void main() {
|
|||||||
flags: 0,
|
flags: 0,
|
||||||
outPathLen: 0,
|
outPathLen: 0,
|
||||||
outPath: Uint8List(64),
|
outPath: Uint8List(64),
|
||||||
advName: 'WX Station',
|
advName: name,
|
||||||
lastAdvert: DateTime.now().millisecondsSinceEpoch ~/ 1000,
|
lastAdvert: DateTime.now().millisecondsSinceEpoch ~/ 1000,
|
||||||
advLat: 0,
|
advLat: 0,
|
||||||
advLon: 0,
|
advLon: 0,
|
||||||
@@ -264,6 +277,36 @@ void main() {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('watched sensor order persists across reloads', () async {
|
||||||
|
SharedPreferences.setMockInitialValues({});
|
||||||
|
final first = buildSensorContact(firstByte: 0x44, name: 'First');
|
||||||
|
final second = buildSensorContact(firstByte: 0x45, name: 'Second');
|
||||||
|
final third = buildSensorContact(firstByte: 0x46, name: 'Third');
|
||||||
|
|
||||||
|
final provider = SensorsProvider();
|
||||||
|
await waitUntilLoaded(provider);
|
||||||
|
await provider.addSensor(first);
|
||||||
|
await provider.addSensor(second);
|
||||||
|
await provider.addSensor(third);
|
||||||
|
|
||||||
|
await provider.reorderSensors(2, 0);
|
||||||
|
|
||||||
|
expect(provider.watchedSensorKeys, <String>[
|
||||||
|
third.publicKeyHex,
|
||||||
|
first.publicKeyHex,
|
||||||
|
second.publicKeyHex,
|
||||||
|
]);
|
||||||
|
|
||||||
|
final reloadedProvider = SensorsProvider();
|
||||||
|
await waitUntilLoaded(reloadedProvider);
|
||||||
|
|
||||||
|
expect(reloadedProvider.watchedSensorKeys, <String>[
|
||||||
|
third.publicKeyHex,
|
||||||
|
first.publicKeyHex,
|
||||||
|
second.publicKeyHex,
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
test(
|
test(
|
||||||
'unsupported auto refresh minutes normalize to nearest option',
|
'unsupported auto refresh minutes normalize to nearest option',
|
||||||
() async {
|
() async {
|
||||||
@@ -340,4 +383,32 @@ void main() {
|
|||||||
);
|
);
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
test('selfContact includes stored self telemetry', () async {
|
||||||
|
SharedPreferences.setMockInitialValues({});
|
||||||
|
final selfKey = Uint8List(32)..[0] = 0x66;
|
||||||
|
final contactsProvider = ContactsProvider();
|
||||||
|
await contactsProvider.initialize(devicePublicKey: selfKey);
|
||||||
|
contactsProvider.updateTelemetry(
|
||||||
|
selfKey.sublist(0, 6),
|
||||||
|
CayenneLppParser.createTemperatureData(19.5, channel: 1),
|
||||||
|
);
|
||||||
|
|
||||||
|
final connectionProvider = _FakeConnectionProvider(
|
||||||
|
isConnected: true,
|
||||||
|
publicKey: selfKey,
|
||||||
|
selfName: 'My Device',
|
||||||
|
);
|
||||||
|
final provider = SensorsProvider();
|
||||||
|
await waitUntilLoaded(provider);
|
||||||
|
|
||||||
|
final selfContact = provider.selfContact(
|
||||||
|
contactsProvider,
|
||||||
|
connectionProvider,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(selfContact, isNotNull);
|
||||||
|
expect(selfContact!.telemetry, isNotNull);
|
||||||
|
expect(selfContact.telemetry!.temperature, closeTo(19.5, 0.1));
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,22 +1,80 @@
|
|||||||
import 'dart:typed_data';
|
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
import 'package:flutter_test/flutter_test.dart';
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
import 'package:meshcore_sar_app/l10n/app_localizations.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.dart';
|
||||||
import 'package:meshcore_sar_app/models/contact_group.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/connection_provider.dart';
|
||||||
import 'package:meshcore_sar_app/providers/contacts_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/map_provider.dart';
|
||||||
import 'package:meshcore_sar_app/providers/messages_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/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:meshcore_sar_app/utils/contact_grouping.dart';
|
||||||
import 'package:provider/provider.dart';
|
import 'package:provider/provider.dart';
|
||||||
import 'package:shared_preferences/shared_preferences.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() {
|
void main() {
|
||||||
|
String? clipboardText;
|
||||||
|
|
||||||
setUp(() {
|
setUp(() {
|
||||||
SharedPreferences.setMockInitialValues({});
|
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}) {
|
Contact buildChannel({required String name, required int channelIndex}) {
|
||||||
@@ -80,8 +138,28 @@ void main() {
|
|||||||
WidgetTester tester, {
|
WidgetTester tester, {
|
||||||
List<Contact> contacts = const [],
|
List<Contact> contacts = const [],
|
||||||
List<SavedContactGroup> savedGroups = const [],
|
List<SavedContactGroup> savedGroups = const [],
|
||||||
|
ConnectionProvider? connectionProvider,
|
||||||
}) async {
|
}) async {
|
||||||
final contactsProvider = ContactsProvider();
|
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) {
|
for (final contact in contacts) {
|
||||||
contactsProvider.addOrUpdateContact(contact);
|
contactsProvider.addOrUpdateContact(contact);
|
||||||
}
|
}
|
||||||
@@ -95,10 +173,17 @@ void main() {
|
|||||||
await tester.pumpWidget(
|
await tester.pumpWidget(
|
||||||
MultiProvider(
|
MultiProvider(
|
||||||
providers: [
|
providers: [
|
||||||
ChangeNotifierProvider.value(value: contactsProvider),
|
ChangeNotifierProvider<ContactsProvider>(
|
||||||
ChangeNotifierProvider(create: (_) => ConnectionProvider()),
|
create: (_) => contactsProvider,
|
||||||
ChangeNotifierProvider(create: (_) => MessagesProvider()),
|
),
|
||||||
|
ChangeNotifierProvider<ConnectionProvider>(
|
||||||
|
create: (_) => resolvedConnectionProvider,
|
||||||
|
),
|
||||||
|
ChangeNotifierProvider<MessagesProvider>(
|
||||||
|
create: (_) => messagesProvider,
|
||||||
|
),
|
||||||
ChangeNotifierProvider(create: (_) => MapProvider()),
|
ChangeNotifierProvider(create: (_) => MapProvider()),
|
||||||
|
ChangeNotifierProvider<AppProvider>(create: (_) => appProvider),
|
||||||
],
|
],
|
||||||
child: MaterialApp(
|
child: MaterialApp(
|
||||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||||
@@ -123,6 +208,7 @@ void main() {
|
|||||||
await tester.tap(find.text('Ops'));
|
await tester.tap(find.text('Ops'));
|
||||||
await tester.pumpAndSettle();
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(find.text('Export psk_base64'), findsNothing);
|
||||||
expect(find.text('Delete Channel'), findsOneWidget);
|
expect(find.text('Delete Channel'), findsOneWidget);
|
||||||
|
|
||||||
await tester.tap(find.text('Delete Channel'));
|
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', (
|
testWidgets('repeaters show Others group when multiple groups exist', (
|
||||||
tester,
|
tester,
|
||||||
) async {
|
) async {
|
||||||
@@ -218,7 +324,25 @@ void main() {
|
|||||||
contacts: [buildSensor(seed: 60, name: 'WX Station')],
|
contacts: [buildSensor(seed: 60, name: 'WX Station')],
|
||||||
);
|
);
|
||||||
|
|
||||||
expect(find.text('Sensors'), findsOneWidget);
|
expect(find.text('Sensors'), findsWidgets);
|
||||||
expect(find.text('WX Station'), findsOneWidget);
|
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/material.dart';
|
||||||
import 'package:flutter_test/flutter_test.dart';
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
import 'package:meshcore_sar_app/models/ble_packet_log.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';
|
import 'package:meshcore_sar_app/screens/live_traffic_screen.dart';
|
||||||
|
|
||||||
BlePacketLog _log({
|
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() {
|
void main() {
|
||||||
testWidgets('shows empty state before traffic arrives', (tester) async {
|
testWidgets('shows empty state before traffic arrives', (tester) async {
|
||||||
final logs = <BlePacketLog>[];
|
final logs = <BlePacketLog>[];
|
||||||
@@ -57,8 +66,8 @@ void main() {
|
|||||||
DateTime now = DateTime(2026, 3, 12, 12, 0, 0);
|
DateTime now = DateTime(2026, 3, 12, 12, 0, 0);
|
||||||
|
|
||||||
await tester.pumpWidget(
|
await tester.pumpWidget(
|
||||||
MaterialApp(
|
_testApp(
|
||||||
home: LiveTrafficScreen(
|
LiveTrafficScreen(
|
||||||
logReader: () => logs,
|
logReader: () => logs,
|
||||||
refreshListenable: refresh,
|
refreshListenable: refresh,
|
||||||
now: () => now,
|
now: () => now,
|
||||||
@@ -78,10 +87,9 @@ void main() {
|
|||||||
DateTime now = DateTime(2026, 3, 12, 12, 0, 0);
|
DateTime now = DateTime(2026, 3, 12, 12, 0, 0);
|
||||||
|
|
||||||
await tester.pumpWidget(
|
await tester.pumpWidget(
|
||||||
MaterialApp(
|
_testApp(
|
||||||
home: LiveTrafficScreen(
|
LiveTrafficScreen(
|
||||||
logReader: () => logs,
|
logReader: () => logs,
|
||||||
rxCountReader: () => 7,
|
|
||||||
refreshListenable: refresh,
|
refreshListenable: refresh,
|
||||||
now: () => now,
|
now: () => now,
|
||||||
),
|
),
|
||||||
@@ -114,10 +122,9 @@ void main() {
|
|||||||
await tester.pump();
|
await tester.pump();
|
||||||
|
|
||||||
expect(find.text('1 pkt/min'), findsOneWidget);
|
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('FLOOD RESPONSE'), findsOneWidget);
|
||||||
expect(find.text('MULTI-HOP'), findsOneWidget);
|
expect(find.text('-84 dBm'), findsOneWidget);
|
||||||
expect(find.textContaining('RSSI -84 dBm'), findsOneWidget);
|
|
||||||
expect(find.textContaining('Hash:'), findsOneWidget);
|
expect(find.textContaining('Hash:'), findsOneWidget);
|
||||||
expect(
|
expect(
|
||||||
find.textContaining('Path: 3 hops [c010,6301,68d9]'),
|
find.textContaining('Path: 3 hops [c010,6301,68d9]'),
|
||||||
@@ -143,8 +150,8 @@ void main() {
|
|||||||
);
|
);
|
||||||
|
|
||||||
await tester.pumpWidget(
|
await tester.pumpWidget(
|
||||||
MaterialApp(
|
_testApp(
|
||||||
home: LiveTrafficScreen(
|
LiveTrafficScreen(
|
||||||
logReader: () => logs,
|
logReader: () => logs,
|
||||||
refreshListenable: refresh,
|
refreshListenable: refresh,
|
||||||
now: () => now,
|
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.tap(find.byTooltip('Clear live view'));
|
||||||
await tester.pump();
|
await tester.pump();
|
||||||
@@ -182,4 +189,43 @@ void main() {
|
|||||||
expect(find.text('No packets for this filter'), findsNothing);
|
expect(find.text('No packets for this filter'), findsNothing);
|
||||||
expect(find.textContaining('Size: 3 bytes'), findsOneWidget);
|
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,
|
||||||
|
);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
55
test/services/bthome_met_history_test.dart
Normal file
55
test/services/bthome_met_history_test.dart
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:meshcore_sar_app/models/contact.dart';
|
||||||
|
import 'package:meshcore_sar_app/services/bthome_met_history.dart';
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
test('parses a valid BTHome MET history response', () {
|
||||||
|
final parsed = BTHomeMetHistoryParser.parse('1,0,4,11.2,11.8,12.1,12.3');
|
||||||
|
|
||||||
|
expect(parsed.measurement, BTHomeMetMeasurement.temperature);
|
||||||
|
expect(parsed.page, 0);
|
||||||
|
expect(parsed.values, <double>[11.2, 11.8, 12.1, 12.3]);
|
||||||
|
expect(parsed.latest, 12.3);
|
||||||
|
expect(parsed.minimum, 11.2);
|
||||||
|
expect(parsed.maximum, 12.3);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rejects malformed BTHome MET history counts', () {
|
||||||
|
expect(
|
||||||
|
() => BTHomeMetHistoryParser.parse('2,0,3,41,42'),
|
||||||
|
throwsA(isA<BTHomeMetHistoryFormatException>()),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('detects available BTHome MET measurements from telemetry', () {
|
||||||
|
final contact = Contact(
|
||||||
|
publicKey: Uint8List(32),
|
||||||
|
type: ContactType.sensor,
|
||||||
|
flags: 0,
|
||||||
|
outPathLen: 0,
|
||||||
|
outPath: Uint8List(64),
|
||||||
|
advName: 'WX',
|
||||||
|
lastAdvert: 0,
|
||||||
|
advLat: 0,
|
||||||
|
advLon: 0,
|
||||||
|
lastMod: 0,
|
||||||
|
telemetry: ContactTelemetry(
|
||||||
|
temperature: 20.1,
|
||||||
|
humidity: 52,
|
||||||
|
extraSensorData: const {'speed_2': 3.1, 'gust_2': 4.8, 'rain_2': 12.3},
|
||||||
|
timestamp: DateTime(2026, 3, 21, 12),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(bTHomeMetMeasurementsForContact(contact), <BTHomeMetMeasurement>[
|
||||||
|
BTHomeMetMeasurement.temperature,
|
||||||
|
BTHomeMetMeasurement.humidity,
|
||||||
|
BTHomeMetMeasurement.windSpeed,
|
||||||
|
BTHomeMetMeasurement.gust,
|
||||||
|
BTHomeMetMeasurement.rain,
|
||||||
|
]);
|
||||||
|
expect(supportsBTHomeMetHistory(contact), isTrue);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -146,23 +146,55 @@ void main() {
|
|||||||
test('supports clearing the live view without mutating source logs', () {
|
test('supports clearing the live view without mutating source logs', () {
|
||||||
final now = DateTime(2026, 3, 12, 12, 0, 0);
|
final now = DateTime(2026, 3, 12, 12, 0, 0);
|
||||||
final clearAt = now.subtract(const Duration(seconds: 8));
|
final clearAt = now.subtract(const Duration(seconds: 8));
|
||||||
final snapshot = LiveTrafficSummary.fromLogs([
|
final snapshot = LiveTrafficSummary.fromLogs(
|
||||||
_log(
|
[
|
||||||
timestamp: now.subtract(const Duration(seconds: 10)),
|
_log(
|
||||||
direction: PacketDirection.rx,
|
timestamp: now.subtract(const Duration(seconds: 10)),
|
||||||
rawData: [0x88, 0x00, 0x00],
|
direction: PacketDirection.rx,
|
||||||
responseCode: 0x88,
|
rawData: [0x88, 0x00, 0x00],
|
||||||
),
|
responseCode: 0x88,
|
||||||
_log(
|
),
|
||||||
timestamp: now.subtract(const Duration(seconds: 4)),
|
_log(
|
||||||
direction: PacketDirection.rx,
|
timestamp: now.subtract(const Duration(seconds: 4)),
|
||||||
rawData: [0x88, 0x00, 0x00],
|
direction: PacketDirection.rx,
|
||||||
responseCode: 0x88,
|
rawData: [0x88, 0x00, 0x00],
|
||||||
),
|
responseCode: 0x88,
|
||||||
], now: now, clearedAt: clearAt);
|
),
|
||||||
|
],
|
||||||
|
now: now,
|
||||||
|
clearedAt: clearAt,
|
||||||
|
);
|
||||||
|
|
||||||
expect(snapshot.totalCount, 1);
|
expect(snapshot.totalCount, 1);
|
||||||
expect(snapshot.visibleEntries, hasLength(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(() {
|
setUp(() {
|
||||||
SharedPreferences.setMockInitialValues({});
|
SharedPreferences.setMockInitialValues({});
|
||||||
ProfileStorageScope.setScope(
|
ProfileStorageScope.setScope(
|
||||||
profilesEnabled: false,
|
profilesEnabled: true,
|
||||||
activeProfileId: ConfigProfile.defaultProfileId,
|
activeProfileId: ConfigProfile.defaultProfileId,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
group('ProfileManager', () {
|
group('ProfileManager', () {
|
||||||
test(
|
test('shows the built-in default profile on a fresh install', () async {
|
||||||
'hides the built-in default profile until profiles are enabled',
|
final manager = ProfileManager();
|
||||||
() async {
|
|
||||||
final manager = ProfileManager();
|
|
||||||
|
|
||||||
await manager.initialize();
|
await manager.initialize();
|
||||||
|
|
||||||
expect(manager.activeProfileId, ConfigProfile.defaultProfileId);
|
expect(manager.activeProfileId, ConfigProfile.defaultProfileId);
|
||||||
expect(manager.visibleProfiles, isEmpty);
|
expect(manager.visibleProfiles, hasLength(1));
|
||||||
expect(
|
expect(
|
||||||
manager.getProfile(ConfigProfile.defaultProfileId)?.isDefault,
|
manager.getProfile(ConfigProfile.defaultProfileId)?.isDefault,
|
||||||
isTrue,
|
isTrue,
|
||||||
);
|
);
|
||||||
expect(ProfileStorageScope.profilesEnabled, isFalse);
|
expect(ProfileStorageScope.profilesEnabled, isTrue);
|
||||||
expect(ProfileStorageScope.effectiveNamespace, isNull);
|
expect(ProfileStorageScope.effectiveNamespace, isNull);
|
||||||
|
expect(manager.visibleProfiles.single.name, 'Default');
|
||||||
await manager.setProfilesEnabled(true);
|
expect(ProfileStorageScope.effectiveNamespace, isNull);
|
||||||
|
});
|
||||||
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);
|
|
||||||
},
|
|
||||||
);
|
|
||||||
|
|
||||||
test(
|
test(
|
||||||
'persists custom profiles and restores scoped active profile state',
|
'persists custom profiles and restores scoped active profile state',
|
||||||
@@ -82,5 +70,44 @@ void main() {
|
|||||||
expect(reloaded.activeProfileId, profile.id);
|
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);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,6 +13,8 @@ import 'package:meshcore_sar_app/providers/drawing_provider.dart';
|
|||||||
import 'package:meshcore_sar_app/providers/map_provider.dart';
|
import 'package:meshcore_sar_app/providers/map_provider.dart';
|
||||||
import 'package:meshcore_sar_app/providers/messages_provider.dart';
|
import 'package:meshcore_sar_app/providers/messages_provider.dart';
|
||||||
import 'package:meshcore_sar_app/providers/sensors_provider.dart';
|
import 'package:meshcore_sar_app/providers/sensors_provider.dart';
|
||||||
|
import 'package:meshcore_sar_app/providers/voice_provider.dart';
|
||||||
|
import 'package:meshcore_sar_app/providers/image_provider.dart' as ip;
|
||||||
import 'package:meshcore_sar_app/services/app_config_snapshot_service.dart';
|
import 'package:meshcore_sar_app/services/app_config_snapshot_service.dart';
|
||||||
import 'package:meshcore_sar_app/services/contact_storage_service.dart';
|
import 'package:meshcore_sar_app/services/contact_storage_service.dart';
|
||||||
import 'package:meshcore_sar_app/services/device_config_applicator.dart';
|
import 'package:meshcore_sar_app/services/device_config_applicator.dart';
|
||||||
@@ -184,12 +186,87 @@ void main() {
|
|||||||
expect(manager.activeProfileId, target.id);
|
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 voiceProvider = _FakeVoiceProvider();
|
||||||
|
final imageProvider = _FakeImageProvider();
|
||||||
|
final coordinator = _buildCoordinator(
|
||||||
|
profileManager: manager,
|
||||||
|
connectionProvider: connectionProvider,
|
||||||
|
voiceProvider: voiceProvider,
|
||||||
|
imageProvider: imageProvider,
|
||||||
|
);
|
||||||
|
|
||||||
|
await coordinator.syncActiveProfileForCurrentDevice();
|
||||||
|
|
||||||
|
expect(manager.activeProfileId, alpha.id);
|
||||||
|
expect(connectionProvider.disconnectCallCount, 0);
|
||||||
|
expect(voiceProvider.reloadCallCount, 1);
|
||||||
|
expect(imageProvider.reloadCallCount, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test(
|
||||||
|
'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,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
ProfileWorkspaceCoordinator _buildCoordinator({
|
ProfileWorkspaceCoordinator _buildCoordinator({
|
||||||
required ProfileManager profileManager,
|
required ProfileManager profileManager,
|
||||||
_FakeConnectionProvider? connectionProvider,
|
_FakeConnectionProvider? connectionProvider,
|
||||||
|
_FakeVoiceProvider? voiceProvider,
|
||||||
|
_FakeImageProvider? imageProvider,
|
||||||
}) {
|
}) {
|
||||||
return ProfileWorkspaceCoordinator(
|
return ProfileWorkspaceCoordinator(
|
||||||
profileManager: profileManager,
|
profileManager: profileManager,
|
||||||
@@ -200,6 +277,8 @@ ProfileWorkspaceCoordinator _buildCoordinator({
|
|||||||
mapProvider: _FakeMapProvider(),
|
mapProvider: _FakeMapProvider(),
|
||||||
drawingProvider: _FakeDrawingProvider(),
|
drawingProvider: _FakeDrawingProvider(),
|
||||||
channelsProvider: _FakeChannelsProvider(),
|
channelsProvider: _FakeChannelsProvider(),
|
||||||
|
voiceProvider: voiceProvider ?? _FakeVoiceProvider(),
|
||||||
|
imageProvider: imageProvider ?? _FakeImageProvider(),
|
||||||
appProvider: _FakeAppProvider(),
|
appProvider: _FakeAppProvider(),
|
||||||
appConfigSnapshotService: _FakeAppConfigSnapshotService(),
|
appConfigSnapshotService: _FakeAppConfigSnapshotService(),
|
||||||
mapWorkspaceSnapshotService: _FakeMapWorkspaceSnapshotService(),
|
mapWorkspaceSnapshotService: _FakeMapWorkspaceSnapshotService(),
|
||||||
@@ -265,10 +344,16 @@ class _FakeDeviceConfigApplicator extends DeviceConfigApplicator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
class _FakeConnectionProvider implements ConnectionProvider {
|
class _FakeConnectionProvider implements ConnectionProvider {
|
||||||
|
_FakeConnectionProvider({DeviceInfo? deviceInfo})
|
||||||
|
: deviceInfo = deviceInfo ?? DeviceInfo();
|
||||||
|
|
||||||
int disconnectCallCount = 0;
|
int disconnectCallCount = 0;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
DeviceInfo get deviceInfo => DeviceInfo();
|
final DeviceInfo deviceInfo;
|
||||||
|
|
||||||
|
@override
|
||||||
|
ConnectionMode get connectionMode => ConnectionMode.ble;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Future<void> disconnect() async {
|
Future<void> disconnect() async {
|
||||||
@@ -333,6 +418,30 @@ class _FakeChannelsProvider implements ChannelsProvider {
|
|||||||
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
|
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
class _FakeVoiceProvider implements VoiceProvider {
|
||||||
|
int reloadCallCount = 0;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> reloadProfileScopedState() async {
|
||||||
|
reloadCallCount += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
|
||||||
|
}
|
||||||
|
|
||||||
|
class _FakeImageProvider implements ip.ImageProvider {
|
||||||
|
int reloadCallCount = 0;
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> reloadProfileScopedState() async {
|
||||||
|
reloadCallCount += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
|
||||||
|
}
|
||||||
|
|
||||||
class _FakeAppProvider implements AppProvider {
|
class _FakeAppProvider implements AppProvider {
|
||||||
@override
|
@override
|
||||||
Future<void> reloadProfileScopedSettings() async {}
|
Future<void> reloadProfileScopedSettings() 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('CO2'), findsOneWidget);
|
||||||
expect(find.text('415 ppm'), findsOneWidget);
|
expect(find.text('415 ppm'), findsOneWidget);
|
||||||
expect(find.text('Illuminance'), 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('Current'), findsOneWidget);
|
||||||
expect(find.text('15 mA'), findsOneWidget);
|
expect(find.text('15 mA'), findsOneWidget);
|
||||||
expect(find.text('Power'), findsOneWidget);
|
expect(find.text('Power'), findsOneWidget);
|
||||||
expect(find.text('Distance'), findsOneWidget);
|
expect(find.text('Distance'), findsOneWidget);
|
||||||
expect(
|
expect(find.byKey(const ValueKey('sensor_metric_battery')), findsOneWidget);
|
||||||
find.byKey(const ValueKey('sensor_metric_channel_battery')),
|
|
||||||
findsOneWidget,
|
|
||||||
);
|
|
||||||
expect(find.text('ch1'), findsWidgets);
|
expect(find.text('ch1'), findsWidgets);
|
||||||
expect(
|
expect(
|
||||||
find.byKey(const ValueKey('sensor_metric_channel_extra:illuminance_2')),
|
find.byKey(const ValueKey('sensor_metric_extra:illuminance_2')),
|
||||||
findsOneWidget,
|
findsOneWidget,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
437
test/widgets/message_bubble_test.dart
Normal file
437
test/widgets/message_bubble_test.dart
Normal file
@@ -0,0 +1,437 @@
|
|||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:flutter/gestures.dart';
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:meshcore_sar_app/l10n/app_localizations.dart';
|
||||||
|
import 'package:meshcore_sar_app/models/message.dart';
|
||||||
|
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();
|
||||||
|
|
||||||
|
final launchedUrls = <String>[];
|
||||||
|
|
||||||
|
setUp(() {
|
||||||
|
SharedPreferences.setMockInitialValues({});
|
||||||
|
launchedUrls.clear();
|
||||||
|
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||||
|
.setMockMethodCallHandler(
|
||||||
|
const MethodChannel('plugins.flutter.io/url_launcher'),
|
||||||
|
(call) async {
|
||||||
|
switch (call.method) {
|
||||||
|
case 'canLaunch':
|
||||||
|
return true;
|
||||||
|
case 'launch':
|
||||||
|
final arguments = Map<dynamic, dynamic>.from(
|
||||||
|
call.arguments as Map<dynamic, dynamic>,
|
||||||
|
);
|
||||||
|
launchedUrls.add(arguments['url'] as String);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
},
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
tearDown(() {
|
||||||
|
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||||
|
.setMockMethodCallHandler(
|
||||||
|
const MethodChannel('plugins.flutter.io/url_launcher'),
|
||||||
|
null,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('received bubbles show signal chips on double tap', (
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('message bubble detects and opens links', (tester) async {
|
||||||
|
final harness = await _TestHarness.create();
|
||||||
|
try {
|
||||||
|
final message = Message(
|
||||||
|
id: 'message-link',
|
||||||
|
messageType: MessageType.contact,
|
||||||
|
senderPublicKeyPrefix: _prefix(31),
|
||||||
|
pathLen: 0,
|
||||||
|
textType: MessageTextType.plain,
|
||||||
|
senderTimestamp: 1700000000,
|
||||||
|
text: 'Check https://example.com/docs, then ping @[Rescue Team].',
|
||||||
|
receivedAt: DateTime.fromMillisecondsSinceEpoch(1700000000500),
|
||||||
|
deliveryStatus: MessageDeliveryStatus.received,
|
||||||
|
);
|
||||||
|
|
||||||
|
await tester.pumpWidget(_buildApp(harness, message));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
final richText = tester
|
||||||
|
.widgetList<RichText>(find.byType(RichText))
|
||||||
|
.firstWhere(
|
||||||
|
(widget) =>
|
||||||
|
widget.text.toPlainText().contains('https://example.com/docs'),
|
||||||
|
);
|
||||||
|
final linkSpan = _findTextSpan(
|
||||||
|
richText.text,
|
||||||
|
(span) => span.text == 'https://example.com/docs',
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(richText.text.toPlainText(), contains('https://example.com/docs'));
|
||||||
|
expect(find.text('@Rescue Team'), findsOneWidget);
|
||||||
|
|
||||||
|
expect(linkSpan, isNotNull);
|
||||||
|
|
||||||
|
final recognizer = linkSpan!.recognizer;
|
||||||
|
expect(recognizer, isA<TapGestureRecognizer>());
|
||||||
|
(recognizer! as TapGestureRecognizer).onTap!();
|
||||||
|
await tester.pump();
|
||||||
|
|
||||||
|
expect(launchedUrls, ['https://example.com/docs']);
|
||||||
|
} finally {
|
||||||
|
await _disposeHarness(tester, harness);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('message bubble opens meshcore links in add contact screen', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final harness = await _TestHarness.create();
|
||||||
|
try {
|
||||||
|
const payloadSegment = '00112233445566778899aabbccddeeff';
|
||||||
|
final advert =
|
||||||
|
'meshcore://'
|
||||||
|
'$payloadSegment'
|
||||||
|
'$payloadSegment'
|
||||||
|
'$payloadSegment'
|
||||||
|
'$payloadSegment'
|
||||||
|
'$payloadSegment'
|
||||||
|
'$payloadSegment'
|
||||||
|
'0011';
|
||||||
|
final message = Message(
|
||||||
|
id: 'message-meshcore-link',
|
||||||
|
messageType: MessageType.contact,
|
||||||
|
senderPublicKeyPrefix: _prefix(41),
|
||||||
|
pathLen: 0,
|
||||||
|
textType: MessageTextType.plain,
|
||||||
|
senderTimestamp: 1700000000,
|
||||||
|
text: 'Import $advert',
|
||||||
|
receivedAt: DateTime.fromMillisecondsSinceEpoch(1700000000500),
|
||||||
|
deliveryStatus: MessageDeliveryStatus.received,
|
||||||
|
);
|
||||||
|
|
||||||
|
await tester.pumpWidget(_buildApp(harness, message));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
final richText = tester
|
||||||
|
.widgetList<RichText>(find.byType(RichText))
|
||||||
|
.firstWhere((widget) => widget.text.toPlainText().contains(advert));
|
||||||
|
final linkSpan = _findTextSpan(
|
||||||
|
richText.text,
|
||||||
|
(span) => span.text == advert,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(linkSpan, isNotNull);
|
||||||
|
|
||||||
|
final recognizer = linkSpan!.recognizer;
|
||||||
|
expect(recognizer, isA<TapGestureRecognizer>());
|
||||||
|
(recognizer! as TapGestureRecognizer).onTap!();
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(find.text('Import a shared contact advert'), findsOneWidget);
|
||||||
|
expect(find.text(advert), findsOneWidget);
|
||||||
|
} finally {
|
||||||
|
await _disposeHarness(tester, harness);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('message bubble linkifies raw meshcore adverts', (tester) async {
|
||||||
|
final harness = await _TestHarness.create();
|
||||||
|
try {
|
||||||
|
const advert =
|
||||||
|
'00112233445566778899aabbccddeeff'
|
||||||
|
'00112233445566778899aabbccddeeff'
|
||||||
|
'00112233445566778899aabbccddeeff'
|
||||||
|
'00112233445566778899aabbccddeeff'
|
||||||
|
'00112233445566778899aabbccddeeff'
|
||||||
|
'00112233445566778899aabbccddeeff'
|
||||||
|
'0011';
|
||||||
|
final message = Message(
|
||||||
|
id: 'message-meshcore-raw',
|
||||||
|
messageType: MessageType.contact,
|
||||||
|
senderPublicKeyPrefix: _prefix(51),
|
||||||
|
pathLen: 0,
|
||||||
|
textType: MessageTextType.plain,
|
||||||
|
senderTimestamp: 1700000000,
|
||||||
|
text: 'Import raw advert: $advert',
|
||||||
|
receivedAt: DateTime.fromMillisecondsSinceEpoch(1700000000500),
|
||||||
|
deliveryStatus: MessageDeliveryStatus.received,
|
||||||
|
);
|
||||||
|
|
||||||
|
await tester.pumpWidget(_buildApp(harness, message));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
final richText = tester
|
||||||
|
.widgetList<RichText>(find.byType(RichText))
|
||||||
|
.firstWhere((widget) => widget.text.toPlainText().contains(advert));
|
||||||
|
final linkSpan = _findTextSpan(
|
||||||
|
richText.text,
|
||||||
|
(span) => span.text == advert,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(linkSpan, isNotNull);
|
||||||
|
|
||||||
|
final recognizer = linkSpan!.recognizer;
|
||||||
|
expect(recognizer, isA<TapGestureRecognizer>());
|
||||||
|
(recognizer! as TapGestureRecognizer).onTap!();
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(find.text('Import a shared contact advert'), findsOneWidget);
|
||||||
|
expect(find.text(advert), findsOneWidget);
|
||||||
|
} finally {
|
||||||
|
await _disposeHarness(tester, harness);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Widget _buildApp(_TestHarness harness, Message message) {
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
|
||||||
|
TextSpan? _findTextSpan(
|
||||||
|
InlineSpan span,
|
||||||
|
bool Function(TextSpan span) predicate,
|
||||||
|
) {
|
||||||
|
if (span is! TextSpan) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (predicate(span)) {
|
||||||
|
return span;
|
||||||
|
}
|
||||||
|
for (final child in span.children ?? const <InlineSpan>[]) {
|
||||||
|
final match = _findTextSpan(child, predicate);
|
||||||
|
if (match != null) {
|
||||||
|
return match;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
@@ -11,6 +11,8 @@ void main() {
|
|||||||
required String name,
|
required String name,
|
||||||
required ContactType type,
|
required ContactType type,
|
||||||
int secondByte = 0,
|
int secondByte = 0,
|
||||||
|
int flags = 0,
|
||||||
|
int lastAdvert = 0,
|
||||||
}) {
|
}) {
|
||||||
final publicKey = Uint8List(32);
|
final publicKey = Uint8List(32);
|
||||||
publicKey[1] = secondByte;
|
publicKey[1] = secondByte;
|
||||||
@@ -18,11 +20,11 @@ void main() {
|
|||||||
return Contact(
|
return Contact(
|
||||||
publicKey: publicKey,
|
publicKey: publicKey,
|
||||||
type: type,
|
type: type,
|
||||||
flags: 0,
|
flags: flags,
|
||||||
outPathLen: 0,
|
outPathLen: 0,
|
||||||
outPath: Uint8List(0),
|
outPath: Uint8List(0),
|
||||||
advName: name,
|
advName: name,
|
||||||
lastAdvert: 0,
|
lastAdvert: lastAdvert,
|
||||||
advLat: 0,
|
advLat: 0,
|
||||||
advLon: 0,
|
advLon: 0,
|
||||||
lastMod: 0,
|
lastMod: 0,
|
||||||
@@ -98,4 +100,54 @@ void main() {
|
|||||||
expect(find.text('Show all'), findsNothing);
|
expect(find.text('Show all'), findsNothing);
|
||||||
expect(find.text('John Smith'), findsOneWidget);
|
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/material.dart';
|
||||||
import 'package:flutter_test/flutter_test.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/screens/sensors_tab.dart';
|
||||||
import 'package:meshcore_sar_app/widgets/sensors/sensor_telemetry_card.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 {
|
testWidgets('renders selector previews and channel badges', (tester) async {
|
||||||
await tester.pumpWidget(
|
await tester.pumpWidget(
|
||||||
MaterialApp(
|
MaterialApp(
|
||||||
|
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||||
|
supportedLocales: AppLocalizations.supportedLocales,
|
||||||
home: Scaffold(
|
home: Scaffold(
|
||||||
body: SensorMetricSelectorItem(
|
body: SensorMetricSelectorItem(
|
||||||
option: const SensorMetricOption(
|
option: const SensorMetricOption(
|
||||||
@@ -14,12 +17,12 @@ void main() {
|
|||||||
label: 'Illuminance (ch 2)',
|
label: 'Illuminance (ch 2)',
|
||||||
defaultLabel: 'Illuminance',
|
defaultLabel: 'Illuminance',
|
||||||
channel: 2,
|
channel: 2,
|
||||||
valuePreview: '500 lx',
|
valuePreview: '~4.2 W/m2',
|
||||||
previewCardData: SensorMetricCardData(
|
previewCardData: SensorMetricCardData(
|
||||||
fieldKey: 'extra:illuminance_2',
|
fieldKey: 'extra:illuminance_2',
|
||||||
icon: Icons.light_mode_outlined,
|
icon: Icons.light_mode_outlined,
|
||||||
label: 'Illuminance',
|
label: 'Illuminance',
|
||||||
value: '500 lx',
|
value: '~4.2 W/m2',
|
||||||
accent: Color(0xFFC17B1D),
|
accent: Color(0xFFC17B1D),
|
||||||
channel: 2,
|
channel: 2,
|
||||||
),
|
),
|
||||||
@@ -39,7 +42,8 @@ void main() {
|
|||||||
);
|
);
|
||||||
|
|
||||||
expect(find.text('Show on sensor card'), findsOneWidget);
|
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(
|
expect(
|
||||||
find.byKey(const ValueKey('sensor_selector_channel_extra:illuminance_2')),
|
find.byKey(const ValueKey('sensor_selector_channel_extra:illuminance_2')),
|
||||||
findsOneWidget,
|
findsOneWidget,
|
||||||
@@ -50,6 +54,8 @@ void main() {
|
|||||||
testWidgets('omits duplicate channel chip for channel 1', (tester) async {
|
testWidgets('omits duplicate channel chip for channel 1', (tester) async {
|
||||||
await tester.pumpWidget(
|
await tester.pumpWidget(
|
||||||
MaterialApp(
|
MaterialApp(
|
||||||
|
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||||
|
supportedLocales: AppLocalizations.supportedLocales,
|
||||||
home: Scaffold(
|
home: Scaffold(
|
||||||
body: SensorMetricSelectorItem(
|
body: SensorMetricSelectorItem(
|
||||||
option: const SensorMetricOption(
|
option: const SensorMetricOption(
|
||||||
|
|||||||
@@ -63,12 +63,14 @@ void main() {
|
|||||||
expect(find.text('Light'), findsOneWidget);
|
expect(find.text('Light'), findsOneWidget);
|
||||||
expect(find.text('Temperature'), findsNothing);
|
expect(find.text('Temperature'), findsNothing);
|
||||||
expect(find.text('Illuminance'), findsNothing);
|
expect(find.text('Illuminance'), findsNothing);
|
||||||
|
expect(find.text('~4.2 W/m2'), findsOneWidget);
|
||||||
|
expect(find.textContaining('lx'), findsNothing);
|
||||||
expect(
|
expect(
|
||||||
find.byKey(const ValueKey('sensor_metric_channel_temperature')),
|
find.byKey(const ValueKey('sensor_metric_temperature')),
|
||||||
findsOneWidget,
|
findsOneWidget,
|
||||||
);
|
);
|
||||||
expect(
|
expect(
|
||||||
find.byKey(const ValueKey('sensor_metric_channel_extra:illuminance_2')),
|
find.byKey(const ValueKey('sensor_metric_extra:illuminance_2')),
|
||||||
findsOneWidget,
|
findsOneWidget,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
@@ -187,4 +189,36 @@ void main() {
|
|||||||
expect(find.text('2°C'), findsOneWidget);
|
expect(find.text('2°C'), findsOneWidget);
|
||||||
expect(find.text('12.3 mm'), findsOneWidget);
|
expect(find.text('12.3 mm'), findsOneWidget);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
testWidgets('long pressing a telemetry bubble triggers refresh', (
|
||||||
|
tester,
|
||||||
|
) async {
|
||||||
|
final contact = buildContact();
|
||||||
|
var refreshCount = 0;
|
||||||
|
|
||||||
|
await tester.pumpWidget(
|
||||||
|
MaterialApp(
|
||||||
|
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||||
|
supportedLocales: AppLocalizations.supportedLocales,
|
||||||
|
home: Scaffold(
|
||||||
|
body: SensorTelemetryCard(
|
||||||
|
contact: contact,
|
||||||
|
state: SensorRefreshState.idle,
|
||||||
|
visibleFields: const {'temperature'},
|
||||||
|
fieldSpans: sensorFullWidthFieldSpans(const {'temperature'}),
|
||||||
|
onRefresh: () async {
|
||||||
|
refreshCount += 1;
|
||||||
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
await tester.longPress(
|
||||||
|
find.byKey(const ValueKey('sensor_metric_temperature')),
|
||||||
|
);
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(refreshCount, 1);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,6 +10,7 @@
|
|||||||
#include <file_selector_windows/file_selector_windows.h>
|
#include <file_selector_windows/file_selector_windows.h>
|
||||||
#include <flutter_avif_windows/flutter_avif_windows_plugin.h>
|
#include <flutter_avif_windows/flutter_avif_windows_plugin.h>
|
||||||
#include <flutter_blue_plus_winrt/flutter_blue_plus_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 <geolocator_windows/geolocator_windows.h>
|
||||||
#include <nsd_windows/nsd_windows_plugin_c_api.h>
|
#include <nsd_windows/nsd_windows_plugin_c_api.h>
|
||||||
#include <permission_handler_windows/permission_handler_windows_plugin.h>
|
#include <permission_handler_windows/permission_handler_windows_plugin.h>
|
||||||
@@ -26,6 +27,8 @@ void RegisterPlugins(flutter::PluginRegistry* registry) {
|
|||||||
registry->GetRegistrarForPlugin("FlutterAvifWindowsPlugin"));
|
registry->GetRegistrarForPlugin("FlutterAvifWindowsPlugin"));
|
||||||
FlutterBluePlusPluginRegisterWithRegistrar(
|
FlutterBluePlusPluginRegisterWithRegistrar(
|
||||||
registry->GetRegistrarForPlugin("FlutterBluePlusPlugin"));
|
registry->GetRegistrarForPlugin("FlutterBluePlusPlugin"));
|
||||||
|
FlutterLibserialportPluginRegisterWithRegistrar(
|
||||||
|
registry->GetRegistrarForPlugin("FlutterLibserialportPlugin"));
|
||||||
GeolocatorWindowsRegisterWithRegistrar(
|
GeolocatorWindowsRegisterWithRegistrar(
|
||||||
registry->GetRegistrarForPlugin("GeolocatorWindows"));
|
registry->GetRegistrarForPlugin("GeolocatorWindows"));
|
||||||
NsdWindowsPluginCApiRegisterWithRegistrar(
|
NsdWindowsPluginCApiRegisterWithRegistrar(
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ list(APPEND FLUTTER_PLUGIN_LIST
|
|||||||
file_selector_windows
|
file_selector_windows
|
||||||
flutter_avif_windows
|
flutter_avif_windows
|
||||||
flutter_blue_plus_winrt
|
flutter_blue_plus_winrt
|
||||||
|
flutter_libserialport
|
||||||
geolocator_windows
|
geolocator_windows
|
||||||
nsd_windows
|
nsd_windows
|
||||||
permission_handler_windows
|
permission_handler_windows
|
||||||
|
|||||||
Reference in New Issue
Block a user