mirror of
https://github.com/dz0ny/meshcore-sar.git
synced 2026-08-11 16:30:28 +00:00
Refactor message handling and enhance BLE connection management
- Cleaned up message formatting in MessagesTab for better readability. - Improved SAR message parsing to include optional inline messages. - Updated BLE connection manager to monitor RSSI values and added callback for RSSI updates. - Adjusted drawing message parser to remove sender name from JSON and extract it from packet metadata. - Enhanced drawing toolbar to reflect changes in message creation without sender name. - Ensured consistent error handling and logging across BLE operations.
This commit is contained in:
@@ -7,17 +7,29 @@ enum DrawingShapeType {
|
||||
rectangle,
|
||||
}
|
||||
|
||||
/// Drawing color enum for compact network transmission
|
||||
enum DrawingColor {
|
||||
red, // 0
|
||||
blue, // 1
|
||||
green, // 2
|
||||
yellow, // 3
|
||||
orange, // 4
|
||||
purple, // 5
|
||||
pink, // 6
|
||||
cyan, // 7
|
||||
}
|
||||
|
||||
/// Drawing colors available for user selection
|
||||
class DrawingColors {
|
||||
static const List<Color> palette = [
|
||||
Colors.red,
|
||||
Colors.blue,
|
||||
Colors.green,
|
||||
Colors.yellow,
|
||||
Colors.orange,
|
||||
Colors.purple,
|
||||
Colors.pink,
|
||||
Colors.cyan,
|
||||
Colors.red, // index 0
|
||||
Colors.blue, // index 1
|
||||
Colors.green, // index 2
|
||||
Colors.yellow, // index 3
|
||||
Colors.orange, // index 4
|
||||
Colors.purple, // index 5
|
||||
Colors.pink, // index 6
|
||||
Colors.cyan, // index 7
|
||||
];
|
||||
|
||||
static String colorToName(Color color) {
|
||||
@@ -31,6 +43,24 @@ class DrawingColors {
|
||||
if (color == Colors.cyan) return 'Cyan';
|
||||
return 'Unknown';
|
||||
}
|
||||
|
||||
/// Convert Color to enum index for network transmission
|
||||
static int colorToIndex(Color color) {
|
||||
for (int i = 0; i < palette.length; i++) {
|
||||
if (palette[i].value == color.value) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return 0; // Default to red if not found
|
||||
}
|
||||
|
||||
/// Convert enum index to Color for network reception
|
||||
static Color indexToColor(int index) {
|
||||
if (index >= 0 && index < palette.length) {
|
||||
return palette[index];
|
||||
}
|
||||
return palette[0]; // Default to red if invalid index
|
||||
}
|
||||
}
|
||||
|
||||
/// Base class for map drawings
|
||||
@@ -56,23 +86,25 @@ abstract class MapDrawing {
|
||||
|
||||
/// Convert to JSON for network transmission (compact format)
|
||||
/// Uses short field names and excludes createdAt to minimize message size
|
||||
Map<String, dynamic> toNetworkJson(String senderName);
|
||||
/// Sender will be fetched from packet metadata
|
||||
Map<String, dynamic> toNetworkJson();
|
||||
|
||||
/// Parse network JSON (compact format)
|
||||
static MapDrawing? fromNetworkJson(Map<String, dynamic> json) {
|
||||
final typeStr = json['t'] as String?;
|
||||
if (typeStr == null) return null;
|
||||
/// senderName will be populated from packet metadata
|
||||
static MapDrawing? fromNetworkJson(Map<String, dynamic> json, {String? senderName}) {
|
||||
final typeNum = json['t'] as int?;
|
||||
if (typeNum == null || typeNum < 0 || typeNum >= DrawingShapeType.values.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
final type = DrawingShapeType.values.firstWhere(
|
||||
(e) => e.name == typeStr,
|
||||
);
|
||||
final type = DrawingShapeType.values[typeNum];
|
||||
|
||||
switch (type) {
|
||||
case DrawingShapeType.line:
|
||||
return LineDrawing.fromNetworkJson(json);
|
||||
return LineDrawing.fromNetworkJson(json, senderName: senderName);
|
||||
case DrawingShapeType.rectangle:
|
||||
return RectangleDrawing.fromNetworkJson(json);
|
||||
return RectangleDrawing.fromNetworkJson(json, senderName: senderName);
|
||||
}
|
||||
} catch (e) {
|
||||
return null;
|
||||
@@ -126,13 +158,13 @@ class LineDrawing extends MapDrawing {
|
||||
}
|
||||
|
||||
@override
|
||||
Map<String, dynamic> toNetworkJson(String senderName) {
|
||||
// Compact format: t=type, c=color, s=sender, p=points
|
||||
Map<String, dynamic> toNetworkJson() {
|
||||
// Ultra-compact format: t=type (0=line, 1=rect), c=color index (0-7), p=points
|
||||
// Points are encoded as flat array [lat1,lon1,lat2,lon2,...]
|
||||
// Sender is fetched from packet metadata, not included in JSON
|
||||
return {
|
||||
't': type.name,
|
||||
'c': color.value,
|
||||
's': senderName,
|
||||
't': type.index,
|
||||
'c': DrawingColors.colorToIndex(color),
|
||||
'p': points.expand((p) => [p.latitude, p.longitude]).toList(),
|
||||
};
|
||||
}
|
||||
@@ -152,18 +184,17 @@ class LineDrawing extends MapDrawing {
|
||||
);
|
||||
}
|
||||
|
||||
static LineDrawing fromNetworkJson(Map<String, dynamic> json) {
|
||||
// Parse compact format
|
||||
static LineDrawing fromNetworkJson(Map<String, dynamic> json, {String? senderName}) {
|
||||
// Parse ultra-compact format
|
||||
final pointsFlat = (json['p'] as List<dynamic>).cast<double>();
|
||||
final points = <LatLng>[];
|
||||
for (int i = 0; i < pointsFlat.length; i += 2) {
|
||||
points.add(LatLng(pointsFlat[i], pointsFlat[i + 1]));
|
||||
}
|
||||
final senderName = json['s'] as String?;
|
||||
|
||||
return LineDrawing(
|
||||
id: DateTime.now().millisecondsSinceEpoch.toString(), // Generate new ID
|
||||
color: Color(json['c'] as int),
|
||||
color: DrawingColors.indexToColor(json['c'] as int),
|
||||
createdAt: DateTime.now(),
|
||||
points: points,
|
||||
senderName: senderName,
|
||||
@@ -219,12 +250,12 @@ class RectangleDrawing extends MapDrawing {
|
||||
}
|
||||
|
||||
@override
|
||||
Map<String, dynamic> toNetworkJson(String senderName) {
|
||||
// Compact format: t=type, c=color, s=sender, b=bounds [lat1,lon1,lat2,lon2]
|
||||
Map<String, dynamic> toNetworkJson() {
|
||||
// Ultra-compact format: t=type (0=line, 1=rect), c=color index (0-7), b=bounds [lat1,lon1,lat2,lon2]
|
||||
// Sender is fetched from packet metadata, not included in JSON
|
||||
return {
|
||||
't': type.name,
|
||||
'c': color.value,
|
||||
's': senderName,
|
||||
't': type.index,
|
||||
'c': DrawingColors.colorToIndex(color),
|
||||
'b': [topLeft.latitude, topLeft.longitude, bottomRight.latitude, bottomRight.longitude],
|
||||
};
|
||||
}
|
||||
@@ -245,14 +276,13 @@ class RectangleDrawing extends MapDrawing {
|
||||
);
|
||||
}
|
||||
|
||||
static RectangleDrawing fromNetworkJson(Map<String, dynamic> json) {
|
||||
// Parse compact format
|
||||
static RectangleDrawing fromNetworkJson(Map<String, dynamic> json, {String? senderName}) {
|
||||
// Parse ultra-compact format
|
||||
final bounds = (json['b'] as List<dynamic>).cast<double>();
|
||||
final senderName = json['s'] as String?;
|
||||
|
||||
return RectangleDrawing(
|
||||
id: DateTime.now().millisecondsSinceEpoch.toString(), // Generate new ID
|
||||
color: Color(json['c'] as int),
|
||||
color: DrawingColors.indexToColor(json['c'] as int),
|
||||
createdAt: DateTime.now(),
|
||||
topLeft: LatLng(bounds[0], bounds[1]),
|
||||
bottomRight: LatLng(bounds[2], bounds[3]),
|
||||
|
||||
@@ -50,6 +50,7 @@ class Message {
|
||||
final bool isSarMarker;
|
||||
final SarMarkerType? sarMarkerType;
|
||||
final LatLng? sarGpsCoordinates;
|
||||
final String? sarNotes; // Optional message/notes for SAR marker
|
||||
|
||||
// Display metadata
|
||||
final DateTime receivedAt;
|
||||
@@ -78,6 +79,7 @@ class Message {
|
||||
this.isSarMarker = false,
|
||||
this.sarMarkerType,
|
||||
this.sarGpsCoordinates,
|
||||
this.sarNotes,
|
||||
required this.receivedAt,
|
||||
this.senderName,
|
||||
this.deliveryStatus = MessageDeliveryStatus.received,
|
||||
@@ -162,7 +164,7 @@ class Message {
|
||||
timestamp: sentAt,
|
||||
senderPublicKey: senderPublicKeyPrefix,
|
||||
senderName: senderName,
|
||||
notes: text,
|
||||
notes: sarNotes, // Use dedicated notes field instead of full text
|
||||
);
|
||||
}
|
||||
|
||||
@@ -218,6 +220,7 @@ class Message {
|
||||
bool? isSarMarker,
|
||||
SarMarkerType? sarMarkerType,
|
||||
LatLng? sarGpsCoordinates,
|
||||
String? sarNotes,
|
||||
DateTime? receivedAt,
|
||||
String? senderName,
|
||||
MessageDeliveryStatus? deliveryStatus,
|
||||
@@ -240,6 +243,7 @@ class Message {
|
||||
isSarMarker: isSarMarker ?? this.isSarMarker,
|
||||
sarMarkerType: sarMarkerType ?? this.sarMarkerType,
|
||||
sarGpsCoordinates: sarGpsCoordinates ?? this.sarGpsCoordinates,
|
||||
sarNotes: sarNotes ?? this.sarNotes,
|
||||
receivedAt: receivedAt ?? this.receivedAt,
|
||||
senderName: senderName ?? this.senderName,
|
||||
deliveryStatus: deliveryStatus ?? this.deliveryStatus,
|
||||
|
||||
@@ -68,7 +68,12 @@ class AppProvider with ChangeNotifier {
|
||||
// Check if message is a drawing broadcast
|
||||
if (DrawingMessageParser.isDrawingMessage(message.text)) {
|
||||
debugPrint('🎨 [AppProvider] Drawing message received, parsing...');
|
||||
final drawing = DrawingMessageParser.parseDrawingMessage(message.text);
|
||||
// Extract sender name from message packet metadata
|
||||
final senderName = message.senderName ?? 'unknown';
|
||||
final drawing = DrawingMessageParser.parseDrawingMessage(
|
||||
message.text,
|
||||
senderName: senderName,
|
||||
);
|
||||
if (drawing != null) {
|
||||
debugPrint('🎨 [AppProvider] Drawing parsed successfully: ${drawing.type.name} from ${drawing.senderName ?? "unknown"}');
|
||||
drawingProvider.addReceivedDrawing(drawing);
|
||||
@@ -177,6 +182,9 @@ class AppProvider with ChangeNotifier {
|
||||
// Sync device time
|
||||
await connectionProvider.syncDeviceTime();
|
||||
|
||||
// Get battery and storage information
|
||||
await connectionProvider.getBatteryAndStorage();
|
||||
|
||||
// Load contacts
|
||||
await connectionProvider.getContacts();
|
||||
|
||||
|
||||
@@ -26,6 +26,14 @@ class PingResult {
|
||||
});
|
||||
}
|
||||
|
||||
/// Scanned device with RSSI information
|
||||
class ScannedDevice {
|
||||
final BluetoothDevice device;
|
||||
final int rssi;
|
||||
|
||||
ScannedDevice({required this.device, required this.rssi});
|
||||
}
|
||||
|
||||
/// Connection Provider - manages MeshCore BLE connection
|
||||
class ConnectionProvider with ChangeNotifier {
|
||||
final MeshCoreBleService _bleService = MeshCoreBleService();
|
||||
@@ -36,8 +44,8 @@ class ConnectionProvider with ChangeNotifier {
|
||||
DeviceInfo _deviceInfo = DeviceInfo();
|
||||
DeviceInfo get deviceInfo => _deviceInfo;
|
||||
|
||||
List<BluetoothDevice> _scannedDevices = [];
|
||||
List<BluetoothDevice> get scannedDevices => _scannedDevices;
|
||||
List<ScannedDevice> _scannedDevices = [];
|
||||
List<ScannedDevice> get scannedDevices => _scannedDevices;
|
||||
|
||||
bool _isScanning = false;
|
||||
bool get isScanning => _isScanning;
|
||||
@@ -352,6 +360,15 @@ class ConnectionProvider with ChangeNotifier {
|
||||
notifyListeners();
|
||||
});
|
||||
};
|
||||
|
||||
_bleService.onRssiUpdate = (rssi) {
|
||||
print('📡 [Provider] RSSI updated: $rssi dBm');
|
||||
_deviceInfo = _deviceInfo.copyWith(
|
||||
signalRssi: rssi,
|
||||
lastUpdate: DateTime.now(),
|
||||
);
|
||||
notifyListeners();
|
||||
};
|
||||
}
|
||||
|
||||
/// Start scanning for MeshCore devices
|
||||
@@ -364,15 +381,26 @@ class ConnectionProvider with ChangeNotifier {
|
||||
print('✅ [Provider] Scan state initialized, notifying listeners');
|
||||
|
||||
try {
|
||||
await for (final device
|
||||
await for (final scanResult
|
||||
in _bleService.scanForDevices(timeout: const Duration(seconds: 10))) {
|
||||
print('📱 [Provider] Device received from scan stream');
|
||||
if (!_scannedDevices.any((d) => d.remoteId == device.remoteId)) {
|
||||
_scannedDevices.add(device);
|
||||
print('✅ [Provider] Added device to list: ${device.platformName}, total: ${_scannedDevices.length}');
|
||||
print('📱 [Provider] Scan result received from scan stream');
|
||||
final device = scanResult.device;
|
||||
final rssi = scanResult.rssi;
|
||||
|
||||
if (!_scannedDevices.any((d) => d.device.remoteId == device.remoteId)) {
|
||||
_scannedDevices.add(ScannedDevice(device: device, rssi: rssi));
|
||||
print('✅ [Provider] Added device to list: ${device.platformName} (RSSI: $rssi dBm), total: ${_scannedDevices.length}');
|
||||
notifyListeners();
|
||||
} else {
|
||||
print(' ⏭️ [Provider] Device already in list, skipping');
|
||||
// Update RSSI if device already exists
|
||||
final index = _scannedDevices.indexWhere((d) => d.device.remoteId == device.remoteId);
|
||||
if (index != -1 && _scannedDevices[index].rssi != rssi) {
|
||||
_scannedDevices[index] = ScannedDevice(device: device, rssi: rssi);
|
||||
print(' 🔄 [Provider] Updated RSSI for ${device.platformName}: $rssi dBm');
|
||||
notifyListeners();
|
||||
} else {
|
||||
print(' ⏭️ [Provider] Device already in list with same RSSI, skipping');
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
|
||||
@@ -273,7 +273,8 @@ class DrawingProvider with ChangeNotifier {
|
||||
|
||||
/// Broadcast a drawing to contacts
|
||||
/// Returns the formatted message string ready to send
|
||||
String createDrawingBroadcastMessage(MapDrawing drawing, String senderName) {
|
||||
return DrawingMessageParser.createDrawingMessage(drawing, senderName);
|
||||
/// Sender will be determined from packet metadata on receiving end
|
||||
String createDrawingBroadcastMessage(MapDrawing drawing) {
|
||||
return DrawingMessageParser.createDrawingMessage(drawing);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,7 +29,8 @@ class HomeScreen extends StatefulWidget {
|
||||
State<HomeScreen> createState() => _HomeScreenState();
|
||||
}
|
||||
|
||||
class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateMixin {
|
||||
class _HomeScreenState extends State<HomeScreen>
|
||||
with SingleTickerProviderStateMixin {
|
||||
late TabController _tabController;
|
||||
int _currentIndex = 0;
|
||||
bool _isMapFullscreen = false;
|
||||
@@ -70,7 +71,10 @@ class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateM
|
||||
bool serviceEnabled = await Geolocator.isLocationServiceEnabled();
|
||||
if (!serviceEnabled) {
|
||||
if (context.mounted) {
|
||||
ToastLogger.error(context, 'Location services are disabled. Please enable them in Settings.');
|
||||
ToastLogger.error(
|
||||
context,
|
||||
'Location services are disabled. Please enable them in Settings.',
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -89,7 +93,10 @@ class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateM
|
||||
|
||||
if (permission == LocationPermission.deniedForever) {
|
||||
if (context.mounted) {
|
||||
ToastLogger.error(context, 'Location permission permanently denied. Please enable in Settings.');
|
||||
ToastLogger.error(
|
||||
context,
|
||||
'Location permission permanently denied. Please enable in Settings.',
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -124,7 +131,10 @@ class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateM
|
||||
await connectionProvider.sendSelfAdvert(floodMode: true);
|
||||
|
||||
if (context.mounted) {
|
||||
ToastLogger.success(context, 'Advertised at ${position.latitude.toStringAsFixed(6)}, ${position.longitude.toStringAsFixed(6)}');
|
||||
ToastLogger.success(
|
||||
context,
|
||||
'Advertised at ${position.latitude.toStringAsFixed(6)}, ${position.longitude.toStringAsFixed(6)}',
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
print('❌ Failed to advertise device: $e');
|
||||
@@ -146,31 +156,40 @@ class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateM
|
||||
backgroundColor: Colors.transparent,
|
||||
builder: (context) => Container(
|
||||
height: MediaQuery.of(context).size.height * 0.9,
|
||||
decoration: const BoxDecoration(
|
||||
color: Color(0xFF1E1E1E),
|
||||
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context).colorScheme.surface,
|
||||
borderRadius: const BorderRadius.vertical(top: Radius.circular(20)),
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
// Header
|
||||
Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context).colorScheme.surfaceContainerHighest,
|
||||
borderRadius: const BorderRadius.vertical(
|
||||
top: Radius.circular(20),
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.arrow_back, color: Colors.white),
|
||||
icon: Icon(
|
||||
Icons.arrow_back,
|
||||
color: Theme.of(context).colorScheme.onSurface,
|
||||
),
|
||||
onPressed: () {
|
||||
connectionProvider.stopScan();
|
||||
Navigator.pop(context);
|
||||
},
|
||||
),
|
||||
const Expanded(
|
||||
Expanded(
|
||||
child: Column(
|
||||
children: [
|
||||
Text(
|
||||
'MeshCore',
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
color: Theme.of(context).colorScheme.onSurface,
|
||||
fontSize: 18,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
@@ -178,7 +197,9 @@ class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateM
|
||||
Text(
|
||||
'Scanning for devices...',
|
||||
style: TextStyle(
|
||||
color: Colors.grey,
|
||||
color: Theme.of(
|
||||
context,
|
||||
).colorScheme.onSurfaceVariant,
|
||||
fontSize: 14,
|
||||
),
|
||||
),
|
||||
@@ -186,8 +207,14 @@ class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateM
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.more_vert, color: Colors.white),
|
||||
onPressed: () {},
|
||||
icon: Icon(
|
||||
Icons.refresh,
|
||||
color: Theme.of(context).colorScheme.primary,
|
||||
),
|
||||
onPressed: () {
|
||||
connectionProvider.stopScan();
|
||||
connectionProvider.startScan();
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
@@ -203,12 +230,18 @@ class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateM
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.info_outline, color: Theme.of(context).colorScheme.onPrimaryContainer),
|
||||
Icon(
|
||||
Icons.info_outline,
|
||||
color: Theme.of(context).colorScheme.onPrimaryContainer,
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
'The default pin for devices without a screen is 123456. Trouble pairing? Forget the bluetooth device in system settings.',
|
||||
style: TextStyle(color: Theme.of(context).colorScheme.onPrimaryContainer, fontSize: 13),
|
||||
style: TextStyle(
|
||||
color: Theme.of(context).colorScheme.onPrimaryContainer,
|
||||
fontSize: 13,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
@@ -222,16 +255,41 @@ class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateM
|
||||
child: Consumer<ConnectionProvider>(
|
||||
builder: (context, provider, child) {
|
||||
if (provider.isScanning && provider.scannedDevices.isEmpty) {
|
||||
return const Center(
|
||||
child: CircularProgressIndicator(),
|
||||
);
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
|
||||
if (provider.scannedDevices.isEmpty) {
|
||||
return const Center(
|
||||
child: Text(
|
||||
'No devices found',
|
||||
style: TextStyle(color: Colors.grey, fontSize: 16),
|
||||
return Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.bluetooth_searching,
|
||||
size: 64,
|
||||
color: Theme.of(
|
||||
context,
|
||||
).colorScheme.onSurfaceVariant.withOpacity(0.5),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'No devices found',
|
||||
style: TextStyle(
|
||||
color: Theme.of(
|
||||
context,
|
||||
).colorScheme.onSurfaceVariant,
|
||||
fontSize: 16,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
TextButton.icon(
|
||||
onPressed: () {
|
||||
connectionProvider.stopScan();
|
||||
connectionProvider.startScan();
|
||||
},
|
||||
icon: const Icon(Icons.refresh),
|
||||
label: const Text('Scan Again'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -239,42 +297,80 @@ class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateM
|
||||
return ListView.builder(
|
||||
itemCount: provider.scannedDevices.length,
|
||||
itemBuilder: (context, index) {
|
||||
final device = provider.scannedDevices[index];
|
||||
final scannedDevice = provider.scannedDevices[index];
|
||||
final device = scannedDevice.device;
|
||||
final rssi = scannedDevice.rssi;
|
||||
final signalColor = _getSignalColor(rssi);
|
||||
|
||||
return Container(
|
||||
margin: const EdgeInsets.symmetric(
|
||||
horizontal: 16,
|
||||
vertical: 4,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFF2D2D2D),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
color: Theme.of(
|
||||
context,
|
||||
).colorScheme.surfaceContainerHighest,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(
|
||||
color: Theme.of(
|
||||
context,
|
||||
).colorScheme.outline.withOpacity(0.2),
|
||||
width: 1,
|
||||
),
|
||||
),
|
||||
child: ListTile(
|
||||
leading: const Icon(
|
||||
contentPadding: const EdgeInsets.symmetric(
|
||||
horizontal: 16,
|
||||
vertical: 8,
|
||||
),
|
||||
leading: Icon(
|
||||
Icons.bluetooth,
|
||||
color: Colors.white,
|
||||
color: signalColor,
|
||||
size: 32,
|
||||
),
|
||||
title: Text(
|
||||
device.platformName.isNotEmpty
|
||||
? device.platformName
|
||||
: 'Unknown Device',
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
style: TextStyle(
|
||||
color: Theme.of(context).colorScheme.onSurface,
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
subtitle: const Text(
|
||||
'Tap to connect',
|
||||
style: TextStyle(color: Colors.grey, fontSize: 14),
|
||||
subtitle: Row(
|
||||
children: [
|
||||
Text(
|
||||
'Tap to connect',
|
||||
style: TextStyle(
|
||||
color: Theme.of(
|
||||
context,
|
||||
).colorScheme.onSurfaceVariant,
|
||||
fontSize: 14,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
'${rssi} dBm',
|
||||
style: TextStyle(
|
||||
color: signalColor,
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
trailing: const Icon(
|
||||
trailing: Icon(
|
||||
Icons.chevron_right,
|
||||
color: Colors.white,
|
||||
color: Theme.of(
|
||||
context,
|
||||
).colorScheme.onSurfaceVariant,
|
||||
),
|
||||
onTap: () async {
|
||||
print('🔵 [UI] User tapped device: ${device.platformName}');
|
||||
print(
|
||||
'🔵 [UI] User tapped device: ${device.platformName}',
|
||||
);
|
||||
|
||||
// Get app provider reference before popping dialog
|
||||
final appProvider = context.read<AppProvider>();
|
||||
@@ -284,17 +380,25 @@ class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateM
|
||||
|
||||
print('🔵 [UI] Calling provider.connect()...');
|
||||
final success = await provider.connect(device);
|
||||
print(success
|
||||
? '✅ [UI] provider.connect() returned success'
|
||||
: '❌ [UI] provider.connect() returned failure');
|
||||
print(
|
||||
success
|
||||
? '✅ [UI] provider.connect() returned success'
|
||||
: '❌ [UI] provider.connect() returned failure',
|
||||
);
|
||||
|
||||
if (success && provider.deviceInfo.isConnected) {
|
||||
print('✅ [UI] Device is connected, initializing app provider...');
|
||||
print(
|
||||
'✅ [UI] Device is connected, initializing app provider...',
|
||||
);
|
||||
await appProvider.initialize();
|
||||
print('✅ [UI] App provider initialized');
|
||||
} else {
|
||||
print('❌ [UI] Device not connected after connect() call');
|
||||
print(' Connection state: ${provider.deviceInfo.connectionState}');
|
||||
print(
|
||||
'❌ [UI] Device not connected after connect() call',
|
||||
);
|
||||
print(
|
||||
' Connection state: ${provider.deviceInfo.connectionState}',
|
||||
);
|
||||
print(' Error: ${provider.error}');
|
||||
}
|
||||
},
|
||||
@@ -317,60 +421,77 @@ class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateM
|
||||
final shouldHideUI = _isMapFullscreen && _currentIndex == 2;
|
||||
|
||||
return Scaffold(
|
||||
appBar: shouldHideUI ? null : AppBar(
|
||||
title: _buildCompactStatusBar(),
|
||||
actions: [
|
||||
PopupMenuButton(
|
||||
icon: const Icon(Icons.more_vert),
|
||||
itemBuilder: (context) => [
|
||||
PopupMenuItem(
|
||||
child: const Row(
|
||||
children: [
|
||||
Icon(Icons.map),
|
||||
SizedBox(width: 8),
|
||||
Text('Map Management'),
|
||||
appBar: shouldHideUI
|
||||
? null
|
||||
: AppBar(
|
||||
title: _buildCompactStatusBar(),
|
||||
actions: [
|
||||
Consumer<ConnectionProvider>(
|
||||
builder: (context, provider, child) {
|
||||
if (provider.deviceInfo.isConnected) {
|
||||
return IconButton(
|
||||
onPressed: () async {
|
||||
await provider.disconnect();
|
||||
},
|
||||
icon: const Icon(Icons.power_settings_new),
|
||||
tooltip: 'Disconnect',
|
||||
color: Colors.red.shade700,
|
||||
);
|
||||
}
|
||||
return const SizedBox.shrink();
|
||||
},
|
||||
),
|
||||
PopupMenuButton(
|
||||
icon: const Icon(Icons.more_vert),
|
||||
itemBuilder: (context) => [
|
||||
PopupMenuItem(
|
||||
child: const Row(
|
||||
children: [
|
||||
Icon(Icons.map),
|
||||
SizedBox(width: 8),
|
||||
Text('Map Management'),
|
||||
],
|
||||
),
|
||||
onTap: () {
|
||||
Future.delayed(Duration.zero, () {
|
||||
final appProvider = context.read<AppProvider>();
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => MapManagementScreen(
|
||||
tileCacheService: appProvider.tileCacheService,
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
},
|
||||
),
|
||||
PopupMenuItem(
|
||||
child: const Row(
|
||||
children: [
|
||||
Icon(Icons.settings),
|
||||
SizedBox(width: 8),
|
||||
Text('Settings'),
|
||||
],
|
||||
),
|
||||
onTap: () {
|
||||
Future.delayed(Duration.zero, () {
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => SettingsScreen(
|
||||
onThemeChanged: widget.onThemeChanged,
|
||||
currentTheme: widget.currentTheme,
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
onTap: () {
|
||||
Future.delayed(Duration.zero, () {
|
||||
final appProvider = context.read<AppProvider>();
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => MapManagementScreen(
|
||||
tileCacheService: appProvider.tileCacheService,
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
},
|
||||
),
|
||||
PopupMenuItem(
|
||||
child: const Row(
|
||||
children: [
|
||||
Icon(Icons.settings),
|
||||
SizedBox(width: 8),
|
||||
Text('Settings'),
|
||||
],
|
||||
),
|
||||
onTap: () {
|
||||
Future.delayed(Duration.zero, () {
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => SettingsScreen(
|
||||
onThemeChanged: widget.onThemeChanged,
|
||||
currentTheme: widget.currentTheme,
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
body: TabBarView(
|
||||
controller: _tabController,
|
||||
children: [
|
||||
@@ -385,44 +506,46 @@ class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateM
|
||||
),
|
||||
],
|
||||
),
|
||||
bottomNavigationBar: shouldHideUI ? null : Consumer2<MessagesProvider, ContactsProvider>(
|
||||
builder: (context, messagesProvider, contactsProvider, child) {
|
||||
final unreadCount = messagesProvider.unreadCount;
|
||||
final newContactsCount = contactsProvider.newContactsCount;
|
||||
bottomNavigationBar: shouldHideUI
|
||||
? null
|
||||
: Consumer2<MessagesProvider, ContactsProvider>(
|
||||
builder: (context, messagesProvider, contactsProvider, child) {
|
||||
final unreadCount = messagesProvider.unreadCount;
|
||||
final newContactsCount = contactsProvider.newContactsCount;
|
||||
|
||||
return Container(
|
||||
decoration: BoxDecoration(
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withOpacity(0.1),
|
||||
blurRadius: 4,
|
||||
offset: const Offset(0, -2),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: TabBar(
|
||||
controller: _tabController,
|
||||
tabs: [
|
||||
Tab(
|
||||
icon: _buildTabIconWithBadge(
|
||||
Icons.message,
|
||||
unreadCount,
|
||||
return Container(
|
||||
decoration: BoxDecoration(
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withOpacity(0.1),
|
||||
blurRadius: 4,
|
||||
offset: const Offset(0, -2),
|
||||
),
|
||||
],
|
||||
),
|
||||
text: 'Messages',
|
||||
),
|
||||
Tab(
|
||||
icon: _buildTabIconWithBadge(
|
||||
Icons.contacts,
|
||||
newContactsCount,
|
||||
child: TabBar(
|
||||
controller: _tabController,
|
||||
tabs: [
|
||||
Tab(
|
||||
icon: _buildTabIconWithBadge(
|
||||
Icons.message,
|
||||
unreadCount,
|
||||
),
|
||||
text: 'Messages',
|
||||
),
|
||||
Tab(
|
||||
icon: _buildTabIconWithBadge(
|
||||
Icons.contacts,
|
||||
newContactsCount,
|
||||
),
|
||||
text: 'Contacts',
|
||||
),
|
||||
const Tab(icon: Icon(Icons.map), text: 'Map'),
|
||||
],
|
||||
),
|
||||
text: 'Contacts',
|
||||
),
|
||||
const Tab(icon: Icon(Icons.map), text: 'Map'),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -432,7 +555,9 @@ class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateM
|
||||
final deviceInfo = provider.deviceInfo;
|
||||
final isConnected = deviceInfo.isConnected;
|
||||
|
||||
print('🎨 [UI] Building status bar - isConnected: $isConnected, state: ${deviceInfo.connectionState}');
|
||||
print(
|
||||
'🎨 [UI] Building status bar - isConnected: $isConnected, state: ${deviceInfo.connectionState}',
|
||||
);
|
||||
|
||||
return Row(
|
||||
children: [
|
||||
@@ -443,24 +568,46 @@ class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateM
|
||||
children: [
|
||||
const Text(
|
||||
'MeshCore',
|
||||
style: TextStyle(
|
||||
fontSize: 20,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
|
||||
),
|
||||
Text(
|
||||
isConnected
|
||||
? deviceInfo.displayName ?? 'Connected'
|
||||
: (provider.isReconnecting
|
||||
? 'Reconnecting... (${provider.reconnectionAttempt}/${provider.maxReconnectionAttempts})'
|
||||
: 'Disconnected'),
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
color: provider.isReconnecting
|
||||
? Colors.orange[600]
|
||||
: Colors.grey[600],
|
||||
if (isConnected)
|
||||
Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
// BLE connection strength indicator
|
||||
Icon(
|
||||
Icons.bluetooth_connected,
|
||||
color: deviceInfo.signalRssi != null
|
||||
? _getSignalColor(deviceInfo.signalRssi!)
|
||||
: Colors.grey,
|
||||
size: 16,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
// Battery indicator
|
||||
if (deviceInfo.batteryPercent != null) ...[
|
||||
Icon(
|
||||
_getBatteryIcon(deviceInfo.batteryPercent!),
|
||||
color: _getBatteryColor(deviceInfo.batteryPercent!),
|
||||
size: 16,
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
'${deviceInfo.batteryPercent!.round()}%',
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
color: _getBatteryColor(
|
||||
deviceInfo.batteryPercent!,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
)
|
||||
else if (provider.isReconnecting)
|
||||
Text(
|
||||
'Reconnecting... (${provider.reconnectionAttempt}/${provider.maxReconnectionAttempts})',
|
||||
style: TextStyle(fontSize: 14, color: Colors.orange[600]),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
@@ -478,13 +625,17 @@ class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateM
|
||||
height: 14,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
valueColor: AlwaysStoppedAnimation<Color>(Colors.black54),
|
||||
valueColor: AlwaysStoppedAnimation<Color>(
|
||||
Colors.black54,
|
||||
),
|
||||
),
|
||||
)
|
||||
: const Icon(Icons.bluetooth, size: 18),
|
||||
label: Text(provider.isReconnecting
|
||||
? 'Reconnecting (${provider.reconnectionAttempt}/${provider.maxReconnectionAttempts})'
|
||||
: 'Connect'),
|
||||
label: Text(
|
||||
provider.isReconnecting
|
||||
? 'Reconnecting (${provider.reconnectionAttempt}/${provider.maxReconnectionAttempts})'
|
||||
: 'Connect',
|
||||
),
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: Colors.white,
|
||||
foregroundColor: Colors.black87,
|
||||
@@ -514,15 +665,27 @@ class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateM
|
||||
Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
// Advertise button (broadcast location)
|
||||
FilledButton(
|
||||
onPressed: () => _advertiseDevice(context),
|
||||
style: FilledButton.styleFrom(
|
||||
backgroundColor: Colors.blue.shade700,
|
||||
foregroundColor: Colors.white,
|
||||
padding: const EdgeInsets.all(10),
|
||||
minimumSize: const Size(40, 40),
|
||||
shape: const CircleBorder(),
|
||||
),
|
||||
child: const Icon(Icons.campaign, size: 20),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
// RX/TX indicators with long press to open packet log
|
||||
GestureDetector(
|
||||
onLongPress: () {
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => PacketLogScreen(
|
||||
bleService: provider.bleService,
|
||||
),
|
||||
builder: (context) =>
|
||||
PacketLogScreen(bleService: provider.bleService),
|
||||
),
|
||||
);
|
||||
},
|
||||
@@ -597,9 +760,8 @@ class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateM
|
||||
Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (context) => PacketLogScreen(
|
||||
bleService: provider.bleService,
|
||||
),
|
||||
builder: (context) =>
|
||||
PacketLogScreen(bleService: provider.bleService),
|
||||
),
|
||||
);
|
||||
},
|
||||
@@ -610,34 +772,9 @@ class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateM
|
||||
child: const Icon(Icons.settings, size: 20),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
// Advertise button (broadcast location)
|
||||
FilledButton(
|
||||
onPressed: () => _advertiseDevice(context),
|
||||
style: FilledButton.styleFrom(
|
||||
backgroundColor: Colors.blue.shade700,
|
||||
foregroundColor: Colors.white,
|
||||
padding: const EdgeInsets.all(10),
|
||||
minimumSize: const Size(40, 40),
|
||||
shape: const CircleBorder(),
|
||||
),
|
||||
child: const Icon(Icons.campaign, size: 20),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
// Disconnect button (prominent, icon only)
|
||||
FilledButton(
|
||||
onPressed: () async {
|
||||
await provider.disconnect();
|
||||
},
|
||||
style: FilledButton.styleFrom(
|
||||
backgroundColor: Colors.red.shade700,
|
||||
foregroundColor: Colors.white,
|
||||
padding: const EdgeInsets.all(10),
|
||||
minimumSize: const Size(40, 40),
|
||||
shape: const CircleBorder(),
|
||||
),
|
||||
child: const Icon(Icons.power_settings_new, size: 20),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
|
||||
// Disconnect button (prominent, icon only) - pushed to far right edge
|
||||
],
|
||||
),
|
||||
],
|
||||
@@ -661,7 +798,9 @@ class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateM
|
||||
children: [
|
||||
// Connection status
|
||||
Icon(
|
||||
isConnected ? Icons.bluetooth_connected : Icons.bluetooth_disabled,
|
||||
isConnected
|
||||
? Icons.bluetooth_connected
|
||||
: Icons.bluetooth_disabled,
|
||||
color: isConnected ? Colors.green : Colors.grey,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
@@ -764,7 +903,10 @@ class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateM
|
||||
Expanded(
|
||||
child: Text(
|
||||
provider.error!,
|
||||
style: const TextStyle(color: Colors.red, fontSize: 12),
|
||||
style: const TextStyle(
|
||||
color: Colors.red,
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
@@ -822,10 +964,7 @@ class _HomeScreenState extends State<HomeScreen> with SingleTickerProviderStateM
|
||||
color: Colors.red,
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
constraints: const BoxConstraints(
|
||||
minWidth: 18,
|
||||
minHeight: 18,
|
||||
),
|
||||
constraints: const BoxConstraints(minWidth: 18, minHeight: 18),
|
||||
child: Text(
|
||||
count > 99 ? '99+' : count.toString(),
|
||||
style: const TextStyle(
|
||||
|
||||
@@ -117,7 +117,6 @@ class _MessagesTabState extends State<MessagesTab> {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void _showSarDialog() {
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
@@ -125,7 +124,13 @@ class _MessagesTabState extends State<MessagesTab> {
|
||||
backgroundColor: Colors.transparent,
|
||||
builder: (context) => SarUpdateSheet(
|
||||
onSend: (sarType, position, notes, roomPublicKey, sendToChannel) async {
|
||||
await _sendSarMessage(sarType, position, notes, roomPublicKey, sendToChannel);
|
||||
await _sendSarMessage(
|
||||
sarType,
|
||||
position,
|
||||
notes,
|
||||
roomPublicKey,
|
||||
sendToChannel,
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
@@ -155,7 +160,8 @@ class _MessagesTabState extends State<MessagesTab> {
|
||||
|
||||
try {
|
||||
// Format: S:<emoji>:<latitude>,<longitude>
|
||||
final sarMessage = 'S:${sarType.emoji}:${position.latitude},${position.longitude}';
|
||||
final sarMessage =
|
||||
'S:${sarType.emoji}:${position.latitude},${position.longitude}';
|
||||
|
||||
// Add notes if provided
|
||||
final fullMessage = notes != null && notes.isNotEmpty
|
||||
@@ -170,7 +176,10 @@ class _MessagesTabState extends State<MessagesTab> {
|
||||
);
|
||||
|
||||
if (!mounted) return;
|
||||
ToastLogger.warning(context, '${sarType.displayName} marker broadcast to public channel');
|
||||
ToastLogger.warning(
|
||||
context,
|
||||
'${sarType.displayName} marker broadcast to public channel',
|
||||
);
|
||||
} else {
|
||||
// Create message ID
|
||||
final messageId = '${DateTime.now().millisecondsSinceEpoch}_sent';
|
||||
@@ -202,7 +211,7 @@ class _MessagesTabState extends State<MessagesTab> {
|
||||
final contactsProvider = context.read<ContactsProvider>();
|
||||
final roomContact = contactsProvider.contacts.where((c) {
|
||||
return c.publicKey.length >= roomPublicKey!.length &&
|
||||
_publicKeysMatch(c.publicKey, roomPublicKey!);
|
||||
_publicKeysMatch(c.publicKey, roomPublicKey!);
|
||||
}).firstOrNull;
|
||||
|
||||
// Send SAR message to selected room (persisted and immutable)
|
||||
@@ -219,7 +228,10 @@ class _MessagesTabState extends State<MessagesTab> {
|
||||
}
|
||||
|
||||
if (!mounted) return;
|
||||
ToastLogger.success(context, '${sarType.displayName} marker sent to room');
|
||||
ToastLogger.success(
|
||||
context,
|
||||
'${sarType.displayName} marker sent to room',
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
@@ -227,7 +239,6 @@ class _MessagesTabState extends State<MessagesTab> {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Handle pull-to-refresh for manual message sync
|
||||
/// This is a FALLBACK mechanism - messages are normally synced automatically via PUSH_CODE_MSG_WAITING
|
||||
Future<void> _handleRefresh() async {
|
||||
@@ -242,8 +253,6 @@ class _MessagesTabState extends State<MessagesTab> {
|
||||
try {
|
||||
print('🔄 [MessagesTab] Manual refresh triggered - syncing messages');
|
||||
final messageCount = await connectionProvider.syncAllMessages();
|
||||
print('✅ [MessagesTab] Synced $messageCount message(s)');
|
||||
|
||||
if (!mounted) return;
|
||||
if (messageCount > 0) {
|
||||
ToastLogger.success(context, 'Synced $messageCount message(s)');
|
||||
@@ -277,65 +286,73 @@ class _MessagesTabState extends State<MessagesTab> {
|
||||
onRefresh: _handleRefresh,
|
||||
child: messages.isEmpty
|
||||
? LayoutBuilder(
|
||||
builder: (context, constraints) => SingleChildScrollView(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
child: ConstrainedBox(
|
||||
constraints: BoxConstraints(minHeight: constraints.maxHeight),
|
||||
child: Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.message_outlined,
|
||||
size: 64,
|
||||
color: Theme.of(context).disabledColor,
|
||||
builder: (context, constraints) =>
|
||||
SingleChildScrollView(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
child: ConstrainedBox(
|
||||
constraints: BoxConstraints(
|
||||
minHeight: constraints.maxHeight,
|
||||
),
|
||||
child: Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.message_outlined,
|
||||
size: 64,
|
||||
color: Theme.of(context).disabledColor,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'No messages yet',
|
||||
style: Theme.of(
|
||||
context,
|
||||
).textTheme.titleLarge,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'Pull down to sync messages',
|
||||
style: Theme.of(
|
||||
context,
|
||||
).textTheme.bodyMedium,
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'No messages yet',
|
||||
style: Theme.of(context).textTheme.titleLarge,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'Pull down to sync messages',
|
||||
style: Theme.of(context).textTheme.bodyMedium,
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
: ListView.builder(
|
||||
reverse: true,
|
||||
padding: const EdgeInsets.all(8),
|
||||
itemCount: messages.length,
|
||||
itemBuilder: (context, index) {
|
||||
final message = messages[index];
|
||||
reverse: true,
|
||||
padding: const EdgeInsets.all(8),
|
||||
itemCount: messages.length,
|
||||
itemBuilder: (context, index) {
|
||||
final message = messages[index];
|
||||
|
||||
// Display system messages with minimal styling
|
||||
if (message.isSystemMessage) {
|
||||
return _SystemMessageBubble(message: message);
|
||||
}
|
||||
// Display system messages with minimal styling
|
||||
if (message.isSystemMessage) {
|
||||
return _SystemMessageBubble(message: message);
|
||||
}
|
||||
|
||||
return _MessageBubble(
|
||||
message: message,
|
||||
onTap: message.isSarMarker &&
|
||||
message.sarGpsCoordinates != null
|
||||
? () {
|
||||
final mapProvider =
|
||||
context.read<MapProvider>();
|
||||
mapProvider.navigateToLocation(
|
||||
location: message.sarGpsCoordinates!,
|
||||
zoom: 15.0,
|
||||
);
|
||||
widget.onNavigateToMap();
|
||||
}
|
||||
: null,
|
||||
);
|
||||
},
|
||||
),
|
||||
return _MessageBubble(
|
||||
message: message,
|
||||
onTap:
|
||||
message.isSarMarker &&
|
||||
message.sarGpsCoordinates != null
|
||||
? () {
|
||||
final mapProvider = context
|
||||
.read<MapProvider>();
|
||||
mapProvider.navigateToLocation(
|
||||
location: message.sarGpsCoordinates!,
|
||||
zoom: 15.0,
|
||||
);
|
||||
widget.onNavigateToMap();
|
||||
}
|
||||
: null,
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -352,68 +369,72 @@ class _MessagesTabState extends State<MessagesTab> {
|
||||
),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
children: [
|
||||
// SAR quick action button
|
||||
IconButton(
|
||||
icon: const Icon(Icons.add_location_alt),
|
||||
tooltip: 'Send SAR marker',
|
||||
onPressed: _showSarDialog,
|
||||
style: IconButton.styleFrom(
|
||||
backgroundColor: Theme.of(context).colorScheme.primaryContainer,
|
||||
foregroundColor: Theme.of(context).colorScheme.onPrimaryContainer,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
// Text field with embedded send button
|
||||
Expanded(
|
||||
child: TextField(
|
||||
controller: _textController,
|
||||
focusNode: _focusNode,
|
||||
maxLength: _maxCharacters,
|
||||
maxLines: null,
|
||||
maxLengthEnforcement: MaxLengthEnforcement.enforced,
|
||||
style: const TextStyle(fontSize: 14),
|
||||
decoration: InputDecoration(
|
||||
hintText: 'Type a message...',
|
||||
hintStyle: const TextStyle(fontSize: 14),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(24),
|
||||
),
|
||||
contentPadding: const EdgeInsets.symmetric(
|
||||
horizontal: 16,
|
||||
vertical: 10,
|
||||
),
|
||||
isDense: true,
|
||||
counterText: _characterCount >= 150
|
||||
? '$_characterCount/$_maxCharacters'
|
||||
: '',
|
||||
counterStyle: TextStyle(
|
||||
fontSize: 10,
|
||||
color: _characterCount > _maxCharacters * 0.9
|
||||
? Colors.orange
|
||||
: Theme.of(context).textTheme.bodySmall?.color,
|
||||
),
|
||||
suffixIcon: IconButton(
|
||||
icon: Icon(
|
||||
Icons.send_rounded,
|
||||
size: 22,
|
||||
color: _textController.text.trim().isEmpty
|
||||
? Theme.of(context).disabledColor
|
||||
: Theme.of(context).colorScheme.primary,
|
||||
),
|
||||
onPressed: _textController.text.trim().isEmpty
|
||||
? null
|
||||
: _sendMessage,
|
||||
tooltip: 'Send',
|
||||
),
|
||||
),
|
||||
textInputAction: TextInputAction.send,
|
||||
onSubmitted: (_) => _sendMessage(),
|
||||
),
|
||||
),
|
||||
],
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
children: [
|
||||
// SAR quick action button
|
||||
IconButton(
|
||||
icon: const Icon(Icons.add_location_alt),
|
||||
tooltip: 'Send SAR marker',
|
||||
onPressed: _showSarDialog,
|
||||
style: IconButton.styleFrom(
|
||||
backgroundColor: Theme.of(
|
||||
context,
|
||||
).colorScheme.primaryContainer,
|
||||
foregroundColor: Theme.of(
|
||||
context,
|
||||
).colorScheme.onPrimaryContainer,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
// Text field with embedded send button
|
||||
Expanded(
|
||||
child: TextField(
|
||||
controller: _textController,
|
||||
focusNode: _focusNode,
|
||||
maxLength: _maxCharacters,
|
||||
maxLines: null,
|
||||
maxLengthEnforcement: MaxLengthEnforcement.enforced,
|
||||
style: const TextStyle(fontSize: 14),
|
||||
decoration: InputDecoration(
|
||||
hintText: 'Type a message...',
|
||||
hintStyle: const TextStyle(fontSize: 14),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(24),
|
||||
),
|
||||
contentPadding: const EdgeInsets.symmetric(
|
||||
horizontal: 16,
|
||||
vertical: 10,
|
||||
),
|
||||
isDense: true,
|
||||
counterText: _characterCount >= 150
|
||||
? '$_characterCount/$_maxCharacters'
|
||||
: '',
|
||||
counterStyle: TextStyle(
|
||||
fontSize: 10,
|
||||
color: _characterCount > _maxCharacters * 0.9
|
||||
? Colors.orange
|
||||
: Theme.of(context).textTheme.bodySmall?.color,
|
||||
),
|
||||
suffixIcon: IconButton(
|
||||
icon: Icon(
|
||||
Icons.send_rounded,
|
||||
size: 22,
|
||||
color: _textController.text.trim().isEmpty
|
||||
? Theme.of(context).disabledColor
|
||||
: Theme.of(context).colorScheme.primary,
|
||||
),
|
||||
onPressed: _textController.text.trim().isEmpty
|
||||
? null
|
||||
: _sendMessage,
|
||||
tooltip: 'Send',
|
||||
),
|
||||
),
|
||||
textInputAction: TextInputAction.send,
|
||||
onSubmitted: (_) => _sendMessage(),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
@@ -426,10 +447,7 @@ class _MessageBubble extends StatelessWidget {
|
||||
final Message message;
|
||||
final VoidCallback? onTap;
|
||||
|
||||
const _MessageBubble({
|
||||
required this.message,
|
||||
this.onTap,
|
||||
});
|
||||
const _MessageBubble({required this.message, this.onTap});
|
||||
|
||||
/// Helper method to compare two public keys for equality
|
||||
bool _publicKeysMatch(Uint8List key1, Uint8List key2) {
|
||||
@@ -440,7 +458,10 @@ class _MessageBubble extends StatelessWidget {
|
||||
return true;
|
||||
}
|
||||
|
||||
Future<void> _retryFailedMessage(BuildContext context, Message failedMessage) async {
|
||||
Future<void> _retryFailedMessage(
|
||||
BuildContext context,
|
||||
Message failedMessage,
|
||||
) async {
|
||||
final connectionProvider = context.read<ConnectionProvider>();
|
||||
final messagesProvider = context.read<MessagesProvider>();
|
||||
|
||||
@@ -467,15 +488,19 @@ class _MessageBubble extends StatelessWidget {
|
||||
// Direct message retry (for SAR markers sent to rooms)
|
||||
if (failedMessage.recipientPublicKey == null) {
|
||||
messagesProvider.markMessageFailed(retryMessageId);
|
||||
ToastLogger.error(context, 'Cannot retry: recipient information missing');
|
||||
ToastLogger.error(
|
||||
context,
|
||||
'Cannot retry: recipient information missing',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Look up the room contact for path logging
|
||||
final contactsProvider = context.read<ContactsProvider>();
|
||||
final roomContact = contactsProvider.contacts.where((c) {
|
||||
return c.publicKey.length >= failedMessage.recipientPublicKey!.length &&
|
||||
_publicKeysMatch(c.publicKey, failedMessage.recipientPublicKey!);
|
||||
return c.publicKey.length >=
|
||||
failedMessage.recipientPublicKey!.length &&
|
||||
_publicKeysMatch(c.publicKey, failedMessage.recipientPublicKey!);
|
||||
}).firstOrNull;
|
||||
|
||||
// Resend to the same room
|
||||
@@ -511,12 +536,14 @@ class _MessageBubble extends StatelessWidget {
|
||||
// Determine if this is own message
|
||||
final connectionProvider = context.read<ConnectionProvider>();
|
||||
final selfPublicKey = connectionProvider.deviceInfo.publicKey;
|
||||
final isOwnMessage = message.isSentMessage || message.isFromSelf(selfPublicKey);
|
||||
final isOwnMessage =
|
||||
message.isSentMessage || message.isFromSelf(selfPublicKey);
|
||||
|
||||
// Check if we can reply to this message (must be contact message from someone else)
|
||||
final canReply = message.isContactMessage &&
|
||||
!isOwnMessage &&
|
||||
message.senderPublicKeyPrefix != null;
|
||||
final canReply =
|
||||
message.isContactMessage &&
|
||||
!isOwnMessage &&
|
||||
message.senderPublicKeyPrefix != null;
|
||||
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
@@ -552,7 +579,10 @@ class _MessageBubble extends StatelessWidget {
|
||||
// Delete message option
|
||||
ListTile(
|
||||
leading: const Icon(Icons.delete, color: Colors.red),
|
||||
title: const Text('Delete message', style: TextStyle(color: Colors.red)),
|
||||
title: const Text(
|
||||
'Delete message',
|
||||
style: TextStyle(color: Colors.red),
|
||||
),
|
||||
onTap: () {
|
||||
Navigator.pop(context);
|
||||
_showDeleteConfirmation(context);
|
||||
@@ -575,7 +605,12 @@ class _MessageBubble extends StatelessWidget {
|
||||
|
||||
// Find contact by public key prefix (first 6 bytes)
|
||||
final senderKeyHex = message.senderPublicKeyPrefix!
|
||||
.sublist(0, message.senderPublicKeyPrefix!.length < 6 ? message.senderPublicKeyPrefix!.length : 6)
|
||||
.sublist(
|
||||
0,
|
||||
message.senderPublicKeyPrefix!.length < 6
|
||||
? message.senderPublicKeyPrefix!.length
|
||||
: 6,
|
||||
)
|
||||
.map((b) => b.toRadixString(16).padLeft(2, '0'))
|
||||
.join('');
|
||||
|
||||
@@ -633,7 +668,8 @@ class _MessageBubble extends StatelessWidget {
|
||||
// after loading from storage
|
||||
final connectionProvider = context.read<ConnectionProvider>();
|
||||
final selfPublicKey = connectionProvider.deviceInfo.publicKey;
|
||||
final isOwnMessage = message.isSentMessage || message.isFromSelf(selfPublicKey);
|
||||
final isOwnMessage =
|
||||
message.isSentMessage || message.isFromSelf(selfPublicKey);
|
||||
|
||||
// Debug logging for sent messages
|
||||
if (message.isSentMessage) {
|
||||
@@ -642,9 +678,13 @@ class _MessageBubble extends StatelessWidget {
|
||||
debugPrint(' Delivery Status: ${message.deliveryStatus.name}');
|
||||
debugPrint(' isSentMessage: ${message.isSentMessage}');
|
||||
debugPrint(' isOwnMessage: $isOwnMessage');
|
||||
debugPrint(' Has recipientPublicKey: ${message.recipientPublicKey != null}');
|
||||
debugPrint(
|
||||
' Has recipientPublicKey: ${message.recipientPublicKey != null}',
|
||||
);
|
||||
if (message.recipientPublicKey != null) {
|
||||
debugPrint(' Recipient key (first 12 hex): ${message.recipientPublicKey!.sublist(0, 6).map((b) => b.toRadixString(16).padLeft(2, '0')).join()}');
|
||||
debugPrint(
|
||||
' Recipient key (first 12 hex): ${message.recipientPublicKey!.sublist(0, 6).map((b) => b.toRadixString(16).padLeft(2, '0')).join()}',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -654,7 +694,12 @@ class _MessageBubble extends StatelessWidget {
|
||||
if (message.senderPublicKeyPrefix != null && !isOwnMessage) {
|
||||
// Find contact by public key prefix (first 6 bytes)
|
||||
final senderKeyHex = message.senderPublicKeyPrefix!
|
||||
.sublist(0, message.senderPublicKeyPrefix!.length < 6 ? message.senderPublicKeyPrefix!.length : 6)
|
||||
.sublist(
|
||||
0,
|
||||
message.senderPublicKeyPrefix!.length < 6
|
||||
? message.senderPublicKeyPrefix!.length
|
||||
: 6,
|
||||
)
|
||||
.map((b) => b.toRadixString(16).padLeft(2, '0'))
|
||||
.join('');
|
||||
|
||||
@@ -671,10 +716,17 @@ class _MessageBubble extends StatelessWidget {
|
||||
// For sent direct messages, look up recipient contact
|
||||
dynamic recipientContact;
|
||||
String? recipientDisplayName;
|
||||
if (isOwnMessage && message.isContactMessage && message.recipientPublicKey != null) {
|
||||
if (isOwnMessage &&
|
||||
message.isContactMessage &&
|
||||
message.recipientPublicKey != null) {
|
||||
// Find recipient by public key
|
||||
final recipientKeyHex = message.recipientPublicKey!
|
||||
.sublist(0, message.recipientPublicKey!.length < 6 ? message.recipientPublicKey!.length : 6)
|
||||
.sublist(
|
||||
0,
|
||||
message.recipientPublicKey!.length < 6
|
||||
? message.recipientPublicKey!.length
|
||||
: 6,
|
||||
)
|
||||
.map((b) => b.toRadixString(16).padLeft(2, '0'))
|
||||
.join('');
|
||||
|
||||
@@ -686,8 +738,12 @@ class _MessageBubble extends StatelessWidget {
|
||||
for (final c in contactsProvider.contacts) {
|
||||
debugPrint(' Contact: ${c.displayName ?? c.advName}');
|
||||
debugPrint(' Key: ${c.publicKeyHex}');
|
||||
debugPrint(' First 12 chars: ${c.publicKeyHex.substring(0, c.publicKeyHex.length >= 12 ? 12 : c.publicKeyHex.length)}');
|
||||
debugPrint(' Matches: ${c.publicKeyHex.startsWith(recipientKeyHex)}');
|
||||
debugPrint(
|
||||
' First 12 chars: ${c.publicKeyHex.substring(0, c.publicKeyHex.length >= 12 ? 12 : c.publicKeyHex.length)}',
|
||||
);
|
||||
debugPrint(
|
||||
' Matches: ${c.publicKeyHex.startsWith(recipientKeyHex)}',
|
||||
);
|
||||
}
|
||||
|
||||
recipientContact = contactsProvider.contacts.where((c) {
|
||||
@@ -704,7 +760,8 @@ class _MessageBubble extends StatelessWidget {
|
||||
if (roleEmoji != null && roleEmoji.isNotEmpty) {
|
||||
recipientDisplayName = '$roleEmoji ${recipientContact.displayName}';
|
||||
} else {
|
||||
recipientDisplayName = recipientContact.displayName ?? recipientContact.advName;
|
||||
recipientDisplayName =
|
||||
recipientContact.displayName ?? recipientContact.advName;
|
||||
}
|
||||
debugPrint(' Final recipient name: $recipientDisplayName');
|
||||
} else {
|
||||
@@ -737,20 +794,24 @@ class _MessageBubble extends StatelessWidget {
|
||||
width: 2,
|
||||
)
|
||||
: isOwnMessage
|
||||
? Border.all(
|
||||
color: Theme.of(context).colorScheme.primary.withValues(alpha: 0.3),
|
||||
width: 1.5,
|
||||
)
|
||||
: !message.isRead && !message.isSentMessage && !message.isSystemMessage
|
||||
? Border.all(
|
||||
color: Colors.blue,
|
||||
width: 1.5,
|
||||
)
|
||||
: null,
|
||||
? Border.all(
|
||||
color: Theme.of(
|
||||
context,
|
||||
).colorScheme.primary.withValues(alpha: 0.3),
|
||||
width: 1.5,
|
||||
)
|
||||
: !message.isRead &&
|
||||
!message.isSentMessage &&
|
||||
!message.isSystemMessage
|
||||
? Border.all(color: Colors.blue, width: 1.5)
|
||||
: null,
|
||||
boxShadow: isSarMarker
|
||||
? [
|
||||
BoxShadow(
|
||||
color: _getSarMarkerBorderColor(context, isDarkMode).withValues(alpha: 0.3),
|
||||
color: _getSarMarkerBorderColor(
|
||||
context,
|
||||
isDarkMode,
|
||||
).withValues(alpha: 0.3),
|
||||
blurRadius: 8,
|
||||
offset: const Offset(0, 2),
|
||||
),
|
||||
@@ -764,7 +825,10 @@ class _MessageBubble extends StatelessWidget {
|
||||
Row(
|
||||
children: [
|
||||
// Unread indicator badge
|
||||
if (!message.isRead && !message.isSentMessage && !message.isSystemMessage && !isSarMarker)
|
||||
if (!message.isRead &&
|
||||
!message.isSentMessage &&
|
||||
!message.isSystemMessage &&
|
||||
!isSarMarker)
|
||||
Container(
|
||||
width: 8,
|
||||
height: 8,
|
||||
@@ -795,7 +859,8 @@ class _MessageBubble extends StatelessWidget {
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
'SAR ALERT',
|
||||
style: Theme.of(context).textTheme.labelSmall?.copyWith(
|
||||
style: Theme.of(context).textTheme.labelSmall
|
||||
?.copyWith(
|
||||
color: Colors.white,
|
||||
fontWeight: FontWeight.bold,
|
||||
letterSpacing: 0.5,
|
||||
@@ -806,7 +871,11 @@ class _MessageBubble extends StatelessWidget {
|
||||
)
|
||||
else ...[
|
||||
if (isOwnMessage)
|
||||
Icon(Icons.account_circle, size: 16, color: Theme.of(context).colorScheme.primary)
|
||||
Icon(
|
||||
Icons.account_circle,
|
||||
size: 16,
|
||||
color: Theme.of(context).colorScheme.primary,
|
||||
)
|
||||
else if (message.isChannelMessage)
|
||||
const Icon(Icons.tag, size: 16)
|
||||
else
|
||||
@@ -815,25 +884,33 @@ class _MessageBubble extends StatelessWidget {
|
||||
Text(
|
||||
displayName,
|
||||
style: Theme.of(context).textTheme.labelMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
color: isOwnMessage ? Theme.of(context).colorScheme.primary : null,
|
||||
),
|
||||
fontWeight: FontWeight.bold,
|
||||
color: isOwnMessage
|
||||
? Theme.of(context).colorScheme.primary
|
||||
: null,
|
||||
),
|
||||
),
|
||||
// Show recipient for sent direct messages
|
||||
if (isOwnMessage && message.isContactMessage && recipientDisplayName != null) ...[
|
||||
if (isOwnMessage &&
|
||||
message.isContactMessage &&
|
||||
recipientDisplayName != null) ...[
|
||||
const SizedBox(width: 4),
|
||||
Icon(
|
||||
Icons.arrow_forward,
|
||||
size: 14,
|
||||
color: Theme.of(context).textTheme.labelSmall?.color?.withValues(alpha: 0.6),
|
||||
color: Theme.of(
|
||||
context,
|
||||
).textTheme.labelSmall?.color?.withValues(alpha: 0.6),
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
recipientDisplayName,
|
||||
style: Theme.of(context).textTheme.labelSmall?.copyWith(
|
||||
color: Theme.of(context).textTheme.labelSmall?.color?.withValues(alpha: 0.7),
|
||||
fontStyle: FontStyle.italic,
|
||||
),
|
||||
color: Theme.of(
|
||||
context,
|
||||
).textTheme.labelSmall?.color?.withValues(alpha: 0.7),
|
||||
fontStyle: FontStyle.italic,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
@@ -841,8 +918,10 @@ class _MessageBubble extends StatelessWidget {
|
||||
Text(
|
||||
message.timeAgo,
|
||||
style: Theme.of(context).textTheme.labelSmall?.copyWith(
|
||||
fontWeight: isSarMarker ? FontWeight.w600 : FontWeight.normal,
|
||||
),
|
||||
fontWeight: isSarMarker
|
||||
? FontWeight.w600
|
||||
: FontWeight.normal,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
@@ -863,16 +942,14 @@ class _MessageBubble extends StatelessWidget {
|
||||
children: [
|
||||
Text(
|
||||
message.sarMarkerType!.displayName,
|
||||
style: Theme.of(context).textTheme.titleSmall?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
style: Theme.of(context).textTheme.titleSmall
|
||||
?.copyWith(fontWeight: FontWeight.bold),
|
||||
),
|
||||
if (message.sarGpsCoordinates != null)
|
||||
Text(
|
||||
'${message.sarGpsCoordinates!.latitude.toStringAsFixed(5)}, ${message.sarGpsCoordinates!.longitude.toStringAsFixed(5)}',
|
||||
style: Theme.of(context).textTheme.labelSmall?.copyWith(
|
||||
fontFamily: 'monospace',
|
||||
),
|
||||
style: Theme.of(context).textTheme.labelSmall
|
||||
?.copyWith(fontFamily: 'monospace'),
|
||||
),
|
||||
],
|
||||
),
|
||||
@@ -884,13 +961,25 @@ class _MessageBubble extends StatelessWidget {
|
||||
),
|
||||
],
|
||||
),
|
||||
// Display SAR notes/message if present
|
||||
if (message.sarNotes != null && message.sarNotes!.isNotEmpty) ...[
|
||||
const SizedBox(height: 8),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context).colorScheme.surfaceVariant.withValues(alpha: 0.5),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Text(
|
||||
message.sarNotes!,
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
),
|
||||
],
|
||||
]
|
||||
// Regular message content
|
||||
else
|
||||
Text(
|
||||
message.text,
|
||||
style: Theme.of(context).textTheme.bodyMedium,
|
||||
),
|
||||
Text(message.text, style: Theme.of(context).textTheme.bodyMedium),
|
||||
|
||||
// Delivery status for sent messages
|
||||
if (message.isSentMessage) ...[
|
||||
@@ -907,17 +996,21 @@ class _MessageBubble extends StatelessWidget {
|
||||
Text(
|
||||
message.deliveryStatusText,
|
||||
style: Theme.of(context).textTheme.labelSmall?.copyWith(
|
||||
color: _getDeliveryStatusColor(message.deliveryStatus),
|
||||
fontStyle: FontStyle.italic,
|
||||
),
|
||||
color: _getDeliveryStatusColor(message.deliveryStatus),
|
||||
fontStyle: FontStyle.italic,
|
||||
),
|
||||
),
|
||||
// Show retry button for failed messages
|
||||
if (message.deliveryStatus == MessageDeliveryStatus.failed) ...[
|
||||
if (message.deliveryStatus ==
|
||||
MessageDeliveryStatus.failed) ...[
|
||||
const SizedBox(width: 6),
|
||||
GestureDetector(
|
||||
onTap: () => _retryFailedMessage(context, message),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 6,
|
||||
vertical: 2,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.orange.withOpacity(0.2),
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
@@ -926,11 +1019,16 @@ class _MessageBubble extends StatelessWidget {
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Icon(Icons.refresh, size: 12, color: Colors.orange),
|
||||
const Icon(
|
||||
Icons.refresh,
|
||||
size: 12,
|
||||
color: Colors.orange,
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
'Retry',
|
||||
style: Theme.of(context).textTheme.labelSmall?.copyWith(
|
||||
style: Theme.of(context).textTheme.labelSmall
|
||||
?.copyWith(
|
||||
color: Colors.orange,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
@@ -979,12 +1077,20 @@ class _MessageBubble extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
Color _getMessageBubbleColor(BuildContext context, bool isOwnMessage, bool isDarkMode) {
|
||||
Color _getMessageBubbleColor(
|
||||
BuildContext context,
|
||||
bool isOwnMessage,
|
||||
bool isDarkMode,
|
||||
) {
|
||||
if (isOwnMessage) {
|
||||
// Own messages: slightly highlighted with primary color tint
|
||||
return isDarkMode
|
||||
? Theme.of(context).colorScheme.primaryContainer.withValues(alpha: 0.3)
|
||||
: Theme.of(context).colorScheme.primaryContainer.withValues(alpha: 0.15);
|
||||
? Theme.of(
|
||||
context,
|
||||
).colorScheme.primaryContainer.withValues(alpha: 0.3)
|
||||
: Theme.of(
|
||||
context,
|
||||
).colorScheme.primaryContainer.withValues(alpha: 0.15);
|
||||
} else {
|
||||
// Others' messages: default surface color
|
||||
return Theme.of(context).colorScheme.surfaceVariant;
|
||||
@@ -1000,24 +1106,24 @@ class _MessageBubble extends StatelessWidget {
|
||||
switch (message.sarMarkerType!) {
|
||||
case SarMarkerType.foundPerson:
|
||||
return isDarkMode
|
||||
? const Color(0xFF1B5E20).withValues(alpha: 0.4) // Dark green
|
||||
: const Color(0xFFC8E6C9).withValues(alpha: 0.9); // Light green
|
||||
? const Color(0xFF1B5E20).withValues(alpha: 0.4) // Dark green
|
||||
: const Color(0xFFC8E6C9).withValues(alpha: 0.9); // Light green
|
||||
case SarMarkerType.fire:
|
||||
return isDarkMode
|
||||
? const Color(0xFFB71C1C).withValues(alpha: 0.4) // Dark red
|
||||
: const Color(0xFFFFCDD2).withValues(alpha: 0.9); // Light red
|
||||
? const Color(0xFFB71C1C).withValues(alpha: 0.4) // Dark red
|
||||
: const Color(0xFFFFCDD2).withValues(alpha: 0.9); // Light red
|
||||
case SarMarkerType.stagingArea:
|
||||
return isDarkMode
|
||||
? const Color(0xFF0D47A1).withValues(alpha: 0.4) // Dark blue
|
||||
: const Color(0xFFBBDEFB).withValues(alpha: 0.9); // Light blue
|
||||
? const Color(0xFF0D47A1).withValues(alpha: 0.4) // Dark blue
|
||||
: const Color(0xFFBBDEFB).withValues(alpha: 0.9); // Light blue
|
||||
case SarMarkerType.object:
|
||||
return isDarkMode
|
||||
? const Color(0xFF4A148C).withValues(alpha: 0.4) // Dark purple
|
||||
: const Color(0xFFE1BEE7).withValues(alpha: 0.9); // Light purple
|
||||
? const Color(0xFF4A148C).withValues(alpha: 0.4) // Dark purple
|
||||
: const Color(0xFFE1BEE7).withValues(alpha: 0.9); // Light purple
|
||||
case SarMarkerType.unknown:
|
||||
return isDarkMode
|
||||
? const Color(0xFF424242).withValues(alpha: 0.4) // Dark gray
|
||||
: const Color(0xFFEEEEEE).withValues(alpha: 0.9); // Light gray
|
||||
? const Color(0xFF424242).withValues(alpha: 0.4) // Dark gray
|
||||
: const Color(0xFFEEEEEE).withValues(alpha: 0.9); // Light gray
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1029,15 +1135,15 @@ class _MessageBubble extends StatelessWidget {
|
||||
// Use vibrant type-specific colors for borders
|
||||
switch (message.sarMarkerType!) {
|
||||
case SarMarkerType.foundPerson:
|
||||
return const Color(0xFF4CAF50); // Green
|
||||
return const Color(0xFF4CAF50); // Green
|
||||
case SarMarkerType.fire:
|
||||
return const Color(0xFFF44336); // Red
|
||||
return const Color(0xFFF44336); // Red
|
||||
case SarMarkerType.stagingArea:
|
||||
return const Color(0xFF2196F3); // Blue
|
||||
return const Color(0xFF2196F3); // Blue
|
||||
case SarMarkerType.object:
|
||||
return const Color(0xFF9C27B0); // Purple
|
||||
return const Color(0xFF9C27B0); // Purple
|
||||
case SarMarkerType.unknown:
|
||||
return const Color(0xFF9E9E9E); // Gray
|
||||
return const Color(0xFF9E9E9E); // Gray
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1127,27 +1233,27 @@ class _SystemMessageBubble extends StatelessWidget {
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
_getLevelIcon(level),
|
||||
size: 14,
|
||||
color: levelColor,
|
||||
),
|
||||
Icon(_getLevelIcon(level), size: 14, color: levelColor),
|
||||
const SizedBox(width: 6),
|
||||
Text(
|
||||
message.timeAgo,
|
||||
style: Theme.of(context).textTheme.labelSmall?.copyWith(
|
||||
color: Theme.of(context).textTheme.bodySmall?.color?.withValues(alpha: 0.6),
|
||||
fontSize: 10,
|
||||
),
|
||||
color: Theme.of(
|
||||
context,
|
||||
).textTheme.bodySmall?.color?.withValues(alpha: 0.6),
|
||||
fontSize: 10,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
message.text,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
fontSize: 11,
|
||||
color: Theme.of(context).textTheme.bodySmall?.color?.withValues(alpha: 0.8),
|
||||
),
|
||||
fontSize: 11,
|
||||
color: Theme.of(
|
||||
context,
|
||||
).textTheme.bodySmall?.color?.withValues(alpha: 0.8),
|
||||
),
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
@@ -1157,4 +1263,3 @@ class _SystemMessageBubble extends StatelessWidget {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import '../meshcore_constants.dart';
|
||||
typedef OnConnectionStateCallback = void Function(bool isConnected);
|
||||
typedef OnErrorCallback = void Function(String error);
|
||||
typedef OnReconnectionAttemptCallback = void Function(int attemptNumber, int maxAttempts);
|
||||
typedef OnRssiUpdateCallback = void Function(int rssi);
|
||||
|
||||
/// Manages BLE connection lifecycle with automatic reconnection
|
||||
class BleConnectionManager {
|
||||
@@ -21,6 +22,10 @@ class BleConnectionManager {
|
||||
Timer? _reconnectionTimer;
|
||||
StreamSubscription<BluetoothConnectionState>? _connectionStateSubscription;
|
||||
|
||||
// RSSI monitoring
|
||||
Timer? _rssiTimer;
|
||||
int? _lastRssi;
|
||||
|
||||
// SAR-optimized reconnection: ~15 minutes total
|
||||
// Pattern: Fast retries first (for temporary issues), then slower retries (for extended disconnections)
|
||||
static const int _maxReconnectionAttempts = 30;
|
||||
@@ -38,6 +43,7 @@ class BleConnectionManager {
|
||||
OnConnectionStateCallback? onConnectionStateChanged;
|
||||
OnErrorCallback? onError;
|
||||
OnReconnectionAttemptCallback? onReconnectionAttempt;
|
||||
OnRssiUpdateCallback? onRssiUpdate;
|
||||
|
||||
// Getters
|
||||
bool get isConnected => _isConnected;
|
||||
@@ -49,7 +55,7 @@ class BleConnectionManager {
|
||||
BluetoothCharacteristic? get txCharacteristic => _txCharacteristic;
|
||||
|
||||
/// Scan for MeshCore devices
|
||||
Stream<BluetoothDevice> scanForDevices({Duration timeout = const Duration(seconds: 10)}) async* {
|
||||
Stream<ScanResult> scanForDevices({Duration timeout = const Duration(seconds: 10)}) async* {
|
||||
try {
|
||||
print('🔍 [BLE] Starting scan for MeshCore devices...');
|
||||
print(' Service UUID: ${MeshCoreConstants.bleServiceUuid}');
|
||||
@@ -73,7 +79,7 @@ class BleConnectionManager {
|
||||
.contains(Guid(MeshCoreConstants.bleServiceUuid))) {
|
||||
deviceCount++;
|
||||
print(' ✅ MeshCore device found! Total: $deviceCount');
|
||||
yield result.device;
|
||||
yield result;
|
||||
} else {
|
||||
print(' ❌ Not a MeshCore device (service UUID mismatch)');
|
||||
}
|
||||
@@ -170,6 +176,9 @@ class BleConnectionManager {
|
||||
// Monitor connection state for automatic reconnection
|
||||
_setupConnectionMonitoring();
|
||||
|
||||
// Start RSSI monitoring
|
||||
_startRssiMonitoring();
|
||||
|
||||
print('✅✅✅ [BLE] Connection completed successfully!');
|
||||
return true;
|
||||
} catch (e) {
|
||||
@@ -189,6 +198,7 @@ class BleConnectionManager {
|
||||
// Disable reconnection before disconnecting
|
||||
_reconnectionEnabled = false;
|
||||
_cancelReconnection();
|
||||
_stopRssiMonitoring();
|
||||
|
||||
await _device?.disconnect();
|
||||
_isConnected = false;
|
||||
@@ -317,10 +327,40 @@ class BleConnectionManager {
|
||||
_reconnectionEnabled = true;
|
||||
}
|
||||
|
||||
/// Start monitoring RSSI in the background
|
||||
void _startRssiMonitoring() {
|
||||
print('📡 [BLE] Starting RSSI monitoring (every 5 seconds)');
|
||||
_stopRssiMonitoring(); // Cancel any existing timer
|
||||
|
||||
_rssiTimer = Timer.periodic(const Duration(seconds: 5), (timer) async {
|
||||
if (_device != null && _isConnected) {
|
||||
try {
|
||||
final rssi = await _device!.readRssi();
|
||||
if (_lastRssi != rssi) {
|
||||
_lastRssi = rssi;
|
||||
print('📡 [BLE] RSSI updated: $rssi dBm');
|
||||
onRssiUpdate?.call(rssi);
|
||||
}
|
||||
} catch (e) {
|
||||
print('⚠️ [BLE] Failed to read RSSI: $e');
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Stop RSSI monitoring
|
||||
void _stopRssiMonitoring() {
|
||||
_rssiTimer?.cancel();
|
||||
_rssiTimer = null;
|
||||
_lastRssi = null;
|
||||
print('📡 [BLE] RSSI monitoring stopped');
|
||||
}
|
||||
|
||||
/// Dispose resources
|
||||
void dispose() {
|
||||
print('🔴 [BLE] Disposing BLE connection manager');
|
||||
_cancelReconnection();
|
||||
_stopRssiMonitoring();
|
||||
_device = null;
|
||||
_rxCharacteristic = null;
|
||||
_txCharacteristic = null;
|
||||
|
||||
@@ -31,6 +31,7 @@ typedef OnBatteryAndStorageCallback = void Function(int millivolts, int? usedKb,
|
||||
typedef OnErrorCallback = void Function(String error);
|
||||
typedef OnConnectionStateCallback = void Function(bool isConnected);
|
||||
typedef OnReconnectionAttemptCallback = void Function(int attemptNumber, int maxAttempts);
|
||||
typedef OnRssiUpdateCallback = void Function(int rssi);
|
||||
|
||||
/// MeshCore BLE Service - coordinates BLE communication components
|
||||
class MeshCoreBleService {
|
||||
@@ -42,6 +43,7 @@ class MeshCoreBleService {
|
||||
// Event callbacks
|
||||
OnConnectionStateCallback? onConnectionStateChanged;
|
||||
OnReconnectionAttemptCallback? onReconnectionAttempt;
|
||||
OnRssiUpdateCallback? onRssiUpdate;
|
||||
OnContactCallback? onContactReceived;
|
||||
OnContactsCompleteCallback? onContactsComplete;
|
||||
OnMessageCallback? onMessageReceived;
|
||||
@@ -83,6 +85,9 @@ class MeshCoreBleService {
|
||||
print('🔄 [Service] Reconnection attempt $attemptNumber/$maxAttempts');
|
||||
onReconnectionAttempt?.call(attemptNumber, maxAttempts);
|
||||
};
|
||||
_connectionManager.onRssiUpdate = (rssi) {
|
||||
onRssiUpdate?.call(rssi);
|
||||
};
|
||||
|
||||
// Command sender callbacks
|
||||
_commandSender.onError = (error) {
|
||||
@@ -167,7 +172,7 @@ class MeshCoreBleService {
|
||||
}
|
||||
|
||||
/// Scan for MeshCore devices
|
||||
Stream<BluetoothDevice> scanForDevices({Duration timeout = const Duration(seconds: 10)}) {
|
||||
Stream<ScanResult> scanForDevices({Duration timeout = const Duration(seconds: 10)}) {
|
||||
return _connectionManager.scanForDevices(timeout: timeout);
|
||||
}
|
||||
|
||||
|
||||
@@ -12,8 +12,9 @@ class DrawingMessageParser {
|
||||
}
|
||||
|
||||
/// Parse drawing message text into MapDrawing object
|
||||
/// senderName should be extracted from packet metadata
|
||||
/// Returns null if parsing fails
|
||||
static MapDrawing? parseDrawingMessage(String text) {
|
||||
static MapDrawing? parseDrawingMessage(String text, {String? senderName}) {
|
||||
if (!isDrawingMessage(text)) {
|
||||
return null;
|
||||
}
|
||||
@@ -25,17 +26,18 @@ class DrawingMessageParser {
|
||||
// Parse JSON
|
||||
final json = jsonDecode(jsonStr) as Map<String, dynamic>;
|
||||
|
||||
// Use compact network format parser
|
||||
return MapDrawing.fromNetworkJson(json);
|
||||
// Use ultra-compact network format parser
|
||||
// Sender name comes from packet metadata, not JSON
|
||||
return MapDrawing.fromNetworkJson(json, senderName: senderName);
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Create drawing message text from MapDrawing object
|
||||
/// Includes sender name in the message
|
||||
static String createDrawingMessage(MapDrawing drawing, String senderName) {
|
||||
final json = drawing.toNetworkJson(senderName);
|
||||
/// Sender will be determined from packet metadata on receiving end
|
||||
static String createDrawingMessage(MapDrawing drawing) {
|
||||
final json = drawing.toNetworkJson();
|
||||
final jsonStr = jsonEncode(json);
|
||||
return '$prefix$jsonStr';
|
||||
}
|
||||
|
||||
@@ -3,17 +3,17 @@ import '../models/sar_marker.dart';
|
||||
import '../models/message.dart';
|
||||
|
||||
/// Parser for SAR (Search & Rescue) special messages
|
||||
/// Format: S:<emoji>:<latitude>,<longitude>
|
||||
/// Format: S:<emoji>:<latitude>,<longitude>:<optional_message>
|
||||
/// Examples:
|
||||
/// S:🧑:37.7749,-122.4194
|
||||
/// S:🔥:40.7128,-74.0060
|
||||
/// S:🏕️:34.0522,-118.2437
|
||||
/// S:🔥:40.7128,-74.0060:Large wildfire spreading
|
||||
/// S:🏕️:34.0522,-118.2437:Base camp established
|
||||
class SarMessageParser {
|
||||
// Updated regex to allow optional notes after coordinates
|
||||
// Captures: emoji (one or more non-colon chars), latitude, longitude
|
||||
// Updated regex to capture optional message after coordinates
|
||||
// Captures: emoji (one or more non-colon chars), latitude, longitude, optional message
|
||||
// Note: Emojis are multi-byte characters, so we use [^:]+ instead of .
|
||||
static final RegExp _sarPattern = RegExp(
|
||||
r'^S:([^:]+):(-?\d+\.?\d*),(-?\d+\.?\d*)',
|
||||
r'^S:([^:]+):(-?\d+\.?\d*),(-?\d+\.?\d*):?(.*)',
|
||||
multiLine: false,
|
||||
);
|
||||
|
||||
@@ -39,6 +39,7 @@ class SarMessageParser {
|
||||
final emoji = match.group(1)!;
|
||||
final latitude = double.parse(match.group(2)!);
|
||||
final longitude = double.parse(match.group(3)!);
|
||||
final inlineMessage = match.group(4)?.trim(); // Optional message after colon
|
||||
|
||||
// Validate coordinates
|
||||
if (latitude < -90 || latitude > 90) return null;
|
||||
@@ -47,14 +48,13 @@ class SarMessageParser {
|
||||
final markerType = SarMarkerType.fromEmoji(emoji);
|
||||
final location = LatLng(latitude, longitude);
|
||||
|
||||
// Extract notes if present (everything after coordinates on first line, or subsequent lines)
|
||||
// Combine inline message with multi-line notes
|
||||
String? notes;
|
||||
final coordsEnd = match.end;
|
||||
if (coordsEnd < firstLine.length) {
|
||||
// Notes on same line after coordinates
|
||||
notes = firstLine.substring(coordsEnd).trim();
|
||||
if (inlineMessage != null && inlineMessage.isNotEmpty) {
|
||||
notes = inlineMessage;
|
||||
}
|
||||
// Check for multi-line notes
|
||||
|
||||
// Check for multi-line notes (lines after the first line)
|
||||
final additionalNotes = extractNotes(text);
|
||||
if (additionalNotes != null) {
|
||||
notes = notes != null ? '$notes\n$additionalNotes' : additionalNotes;
|
||||
@@ -80,6 +80,7 @@ class SarMessageParser {
|
||||
isSarMarker: true,
|
||||
sarMarkerType: sarInfo.type,
|
||||
sarGpsCoordinates: sarInfo.location,
|
||||
sarNotes: sarInfo.notes, // Extract and store notes
|
||||
);
|
||||
}
|
||||
|
||||
@@ -91,7 +92,8 @@ class SarMessageParser {
|
||||
}) {
|
||||
final text = 'S:${type.emoji}:${location.latitude},${location.longitude}';
|
||||
if (notes != null && notes.isNotEmpty) {
|
||||
return '$text\n$notes';
|
||||
// Use colon-separated format for inline message
|
||||
return '$text:$notes';
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
@@ -453,10 +453,8 @@ class DrawingToolbar extends StatelessWidget {
|
||||
for (final drawing in drawings) {
|
||||
try {
|
||||
debugPrint(' Creating message for drawing ${drawing.id}...');
|
||||
final message = drawingProvider.createDrawingBroadcastMessage(
|
||||
drawing,
|
||||
senderName,
|
||||
);
|
||||
// Sender name is no longer included in JSON - will be extracted from packet metadata
|
||||
final message = drawingProvider.createDrawingBroadcastMessage(drawing);
|
||||
debugPrint(' Message created (${message.length} chars): ${message.substring(0, message.length > 100 ? 100 : message.length)}...');
|
||||
debugPrint(' Sending to channel 0...');
|
||||
await connectionProvider.sendChannelMessage(
|
||||
@@ -525,10 +523,8 @@ class DrawingToolbar extends StatelessWidget {
|
||||
for (final drawing in drawings) {
|
||||
try {
|
||||
debugPrint(' Creating message for drawing ${drawing.id}...');
|
||||
final message = drawingProvider.createDrawingBroadcastMessage(
|
||||
drawing,
|
||||
senderName,
|
||||
);
|
||||
// Sender name is no longer included in JSON - will be extracted from packet metadata
|
||||
final message = drawingProvider.createDrawingBroadcastMessage(drawing);
|
||||
debugPrint(' Message created (${message.length} chars): ${message.substring(0, message.length > 100 ? 100 : message.length)}...');
|
||||
debugPrint(' Sending to room ${room.advName}...');
|
||||
await connectionProvider.sendTextMessage(
|
||||
|
||||
Reference in New Issue
Block a user