mirror of
https://github.com/dz0ny/meshcore-sar.git
synced 2026-08-12 00:40:28 +00:00
Implement meshcore-open route reload
This commit is contained in:
15
lib/services/developer_mode_service.dart
Normal file
15
lib/services/developer_mode_service.dart
Normal file
@@ -0,0 +1,15 @@
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
class DeveloperModeService {
|
||||
static const String _developerModeKey = 'developer_mode_enabled';
|
||||
|
||||
static Future<bool> isEnabled() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
return prefs.getBool(_developerModeKey) ?? false;
|
||||
}
|
||||
|
||||
static Future<void> setEnabled(bool enabled) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setBool(_developerModeKey, enabled);
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import '../models/message.dart';
|
||||
import '../models/message_contact_location.dart';
|
||||
import '../models/message_reception_details.dart';
|
||||
import '../models/message_transfer_details.dart';
|
||||
import '../models/message_route_metadata.dart';
|
||||
import 'package:latlong2/latlong.dart';
|
||||
|
||||
/// Service for persisting messages to local storage
|
||||
@@ -16,6 +17,8 @@ class MessageStorageService {
|
||||
'stored_message_reception_details';
|
||||
static const String _messageTransferDetailsKey =
|
||||
'stored_message_transfer_details';
|
||||
static const String _messageRouteMetadataKey =
|
||||
'stored_message_route_metadata';
|
||||
static const int _maxStoredMessages = 1000; // Store up to 1000 messages
|
||||
|
||||
/// Save messages to persistent storage
|
||||
@@ -24,6 +27,7 @@ class MessageStorageService {
|
||||
Map<String, MessageContactLocation> messageContactLocations = const {},
|
||||
Map<String, MessageReceptionDetails> messageReceptionDetails = const {},
|
||||
Map<String, MessageTransferDetails> messageTransferDetails = const {},
|
||||
Map<String, MessageRouteMetadata> messageRouteMetadata = const {},
|
||||
}) async {
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
@@ -44,6 +48,7 @@ class MessageStorageService {
|
||||
final locationJson = <String, dynamic>{};
|
||||
final receptionJson = <String, dynamic>{};
|
||||
final transferJson = <String, dynamic>{};
|
||||
final routeMetadataJson = <String, dynamic>{};
|
||||
for (final entry in messageContactLocations.entries) {
|
||||
if (retainedMessageIds.contains(entry.key)) {
|
||||
locationJson[entry.key] = entry.value.toJson();
|
||||
@@ -59,6 +64,11 @@ class MessageStorageService {
|
||||
transferJson[entry.key] = entry.value.toJson();
|
||||
}
|
||||
}
|
||||
for (final entry in messageRouteMetadata.entries) {
|
||||
if (retainedMessageIds.contains(entry.key)) {
|
||||
routeMetadataJson[entry.key] = entry.value.toJson();
|
||||
}
|
||||
}
|
||||
await prefs.setString(
|
||||
_messageContactLocationsKey,
|
||||
jsonEncode(locationJson),
|
||||
@@ -71,6 +81,10 @@ class MessageStorageService {
|
||||
_messageTransferDetailsKey,
|
||||
jsonEncode(transferJson),
|
||||
);
|
||||
await prefs.setString(
|
||||
_messageRouteMetadataKey,
|
||||
jsonEncode(routeMetadataJson),
|
||||
);
|
||||
|
||||
debugPrint(
|
||||
'✅ [MessageStorage] Saved ${limitedList.length} messages to storage',
|
||||
@@ -170,6 +184,32 @@ class MessageStorageService {
|
||||
}
|
||||
}
|
||||
|
||||
Future<Map<String, MessageRouteMetadata>> loadMessageRouteMetadata() async {
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final jsonString = prefs.getString(_messageRouteMetadataKey);
|
||||
if (jsonString == null || jsonString.isEmpty) {
|
||||
return const {};
|
||||
}
|
||||
|
||||
final decoded = jsonDecode(jsonString);
|
||||
if (decoded is! Map<String, dynamic>) {
|
||||
return const {};
|
||||
}
|
||||
|
||||
final result = <String, MessageRouteMetadata>{};
|
||||
for (final entry in decoded.entries) {
|
||||
final value = entry.value;
|
||||
if (value is! Map<String, dynamic>) continue;
|
||||
result[entry.key] = MessageRouteMetadata.fromJson(value);
|
||||
}
|
||||
return result;
|
||||
} catch (e) {
|
||||
debugPrint('❌ [MessageStorage] Error loading route metadata: $e');
|
||||
return const {};
|
||||
}
|
||||
}
|
||||
|
||||
/// Load messages from persistent storage
|
||||
Future<List<Message>> loadMessages() async {
|
||||
try {
|
||||
@@ -206,6 +246,7 @@ class MessageStorageService {
|
||||
await prefs.remove(_messageContactLocationsKey);
|
||||
await prefs.remove(_messageReceptionDetailsKey);
|
||||
await prefs.remove(_messageTransferDetailsKey);
|
||||
await prefs.remove(_messageRouteMetadataKey);
|
||||
debugPrint('✅ [MessageStorage] Cleared all stored messages');
|
||||
} catch (e) {
|
||||
debugPrint('❌ [MessageStorage] Error clearing messages: $e');
|
||||
|
||||
32
lib/services/messaging_route_preferences.dart
Normal file
32
lib/services/messaging_route_preferences.dart
Normal file
@@ -0,0 +1,32 @@
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
class MessagingRoutePreferences {
|
||||
static const bool defaultAutoRouteRotationEnabled = false;
|
||||
static const bool defaultClearPathOnMaxRetry = false;
|
||||
|
||||
static const String _autoRouteRotationKey =
|
||||
'messaging_auto_route_rotation_enabled';
|
||||
static const String _clearPathOnMaxRetryKey =
|
||||
'messaging_clear_path_on_max_retry';
|
||||
|
||||
static Future<bool> getAutoRouteRotationEnabled() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
return prefs.getBool(_autoRouteRotationKey) ??
|
||||
defaultAutoRouteRotationEnabled;
|
||||
}
|
||||
|
||||
static Future<void> setAutoRouteRotationEnabled(bool enabled) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setBool(_autoRouteRotationKey, enabled);
|
||||
}
|
||||
|
||||
static Future<bool> getClearPathOnMaxRetry() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
return prefs.getBool(_clearPathOnMaxRetryKey) ?? defaultClearPathOnMaxRetry;
|
||||
}
|
||||
|
||||
static Future<void> setClearPathOnMaxRetry(bool enabled) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setBool(_clearPathOnMaxRetryKey, enabled);
|
||||
}
|
||||
}
|
||||
69
lib/services/nearest_router_selector.dart
Normal file
69
lib/services/nearest_router_selector.dart
Normal file
@@ -0,0 +1,69 @@
|
||||
import 'package:geolocator/geolocator.dart';
|
||||
|
||||
import '../models/contact.dart';
|
||||
|
||||
class NearestRouterSelector {
|
||||
const NearestRouterSelector();
|
||||
|
||||
Contact? select({
|
||||
required Position? senderPosition,
|
||||
required List<Contact> repeaters,
|
||||
required Contact recipient,
|
||||
}) {
|
||||
if (senderPosition == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
final eligible = repeaters.where((contact) {
|
||||
if (contact.publicKeyHex == recipient.publicKeyHex) {
|
||||
return false;
|
||||
}
|
||||
if (!contact.isRecentlySeen) {
|
||||
return false;
|
||||
}
|
||||
return contact.displayLocation != null;
|
||||
}).toList();
|
||||
if (eligible.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
|
||||
eligible.sort((a, b) {
|
||||
final locationA = a.displayLocation!;
|
||||
final locationB = b.displayLocation!;
|
||||
final distanceA = Geolocator.distanceBetween(
|
||||
senderPosition.latitude,
|
||||
senderPosition.longitude,
|
||||
locationA.latitude,
|
||||
locationA.longitude,
|
||||
);
|
||||
final distanceB = Geolocator.distanceBetween(
|
||||
senderPosition.latitude,
|
||||
senderPosition.longitude,
|
||||
locationB.latitude,
|
||||
locationB.longitude,
|
||||
);
|
||||
final distanceCompare = distanceA.compareTo(distanceB);
|
||||
if (distanceCompare != 0) {
|
||||
return distanceCompare;
|
||||
}
|
||||
|
||||
final advertCompare = b.lastAdvert.compareTo(a.lastAdvert);
|
||||
if (advertCompare != 0) {
|
||||
return advertCompare;
|
||||
}
|
||||
|
||||
final hopCompare = a.routeHopCount.compareTo(b.routeHopCount);
|
||||
if (hopCompare != 0) {
|
||||
return hopCompare;
|
||||
}
|
||||
|
||||
final nameCompare = a.advName.compareTo(b.advName);
|
||||
if (nameCompare != 0) {
|
||||
return nameCompare;
|
||||
}
|
||||
return a.publicKeyHex.compareTo(b.publicKeyHex);
|
||||
});
|
||||
|
||||
return eligible.first;
|
||||
}
|
||||
}
|
||||
233
lib/services/path_history_service.dart
Normal file
233
lib/services/path_history_service.dart
Normal file
@@ -0,0 +1,233 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../models/contact.dart';
|
||||
import '../models/path_history.dart';
|
||||
import '../models/path_selection.dart';
|
||||
|
||||
class PathHistoryService {
|
||||
static const String _storageKey = 'contact_path_history_v1';
|
||||
static const int _maxDirectPaths = 20;
|
||||
static const int _topRotationCount = 3;
|
||||
|
||||
final Map<String, ContactPathHistory> _cache = {};
|
||||
bool _isLoaded = false;
|
||||
|
||||
Future<void> initialize() async {
|
||||
if (_isLoaded) return;
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final raw = prefs.getString(_storageKey);
|
||||
if (raw == null || raw.isEmpty) {
|
||||
_isLoaded = true;
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
final decoded = jsonDecode(raw);
|
||||
if (decoded is Map<String, dynamic>) {
|
||||
for (final entry in decoded.entries) {
|
||||
final value = entry.value;
|
||||
if (value is Map<String, dynamic>) {
|
||||
_cache[entry.key] = ContactPathHistory.fromJson(entry.key, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
debugPrint('⚠️ [PathHistoryService] Failed to load history: $error');
|
||||
}
|
||||
_isLoaded = true;
|
||||
}
|
||||
|
||||
Future<void> recordLearnedPath(Contact contact) async {
|
||||
await initialize();
|
||||
if (!contact.routeHasPath || contact.routeHopCount <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
final history = _historyFor(contact.publicKeyHex);
|
||||
final signature = _signature(contact.routePathBytes);
|
||||
final existing = _findDirectPath(history.directPaths, signature);
|
||||
final updated = PathRecord(
|
||||
pathBytes: contact.routePathBytes.toList(),
|
||||
hopCount: contact.routeHopCount,
|
||||
hashSize: contact.routeHashSize,
|
||||
successCount: existing?.successCount ?? 0,
|
||||
failureCount: existing?.failureCount ?? 0,
|
||||
lastRoundTripTimeMs: existing?.lastRoundTripTimeMs ?? 0,
|
||||
lastUsedAt: DateTime.now(),
|
||||
);
|
||||
|
||||
await _saveHistory(
|
||||
contact.publicKeyHex,
|
||||
history.copyWith(
|
||||
directPaths: _upsertDirectPath(history.directPaths, updated),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<PathSelection> getSelectionForContact(
|
||||
Contact contact, {
|
||||
required bool autoRouteRotationEnabled,
|
||||
}) async {
|
||||
await initialize();
|
||||
await recordLearnedPath(contact);
|
||||
|
||||
if (!autoRouteRotationEnabled) {
|
||||
if (contact.routeHasPath && contact.routeHopCount > 0) {
|
||||
return PathSelection(
|
||||
mode: PathSelectionMode.directCurrent,
|
||||
pathBytes: Uint8List.fromList(contact.routePathBytes),
|
||||
hopCount: contact.routeHopCount,
|
||||
hashSize: contact.routeHashSize,
|
||||
);
|
||||
}
|
||||
return PathSelection.flood();
|
||||
}
|
||||
|
||||
final history = _historyFor(contact.publicKeyHex);
|
||||
final ranked = List<PathRecord>.from(history.directPaths)
|
||||
..sort(_comparePathRecords);
|
||||
final topPaths = ranked.take(_topRotationCount).toList();
|
||||
if (topPaths.isEmpty) {
|
||||
final nextFloodHistory = history.copyWith(
|
||||
rotationIndex: history.rotationIndex + 1,
|
||||
);
|
||||
await _saveHistory(contact.publicKeyHex, nextFloodHistory);
|
||||
return PathSelection.flood();
|
||||
}
|
||||
|
||||
final selections =
|
||||
topPaths
|
||||
.map(
|
||||
(record) => PathSelection(
|
||||
mode: PathSelectionMode.directHistorical,
|
||||
pathBytes: Uint8List.fromList(record.pathBytes),
|
||||
hopCount: record.hopCount,
|
||||
hashSize: record.hashSize,
|
||||
),
|
||||
)
|
||||
.toList()
|
||||
..add(PathSelection.flood());
|
||||
|
||||
final index = history.rotationIndex % selections.length;
|
||||
final updatedHistory = history.copyWith(
|
||||
rotationIndex: history.rotationIndex + 1,
|
||||
);
|
||||
await _saveHistory(contact.publicKeyHex, updatedHistory);
|
||||
return selections[index];
|
||||
}
|
||||
|
||||
Future<void> recordPathResult(
|
||||
String contactPublicKeyHex,
|
||||
PathSelection selection, {
|
||||
required bool success,
|
||||
int? roundTripTimeMs,
|
||||
}) async {
|
||||
await initialize();
|
||||
final history = _historyFor(contactPublicKeyHex);
|
||||
if (selection.usesFlood) {
|
||||
final current = history.floodStats;
|
||||
await _saveHistory(
|
||||
contactPublicKeyHex,
|
||||
history.copyWith(
|
||||
floodStats: current.copyWith(
|
||||
successCount: current.successCount + (success ? 1 : 0),
|
||||
failureCount: current.failureCount + (success ? 0 : 1),
|
||||
lastRoundTripTimeMs: success
|
||||
? (roundTripTimeMs ?? current.lastRoundTripTimeMs)
|
||||
: current.lastRoundTripTimeMs,
|
||||
lastUsedAt: DateTime.now(),
|
||||
),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
final signature = _signature(selection.pathBytes);
|
||||
final existing = _findDirectPath(history.directPaths, signature);
|
||||
final updated = PathRecord(
|
||||
pathBytes: selection.pathBytes.toList(),
|
||||
hopCount: selection.hopCount,
|
||||
hashSize: selection.hashSize,
|
||||
successCount: (existing?.successCount ?? 0) + (success ? 1 : 0),
|
||||
failureCount: (existing?.failureCount ?? 0) + (success ? 0 : 1),
|
||||
lastRoundTripTimeMs: success
|
||||
? (roundTripTimeMs ?? existing?.lastRoundTripTimeMs ?? 0)
|
||||
: (existing?.lastRoundTripTimeMs ?? 0),
|
||||
lastUsedAt: DateTime.now(),
|
||||
);
|
||||
await _saveHistory(
|
||||
contactPublicKeyHex,
|
||||
history.copyWith(
|
||||
directPaths: _upsertDirectPath(history.directPaths, updated),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
ContactPathHistory historyFor(String contactPublicKeyHex) {
|
||||
return _cache[contactPublicKeyHex] ??
|
||||
ContactPathHistory.empty(contactPublicKeyHex);
|
||||
}
|
||||
|
||||
ContactPathHistory _historyFor(String contactPublicKeyHex) {
|
||||
return _cache.putIfAbsent(
|
||||
contactPublicKeyHex,
|
||||
() => ContactPathHistory.empty(contactPublicKeyHex),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _saveHistory(
|
||||
String contactPublicKeyHex,
|
||||
ContactPathHistory history,
|
||||
) async {
|
||||
_cache[contactPublicKeyHex] = history;
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final payload = <String, dynamic>{};
|
||||
for (final entry in _cache.entries) {
|
||||
payload[entry.key] = entry.value.toJson();
|
||||
}
|
||||
await prefs.setString(_storageKey, jsonEncode(payload));
|
||||
}
|
||||
|
||||
List<PathRecord> _upsertDirectPath(
|
||||
List<PathRecord> existing,
|
||||
PathRecord updatedRecord,
|
||||
) {
|
||||
final updated = List<PathRecord>.from(existing)
|
||||
..removeWhere((record) => record.signature == updatedRecord.signature)
|
||||
..insert(0, updatedRecord);
|
||||
if (updated.length > _maxDirectPaths) {
|
||||
return updated.take(_maxDirectPaths).toList();
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
int _comparePathRecords(PathRecord a, PathRecord b) {
|
||||
final successRateCompare = b.successRate.compareTo(a.successRate);
|
||||
if (successRateCompare != 0) return successRateCompare;
|
||||
|
||||
final successCountCompare = b.successCount.compareTo(a.successCount);
|
||||
if (successCountCompare != 0) return successCountCompare;
|
||||
|
||||
final aRtt = a.lastRoundTripTimeMs == 0 ? 1 << 30 : a.lastRoundTripTimeMs;
|
||||
final bRtt = b.lastRoundTripTimeMs == 0 ? 1 << 30 : b.lastRoundTripTimeMs;
|
||||
final rttCompare = aRtt.compareTo(bRtt);
|
||||
if (rttCompare != 0) return rttCompare;
|
||||
|
||||
return b.lastUsedAt.compareTo(a.lastUsedAt);
|
||||
}
|
||||
|
||||
PathRecord? _findDirectPath(List<PathRecord> records, String signature) {
|
||||
for (final record in records) {
|
||||
if (record.signature == signature) {
|
||||
return record;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
String _signature(Uint8List bytes) =>
|
||||
bytes.map((byte) => byte.toRadixString(16).padLeft(2, '0')).join();
|
||||
}
|
||||
Reference in New Issue
Block a user