Merge remote-tracking branch 'upstream/dev' into battery_percent_warning_android
This commit is contained in:
commit
7d55bf03df
231 files changed
+45362
-9064
No files matched your search
@@ -113,6 +113,10 @@ class AppSettingsService extends ChangeNotifier {
|
||||
await updateSettings(_settings.copyWith(enableMessageTracing: value));
|
||||
}
|
||||
|
||||
Future<void> setRegionOnHopsLine(bool value) async {
|
||||
await updateSettings(_settings.copyWith(regionOnHopsLine: value));
|
||||
}
|
||||
|
||||
Future<void> setMapCacheBounds(Map<String, double>? value) async {
|
||||
await updateSettings(_settings.copyWith(mapCacheBounds: value));
|
||||
}
|
||||
@@ -222,6 +226,12 @@ class AppSettingsService extends ChangeNotifier {
|
||||
await updateSettings(_settings.copyWith(channelMinHopsRetries: value));
|
||||
}
|
||||
|
||||
Future<void> setChannelMinHopsCountRepeaters(bool value) async {
|
||||
await updateSettings(
|
||||
_settings.copyWith(channelMinHopsCountRepeaters: value),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> setThemeMode(String value) async {
|
||||
await updateSettings(_settings.copyWith(themeMode: value));
|
||||
}
|
||||
@@ -240,6 +250,12 @@ class AppSettingsService extends ChangeNotifier {
|
||||
await updateSettings(_settings.copyWith(mapShowDiscoveryContacts: value));
|
||||
}
|
||||
|
||||
Future<void> setEvictDiscoveredContactsEnabled(bool value) async {
|
||||
await updateSettings(
|
||||
_settings.copyWith(evictDiscoveredContactsEnabled: value),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> setBatteryChemistryForDevice(
|
||||
String deviceId,
|
||||
String chemistry,
|
||||
@@ -301,6 +317,14 @@ class AppSettingsService extends ChangeNotifier {
|
||||
await updateSettings(_settings.copyWith(imageMessagesEnabled: value));
|
||||
}
|
||||
|
||||
Future<void> setNetworkMapUploadEnabled(bool value) async {
|
||||
await updateSettings(_settings.copyWith(networkMapUploadEnabled: value));
|
||||
}
|
||||
|
||||
Future<void> setNetworkMapPromptShown(bool value) async {
|
||||
await updateSettings(_settings.copyWith(networkMapPromptShown: value));
|
||||
}
|
||||
|
||||
/// See [AppSettings.imageProcessAutomatically]. `main.dart` mirrors this into
|
||||
/// `ReceivedImageStore.processAutomatically` on every settings change; the
|
||||
/// store applies it to future arrivals only, so flipping it does not
|
||||
|
||||
@@ -633,6 +633,10 @@ enum ImageReassemblyFailureReason {
|
||||
|
||||
/// Dropped by [ImageReassembler.clear] (disconnect / new session).
|
||||
disconnected,
|
||||
|
||||
/// Dropped by [ImageReassembler.clearChannel] because the radio slot it
|
||||
/// arrived on now holds a different channel.
|
||||
channelChanged,
|
||||
}
|
||||
|
||||
/// A fully reassembled image.
|
||||
@@ -878,6 +882,34 @@ class ImageReassembler {
|
||||
}
|
||||
}
|
||||
|
||||
/// Drops every stream that arrived on [channelIndex], whose radio slot now
|
||||
/// holds a different channel, so a new image there can never be completed
|
||||
/// with the old channel's bytes. In-progress streams are reported through
|
||||
/// [onFailed] so their bubbles stop showing "receiving".
|
||||
void clearChannel(int channelIndex, {DateTime? now}) {
|
||||
final at = now ?? _clock();
|
||||
_recentlyCompleted.removeWhere(
|
||||
(key, _) => key.channelIndex == channelIndex,
|
||||
);
|
||||
final dropped = _pending.values
|
||||
.where((entry) => entry.key.channelIndex == channelIndex)
|
||||
.toList();
|
||||
for (final entry in dropped) {
|
||||
_pending.remove(entry.key);
|
||||
onFailed?.call(
|
||||
ImageReassemblyFailure(
|
||||
key: entry.key,
|
||||
total: entry.total,
|
||||
receivedDataChunks: entry.bodies.length,
|
||||
hadParity: entry.hasParity,
|
||||
firstSeen: entry.firstSeen,
|
||||
expiredAt: at,
|
||||
reason: ImageReassemblyFailureReason.channelChanged,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Feeds one received GRP_DATA blob.
|
||||
///
|
||||
/// [now] overrides the clock for tests. Expired entries are swept first, so
|
||||
@@ -1117,10 +1149,15 @@ class ImageReassembler {
|
||||
|
||||
_FinishOutcome? _assemble(_PendingImage entry, {required bool recovered}) {
|
||||
final first = entry.bodies[0];
|
||||
// Chunk 0 must hold the metadata byte; anything shorter cannot
|
||||
// be a chunk 0 from this framing, so keep waiting rather than guessing.
|
||||
if (first == null || first.length < kImageChunkZeroMetadataBytes) {
|
||||
return null;
|
||||
if (first == null) return null;
|
||||
// Chunk 0 must hold the metadata byte; anything shorter cannot be a chunk
|
||||
// 0 from this framing. Every chunk is already here, so waiting would only
|
||||
// leave the stream on "receiving" until the TTL reports it as incomplete.
|
||||
if (first.length < kImageChunkZeroMetadataBytes) {
|
||||
return const _FinishOutcome.failed(
|
||||
ImageChunkStatus.unsupportedFormat,
|
||||
ImageReassemblyFailureReason.unsupportedFormat,
|
||||
);
|
||||
}
|
||||
final metadata = ImageStreamMetadata.decode(first[0]);
|
||||
final out = BytesBuilder();
|
||||
|
||||
@@ -487,6 +487,9 @@ class OnnxImageCodecBackend implements ImageCodecBackend {
|
||||
bool Function()? shouldCancel,
|
||||
}) async {
|
||||
_checkRatePoint(ratePoint);
|
||||
// A previous decode leaves the 2.16 GiB synthesis session resident; the
|
||||
// entropy graph must never be created on top of it.
|
||||
await releaseDecoderSession();
|
||||
final codec = await _ensureEntropy(resolution, forDecode: false);
|
||||
try {
|
||||
// The entropy session stays up on purpose: a second photo is free.
|
||||
@@ -509,6 +512,9 @@ class OnnxImageCodecBackend implements ImageCodecBackend {
|
||||
bool Function()? shouldCancel,
|
||||
}) async {
|
||||
_checkRatePoint(ratePoint);
|
||||
// Same rule in the other direction: the previous decode's synthesis
|
||||
// session is still up, and the entropy graph is about to load.
|
||||
await releaseDecoderSession();
|
||||
final codec = await _ensureEntropy(resolution, forDecode: true);
|
||||
final Float32List yHat;
|
||||
try {
|
||||
|
||||
@@ -99,7 +99,11 @@ class ImageCodecFileStore {
|
||||
}) async {
|
||||
final directoryPath = await modelDirectoryPath();
|
||||
final file = File('$directoryPath/$fileName');
|
||||
final sink = file.openWrite();
|
||||
// Written under a hidden temp name and renamed into place, so a kill
|
||||
// mid-write never leaves a truncated file under the real name, which the
|
||||
// startup scan would register as an installed model.
|
||||
final temp = File(_tempPathFor(directoryPath, fileName));
|
||||
final sink = temp.openWrite();
|
||||
var fileSizeBytes = 0;
|
||||
var completed = false;
|
||||
try {
|
||||
@@ -110,16 +114,22 @@ class ImageCodecFileStore {
|
||||
completed = true;
|
||||
} finally {
|
||||
await sink.close();
|
||||
if (!completed && file.existsSync()) {
|
||||
await file.delete();
|
||||
if (!completed && temp.existsSync()) {
|
||||
await temp.delete();
|
||||
}
|
||||
}
|
||||
await temp.rename(file.path);
|
||||
return DownloadedCodecFile(
|
||||
localPath: file.path,
|
||||
fileSizeBytes: fileSizeBytes,
|
||||
);
|
||||
}
|
||||
|
||||
/// Hidden (leading dot), so [scanDownloadedModels] never lists it and sweeps
|
||||
/// it as junk if a kill leaves it behind.
|
||||
static String _tempPathFor(String directoryPath, String fileName) =>
|
||||
'$directoryPath/.$fileName.part';
|
||||
|
||||
Future<String> chunkFilePath(String fileName, int index) async {
|
||||
final dir = await modelDirectoryPath();
|
||||
return '$dir/.${fileName}_chunk_$index';
|
||||
@@ -195,7 +205,11 @@ class ImageCodecFileStore {
|
||||
}) async {
|
||||
final dir = await modelDirectoryPath();
|
||||
final finalPath = '$dir/$fileName';
|
||||
final sink = File(finalPath).openWrite();
|
||||
// Merged into a hidden temp file first, for the same reason as
|
||||
// [writeModelBytes]: a kill mid-merge must not leave a truncated file
|
||||
// under the real name.
|
||||
final tempPath = _tempPathFor(dir, fileName);
|
||||
final sink = File(tempPath).openWrite();
|
||||
var totalSize = 0;
|
||||
var completed = false;
|
||||
try {
|
||||
@@ -208,6 +222,7 @@ class ImageCodecFileStore {
|
||||
} finally {
|
||||
await sink.close();
|
||||
if (completed) {
|
||||
await File(tempPath).rename(finalPath);
|
||||
for (final chunkPath in chunkPaths) {
|
||||
final file = File(chunkPath);
|
||||
if (file.existsSync()) {
|
||||
@@ -219,9 +234,9 @@ class ImageCodecFileStore {
|
||||
// merge target is thrown away. (The previous version deleted the chunks
|
||||
// unconditionally, which is why an interrupted 872 MB download restarted
|
||||
// from zero.)
|
||||
final finalFile = File(finalPath);
|
||||
if (finalFile.existsSync()) {
|
||||
await finalFile.delete();
|
||||
final tempFile = File(tempPath);
|
||||
if (tempFile.existsSync()) {
|
||||
await tempFile.delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -413,17 +413,26 @@ class ImageCodecService extends ChangeNotifier implements ImageSendCodec {
|
||||
for (final asset in spec.assets) asset.fileName,
|
||||
};
|
||||
|
||||
// A file only counts when its size matches the registry: one cut short by
|
||||
// a kill mid-write must not register the bundle as installed, or every
|
||||
// decode fails and reads as "corrupt". Only enforced where a digest pins
|
||||
// the file, since the size is otherwise advisory.
|
||||
bool intact(ImageCodecModelAsset asset) {
|
||||
final file = onDisk[asset.fileName];
|
||||
if (file == null) return false;
|
||||
if (!asset.hasChecksum || asset.sizeBytes <= 0) return true;
|
||||
return file.fileSizeBytes == asset.sizeBytes;
|
||||
}
|
||||
|
||||
for (final spec in imageCodecPresetModels) {
|
||||
final graphFile = onDisk[spec.fileName];
|
||||
if (graphFile == null) continue;
|
||||
final present = [
|
||||
for (final asset in spec.assets)
|
||||
if (onDisk.containsKey(asset.fileName)) asset.fileName,
|
||||
if (intact(asset)) asset.fileName,
|
||||
];
|
||||
final existing = existingByPath[graphFile.localPath];
|
||||
final complete = spec.assets.every(
|
||||
(asset) => onDisk.containsKey(asset.fileName),
|
||||
);
|
||||
final complete = spec.assets.every(intact);
|
||||
merged.add(
|
||||
ImageCodecModelRecord(
|
||||
id: spec.id,
|
||||
@@ -437,8 +446,7 @@ class ImageCodecService extends ChangeNotifier implements ImageSendCodec {
|
||||
assetFileNames: present,
|
||||
assetRoles: {
|
||||
for (final asset in spec.assets)
|
||||
if (onDisk.containsKey(asset.fileName))
|
||||
asset.fileName: asset.role,
|
||||
if (intact(asset)) asset.fileName: asset.role,
|
||||
},
|
||||
bundleVersion: complete ? kImageCodecBundleVersion : 0,
|
||||
),
|
||||
@@ -1360,8 +1368,14 @@ class ImageCodecService extends ChangeNotifier implements ImageSendCodec {
|
||||
await pendingRelease;
|
||||
} catch (_) {}
|
||||
}
|
||||
if (_session != null && _loadedBundle == bundle) {
|
||||
return _session;
|
||||
final cached = _session;
|
||||
if (cached != null && cached.isDead) {
|
||||
// The worker isolate died; its port answers nothing. Spawn a fresh one
|
||||
// rather than hanging every later job on it.
|
||||
_session = null;
|
||||
_loadedBundle = null;
|
||||
} else if (cached != null && _loadedBundle == bundle) {
|
||||
return cached;
|
||||
}
|
||||
if (bundle == _failedBundle) {
|
||||
return null;
|
||||
|
||||
@@ -79,6 +79,11 @@ class ImageCodecSession {
|
||||
final Map<int, Completer<void>> _pendingReleases = {};
|
||||
int _nextJobId = 1;
|
||||
bool _disposed = false;
|
||||
bool _dead = false;
|
||||
|
||||
/// True once the worker isolate has died. A dead session can never answer
|
||||
/// again, so the owner must drop it and spawn a new one.
|
||||
bool get isDead => _dead;
|
||||
|
||||
ImageCodecSession._({
|
||||
required Isolate isolate,
|
||||
@@ -121,12 +126,16 @@ class ImageCodecSession {
|
||||
});
|
||||
|
||||
errors.listen((message) {
|
||||
final description = message is List && message.isNotEmpty
|
||||
// `null` is the onExit notification: the isolate is gone without an
|
||||
// error report (killed, or a native crash).
|
||||
final description = message == null
|
||||
? 'exited'
|
||||
: message is List && message.isNotEmpty
|
||||
? message.first.toString()
|
||||
: message.toString();
|
||||
final active = session;
|
||||
if (active != null) {
|
||||
active._failAll(StateError('Image codec isolate died: $description'));
|
||||
active._markDead(StateError('Image codec isolate died: $description'));
|
||||
} else if (!handshake.isCompleted) {
|
||||
handshake.complete({'type': 'fatal', 'error': description});
|
||||
}
|
||||
@@ -146,6 +155,7 @@ class ImageCodecSession {
|
||||
),
|
||||
errorsAreFatal: true,
|
||||
onError: errors.sendPort,
|
||||
onExit: errors.sendPort,
|
||||
debugName: 'image-codec',
|
||||
);
|
||||
} catch (_) {
|
||||
@@ -359,6 +369,18 @@ class ImageCodecSession {
|
||||
}
|
||||
}
|
||||
|
||||
/// The worker died on its own. Fail what is pending and refuse new work,
|
||||
/// or the next job would be sent to a dead port and wait forever.
|
||||
void _markDead(Object error) {
|
||||
if (_disposed) return;
|
||||
_dead = true;
|
||||
_disposed = true;
|
||||
_failAll(error);
|
||||
_isolate.kill(priority: Isolate.immediate);
|
||||
_fromWorker.close();
|
||||
_errors.close();
|
||||
}
|
||||
|
||||
/// Kills the isolate and frees the model's resident memory.
|
||||
Future<void> dispose() async {
|
||||
if (_disposed) return;
|
||||
|
||||
@@ -20,6 +20,8 @@ class ImageCodecSession {
|
||||
|
||||
bool get hasTables => false;
|
||||
|
||||
bool get isDead => false;
|
||||
|
||||
Future<void> release({bool decoder = false, bool entropy = false}) async {}
|
||||
|
||||
Future<Uint8List> decodeLatent(
|
||||
|
||||
@@ -275,14 +275,26 @@ class MapTileCacheResult {
|
||||
final int total;
|
||||
final int downloaded;
|
||||
final int failed;
|
||||
final bool cancelled;
|
||||
|
||||
const MapTileCacheResult({
|
||||
required this.total,
|
||||
required this.downloaded,
|
||||
required this.failed,
|
||||
this.cancelled = false,
|
||||
});
|
||||
}
|
||||
|
||||
/// Cooperative cancellation flag for [MapTileCacheService.downloadRegion].
|
||||
/// Tiles already in flight finish; no new tiles are queued after [cancel].
|
||||
class MapTileDownloadCancelToken {
|
||||
bool _cancelled = false;
|
||||
|
||||
bool get isCancelled => _cancelled;
|
||||
|
||||
void cancel() => _cancelled = true;
|
||||
}
|
||||
|
||||
class CachedTileInfo {
|
||||
final String key;
|
||||
final String host;
|
||||
@@ -316,6 +328,10 @@ class MapTileCacheService extends ChangeNotifier {
|
||||
static const int defaultMinZoom = 10;
|
||||
static const int defaultMaxZoom = 15;
|
||||
|
||||
/// Largest bulk download the UI allows in one go. Keeps a single request
|
||||
/// within tile-server usage policies and avoids filling the device.
|
||||
static const int maxBulkDownloadTiles = 20000;
|
||||
|
||||
final AppSettingsService appSettingsService;
|
||||
final BaseCacheManager cacheManager;
|
||||
late final TileProvider tileProvider;
|
||||
@@ -614,6 +630,7 @@ class MapTileCacheService extends ChangeNotifier {
|
||||
int concurrentDownloads = 8,
|
||||
Map<String, String>? headers,
|
||||
void Function(MapTileCacheProgress progress)? onProgress,
|
||||
MapTileDownloadCancelToken? cancelToken,
|
||||
}) async {
|
||||
final safeMin = math.min(minZoom, maxZoom);
|
||||
final safeMax = math.max(minZoom, maxZoom);
|
||||
@@ -652,10 +669,17 @@ class MapTileCacheService extends ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
var stoppedEarly = false;
|
||||
|
||||
outer:
|
||||
for (int zoom = safeMin; zoom <= safeMax; zoom++) {
|
||||
final tileBounds = _tileBoundsForBounds(bounds, zoom);
|
||||
for (int x = tileBounds.minX; x <= tileBounds.maxX; x++) {
|
||||
for (int y = tileBounds.minY; y <= tileBounds.maxY; y++) {
|
||||
if (cancelToken?.isCancelled ?? false) {
|
||||
stoppedEarly = true;
|
||||
break outer;
|
||||
}
|
||||
final url = _buildTileUrl(x, y, zoom, urlTemplate: currentTemplate);
|
||||
await queueDownload(url);
|
||||
}
|
||||
@@ -670,6 +694,7 @@ class MapTileCacheService extends ChangeNotifier {
|
||||
total: total,
|
||||
downloaded: completed - failed,
|
||||
failed: failed,
|
||||
cancelled: stoppedEarly,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -26,7 +26,9 @@ class _AckHistoryEntry {
|
||||
/// for O(1) lookup. [pathSelection] snapshots the route used for this
|
||||
/// specific attempt so that a late PUSH_CODE_SEND_CONFIRMED credits the
|
||||
/// correct path even when the message has since been retried on a different
|
||||
/// route.
|
||||
/// route. Firmware hashes only `attempt & 3`, so attempts N and N+4 of one
|
||||
/// message share an ACK hash; each hash therefore keeps every attempt that
|
||||
/// produced it.
|
||||
typedef AckHashMapping = ({
|
||||
String messageId,
|
||||
DateTime timestamp,
|
||||
@@ -93,7 +95,7 @@ class MessageRetryService extends ChangeNotifier {
|
||||
final Map<String, Message> _pendingMessages = {};
|
||||
final Map<String, Contact> _pendingContacts = {};
|
||||
final Map<String, List<PathSelection>> _attemptPathHistory = {};
|
||||
final Map<String, AckHashMapping> _ackHashToMessageId = {};
|
||||
final Map<String, List<AckHashMapping>> _ackHashToMessageId = {};
|
||||
final Map<String, List<int>> _expectedAckHashes = {};
|
||||
final List<_AckHistoryEntry> _ackHistory = [];
|
||||
final Map<String, List<String>> _sendQueue = {};
|
||||
@@ -103,7 +105,11 @@ class MessageRetryService extends ChangeNotifier {
|
||||
|
||||
RetryServiceConfig? _config;
|
||||
|
||||
MessageRetryService();
|
||||
/// Extra time allowed for RESP_CODE_SENT on top of the delivery timeout
|
||||
/// before an attempt with no SENT reply is treated as timed out.
|
||||
final Duration sentWatchdogGrace;
|
||||
|
||||
MessageRetryService({this.sentWatchdogGrace = const Duration(seconds: 5)});
|
||||
|
||||
void initialize(RetryServiceConfig config) {
|
||||
_config = config;
|
||||
@@ -387,6 +393,7 @@ class MessageRetryService extends ChangeNotifier {
|
||||
if (config.getSelfPublicKey != null && selfPubKey == null) {
|
||||
throw StateError('Self public key unknown; cannot track ACK');
|
||||
}
|
||||
String? expectedHashHex;
|
||||
if (selfPubKey != null) {
|
||||
final outboundText =
|
||||
config.prepareContactOutboundText?.call(contact, message.text) ??
|
||||
@@ -397,7 +404,7 @@ class MessageRetryService extends ChangeNotifier {
|
||||
outboundText,
|
||||
selfPubKey,
|
||||
);
|
||||
final expectedHashHex = expectedHash.toRadixString(16).padLeft(8, '0');
|
||||
expectedHashHex = expectedHash.toRadixString(16).padLeft(8, '0');
|
||||
_expectedHashToMessageId[expectedHashHex] = messageId;
|
||||
|
||||
final shortText = message.text.length > 20
|
||||
@@ -410,6 +417,87 @@ class MessageRetryService extends ChangeNotifier {
|
||||
}
|
||||
|
||||
await config.sendMessage(contact, message.text, attempt, timestampSeconds);
|
||||
_startSentWatchdog(messageId, attempt, expectedHashHex);
|
||||
}
|
||||
|
||||
/// Arms a timer for an attempt whose RESP_CODE_SENT has not arrived yet.
|
||||
/// Without it a lost SENT reply leaves the message pending forever and
|
||||
/// blocks the contact's queue. A SENT reply replaces this timer with the
|
||||
/// normal ACK timeout via [_startTimeoutTimer].
|
||||
void _startSentWatchdog(
|
||||
String messageId,
|
||||
int attempt,
|
||||
String? expectedHashHex,
|
||||
) {
|
||||
final message = _pendingMessages[messageId];
|
||||
final contact = _pendingContacts[messageId];
|
||||
if (message == null || contact == null) return;
|
||||
if (_resolvedMessages.contains(messageId)) return;
|
||||
if (message.retryCount != attempt ||
|
||||
message.status != MessageStatus.pending) {
|
||||
return; // SENT already arrived, or a newer attempt took over.
|
||||
}
|
||||
if (_timeoutTimers[messageId]?.isActive ?? false) return;
|
||||
|
||||
final timeoutMs =
|
||||
_deliveryTimeoutFor(message, contact) +
|
||||
sentWatchdogGrace.inMilliseconds;
|
||||
_timeoutTimers[messageId] = Timer(Duration(milliseconds: timeoutMs), () {
|
||||
final current = _pendingMessages[messageId];
|
||||
if (current == null ||
|
||||
current.retryCount != attempt ||
|
||||
current.status != MessageStatus.pending) {
|
||||
return;
|
||||
}
|
||||
_config?.debugLogService?.warn(
|
||||
'No RESP_CODE_SENT for message $messageId (attempt $attempt) '
|
||||
'after ${timeoutMs}ms → treating as timed out',
|
||||
tag: 'AckHash',
|
||||
);
|
||||
if (expectedHashHex != null &&
|
||||
_expectedHashToMessageId[expectedHashHex] == messageId) {
|
||||
// Drop the SENT expectation so a late SENT for this attempt can't
|
||||
// restart timers for the retry; keep the hash ACK-matchable in case
|
||||
// the radio did transmit it.
|
||||
_expectedHashToMessageId.remove(expectedHashHex);
|
||||
_addAckHashMapping(expectedHashHex, messageId, current);
|
||||
final hash = int.parse(expectedHashHex, radix: 16);
|
||||
final hashes = _expectedAckHashes.putIfAbsent(messageId, () => []);
|
||||
if (!hashes.contains(hash)) hashes.add(hash);
|
||||
}
|
||||
_handleTimeout(messageId);
|
||||
});
|
||||
}
|
||||
|
||||
int _deliveryTimeoutFor(Message message, Contact contact) {
|
||||
final config = _config;
|
||||
final calculate = config?.calculateTimeout;
|
||||
if (calculate == null) return calculateDefaultTimeout(contact);
|
||||
final outboundText =
|
||||
config?.prepareContactOutboundText?.call(contact, message.text) ??
|
||||
message.text;
|
||||
return calculate(
|
||||
message.pathLength ?? contact.pathLength,
|
||||
utf8.encode(outboundText).length,
|
||||
contactKey: contact.publicKeyHex,
|
||||
);
|
||||
}
|
||||
|
||||
void _addAckHashMapping(
|
||||
String ackHashHex,
|
||||
String messageId,
|
||||
Message message,
|
||||
) {
|
||||
final mappings = _ackHashToMessageId.putIfAbsent(ackHashHex, () => []);
|
||||
mappings.removeWhere(
|
||||
(m) => m.messageId == messageId && m.attemptIndex == message.retryCount,
|
||||
);
|
||||
mappings.add((
|
||||
messageId: messageId,
|
||||
timestamp: DateTime.now(),
|
||||
attemptIndex: message.retryCount,
|
||||
pathSelection: _selectionFromMessage(message),
|
||||
));
|
||||
}
|
||||
|
||||
bool updateMessageFromSent(int ackHash, int timeoutMs) {
|
||||
@@ -454,12 +542,7 @@ class MessageRetryService extends ChangeNotifier {
|
||||
}
|
||||
|
||||
final message = _pendingMessages[messageId]!;
|
||||
_ackHashToMessageId[ackHashHex] = (
|
||||
messageId: messageId,
|
||||
timestamp: DateTime.now(),
|
||||
attemptIndex: message.retryCount,
|
||||
pathSelection: _selectionFromMessage(message),
|
||||
);
|
||||
_addAckHashMapping(ackHashHex, messageId, message);
|
||||
|
||||
// Add this ACK hash to the list of expected ACKs for this message (for history)
|
||||
_expectedAckHashes[messageId] ??= [];
|
||||
@@ -526,9 +609,10 @@ class MessageRetryService extends ChangeNotifier {
|
||||
|
||||
void _cleanupMessage(String messageId) {
|
||||
_moveAckHashesToHistory(messageId);
|
||||
_ackHashToMessageId.removeWhere(
|
||||
(_, mapping) => mapping.messageId == messageId,
|
||||
);
|
||||
_ackHashToMessageId.removeWhere((_, mappings) {
|
||||
mappings.removeWhere((mapping) => mapping.messageId == messageId);
|
||||
return mappings.isEmpty;
|
||||
});
|
||||
_expectedHashToMessageId.removeWhere((_, msgId) => msgId == messageId);
|
||||
final contactKey = _pendingContacts[messageId]?.publicKeyHex;
|
||||
_pendingMessages.remove(messageId);
|
||||
@@ -672,26 +756,30 @@ class MessageRetryService extends ChangeNotifier {
|
||||
String? matchedMessageId;
|
||||
int? matchedAttemptIndex;
|
||||
PathSelection? matchedPathSelection;
|
||||
// True when attempts on different routes share this ACK hash, so the
|
||||
// route that delivered it is unknown and must not be credited.
|
||||
var ambiguousPath = false;
|
||||
final ackHashHex = ackHash.toRadixString(16).padLeft(8, '0');
|
||||
|
||||
// Clean up old ACK hash mappings (older than 15 minutes)
|
||||
final cutoffTime = DateTime.now().subtract(const Duration(minutes: 15));
|
||||
final hashesToRemove = <String>[];
|
||||
for (var entry in _ackHashToMessageId.entries) {
|
||||
if (entry.value.timestamp.isBefore(cutoffTime)) {
|
||||
hashesToRemove.add(entry.key);
|
||||
}
|
||||
}
|
||||
for (var hash in hashesToRemove) {
|
||||
_ackHashToMessageId.remove(hash);
|
||||
}
|
||||
_ackHashToMessageId.removeWhere((_, mappings) {
|
||||
mappings.removeWhere((m) => m.timestamp.isBefore(cutoffTime));
|
||||
return mappings.isEmpty;
|
||||
});
|
||||
|
||||
// Use direct O(1) lookup via ACK hash mapping
|
||||
final mapping = _ackHashToMessageId[ackHashHex];
|
||||
if (mapping != null) {
|
||||
final mappings = _ackHashToMessageId[ackHashHex];
|
||||
if (mappings != null && mappings.isNotEmpty) {
|
||||
final mapping = mappings.first;
|
||||
matchedMessageId = mapping.messageId;
|
||||
matchedAttemptIndex = mapping.attemptIndex;
|
||||
matchedPathSelection = mapping.pathSelection;
|
||||
ambiguousPath = mappings.any(
|
||||
(m) =>
|
||||
m.messageId != mapping.messageId ||
|
||||
!_sameSelection(m.pathSelection, mapping.pathSelection),
|
||||
);
|
||||
} else {
|
||||
config?.debugLogService?.warn(
|
||||
'PUSH_CODE_SEND_CONFIRMED: ACK hash $ackHashHex not found in direct mapping, trying fallback',
|
||||
@@ -746,13 +834,15 @@ class MessageRetryService extends ChangeNotifier {
|
||||
config?.updateMessage(deliveredMessage);
|
||||
|
||||
if (contact != null) {
|
||||
_recordPathResultFromMessage(
|
||||
contact.publicKeyHex,
|
||||
message,
|
||||
selection,
|
||||
true,
|
||||
tripTimeMs,
|
||||
);
|
||||
if (!ambiguousPath) {
|
||||
_recordPathResultFromMessage(
|
||||
contact.publicKeyHex,
|
||||
message,
|
||||
selection,
|
||||
true,
|
||||
tripTimeMs,
|
||||
);
|
||||
}
|
||||
if (config?.onDeliveryObserved != null &&
|
||||
tripTimeMs > 0 &&
|
||||
message.pathLength != null) {
|
||||
@@ -825,6 +915,13 @@ class MessageRetryService extends ChangeNotifier {
|
||||
callback(contactKey, recordSelection, success, tripTimeMs);
|
||||
}
|
||||
|
||||
static bool _sameSelection(PathSelection? a, PathSelection? b) {
|
||||
if (a == null || b == null) return a == b;
|
||||
return a.useFlood == b.useFlood &&
|
||||
a.hopCount == b.hopCount &&
|
||||
listEquals(a.pathBytes, b.pathBytes);
|
||||
}
|
||||
|
||||
PathSelection? _selectionFromMessage(Message message) {
|
||||
if (message.pathLength != null && message.pathLength! < 0) {
|
||||
return const PathSelection(pathBytes: [], hopCount: -1, useFlood: true);
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:latlong2/latlong.dart';
|
||||
|
||||
const String networkMapBaseUrl = 'https://map.meshcoreopen.org';
|
||||
|
||||
/// Largest bbox span the read endpoints accept, in degrees.
|
||||
const double networkMapMaxBboxSpan = 20.0;
|
||||
|
||||
class NetworkMapBbox {
|
||||
final double minLon;
|
||||
final double minLat;
|
||||
final double maxLon;
|
||||
final double maxLat;
|
||||
|
||||
const NetworkMapBbox({
|
||||
required this.minLon,
|
||||
required this.minLat,
|
||||
required this.maxLon,
|
||||
required this.maxLat,
|
||||
});
|
||||
|
||||
bool get isWithinLimit =>
|
||||
maxLon - minLon <= networkMapMaxBboxSpan &&
|
||||
maxLat - minLat <= networkMapMaxBboxSpan;
|
||||
|
||||
/// Valid request boxes for a visible area, or null when it is larger than
|
||||
/// [networkMapMaxBboxSpan]. [west] and [east] may be unwrapped (beyond
|
||||
/// ±180) or wrapped across the antimeridian (west > east); an area that
|
||||
/// crosses ±180 is split into two boxes, one on each side.
|
||||
static List<NetworkMapBbox>? forVisibleArea({
|
||||
required double west,
|
||||
required double south,
|
||||
required double east,
|
||||
required double north,
|
||||
}) {
|
||||
final minLat = south.clamp(-90.0, 90.0);
|
||||
final maxLat = north.clamp(-90.0, 90.0);
|
||||
var span = east - west;
|
||||
if (span < 0) span += 360;
|
||||
if (span > networkMapMaxBboxSpan ||
|
||||
maxLat - minLat > networkMapMaxBboxSpan) {
|
||||
return null;
|
||||
}
|
||||
final w = (west + 180) % 360 - 180; // Dart % is non-negative here.
|
||||
final e = w + span;
|
||||
NetworkMapBbox box(double a, double b) =>
|
||||
NetworkMapBbox(minLon: a, minLat: minLat, maxLon: b, maxLat: maxLat);
|
||||
if (e <= 180) return [box(w, e)];
|
||||
return [box(w, 180), box(-180, e - 360)];
|
||||
}
|
||||
|
||||
String get query => [
|
||||
minLon,
|
||||
minLat,
|
||||
maxLon,
|
||||
maxLat,
|
||||
].map((v) => v.toStringAsFixed(5)).join(',');
|
||||
}
|
||||
|
||||
/// An H3 cell as the server describes it. [boundary] is the open polygon
|
||||
/// (usually six points), so clients need no H3 library.
|
||||
class NetworkMapCell {
|
||||
final String cell;
|
||||
final LatLng center;
|
||||
final List<LatLng> boundary;
|
||||
|
||||
const NetworkMapCell({
|
||||
required this.cell,
|
||||
required this.center,
|
||||
required this.boundary,
|
||||
});
|
||||
|
||||
factory NetworkMapCell.fromJson(Map<String, dynamic> json) {
|
||||
return NetworkMapCell(
|
||||
cell: json['cell'] as String,
|
||||
center: LatLng(
|
||||
(json['lat'] as num).toDouble(),
|
||||
(json['lon'] as num).toDouble(),
|
||||
),
|
||||
boundary: [
|
||||
for (final point in (json['boundary'] as List? ?? const []))
|
||||
LatLng(
|
||||
((point as List)[0] as num).toDouble(),
|
||||
(point[1] as num).toDouble(),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
enum NetworkMapRepeaterStatus { active, recent, stale }
|
||||
|
||||
class NetworkMapRepeater {
|
||||
final String key;
|
||||
final String? name;
|
||||
final int type;
|
||||
final NetworkMapCell cell;
|
||||
final String locationSource;
|
||||
final double confidence;
|
||||
final NetworkMapRepeaterStatus status;
|
||||
final bool confirmed;
|
||||
final int sightings;
|
||||
final DateTime? firstSeen;
|
||||
final DateTime? lastSeen;
|
||||
|
||||
// Only present on the single-repeater endpoint.
|
||||
final int? links;
|
||||
final int? coverageCells;
|
||||
final String? reachableArea;
|
||||
|
||||
const NetworkMapRepeater({
|
||||
required this.key,
|
||||
required this.name,
|
||||
required this.type,
|
||||
required this.cell,
|
||||
required this.locationSource,
|
||||
required this.confidence,
|
||||
required this.status,
|
||||
required this.confirmed,
|
||||
required this.sightings,
|
||||
required this.firstSeen,
|
||||
required this.lastSeen,
|
||||
this.links,
|
||||
this.coverageCells,
|
||||
this.reachableArea,
|
||||
});
|
||||
|
||||
bool get isEstimated => locationSource == 'estimated';
|
||||
|
||||
factory NetworkMapRepeater.fromJson(Map<String, dynamic> json) {
|
||||
return NetworkMapRepeater(
|
||||
key: (json['key'] as String).toLowerCase(),
|
||||
name: json['name'] as String?,
|
||||
type: (json['type'] as num?)?.toInt() ?? 2,
|
||||
cell: NetworkMapCell.fromJson(json['cell'] as Map<String, dynamic>),
|
||||
locationSource: json['locationSource'] as String? ?? 'advert',
|
||||
confidence: (json['confidence'] as num?)?.toDouble() ?? 0,
|
||||
status: NetworkMapRepeaterStatus.values.firstWhere(
|
||||
(s) => s.name == json['status'],
|
||||
orElse: () => NetworkMapRepeaterStatus.stale,
|
||||
),
|
||||
confirmed: json['confirmed'] as bool? ?? false,
|
||||
sightings: (json['sightings'] as num?)?.toInt() ?? 0,
|
||||
firstSeen: _parseTime(json['firstSeen']),
|
||||
lastSeen: _parseTime(json['lastSeen']),
|
||||
links: (json['links'] as num?)?.toInt(),
|
||||
coverageCells: (json['coverageCells'] as num?)?.toInt(),
|
||||
reachableArea: json['reachableArea'] as String?,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class NetworkMapLink {
|
||||
final String a;
|
||||
final String b;
|
||||
final NetworkMapCell aCell;
|
||||
final NetworkMapCell bCell;
|
||||
final int packets;
|
||||
final double? snr;
|
||||
final bool confirmed;
|
||||
|
||||
const NetworkMapLink({
|
||||
required this.a,
|
||||
required this.b,
|
||||
required this.aCell,
|
||||
required this.bCell,
|
||||
required this.packets,
|
||||
required this.snr,
|
||||
required this.confirmed,
|
||||
});
|
||||
|
||||
factory NetworkMapLink.fromJson(Map<String, dynamic> json) {
|
||||
return NetworkMapLink(
|
||||
a: (json['a'] as String).toLowerCase(),
|
||||
b: (json['b'] as String).toLowerCase(),
|
||||
aCell: NetworkMapCell.fromJson(json['aCell'] as Map<String, dynamic>),
|
||||
bCell: NetworkMapCell.fromJson(json['bCell'] as Map<String, dynamic>),
|
||||
packets: (json['packets'] as num?)?.toInt() ?? 0,
|
||||
snr: (json['snr'] as num?)?.toDouble(),
|
||||
confirmed: json['confirmed'] as bool? ?? false,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
DateTime? _parseTime(Object? value) =>
|
||||
value is String ? DateTime.tryParse(value) : null;
|
||||
|
||||
class NetworkMapApiException implements Exception {
|
||||
final int statusCode;
|
||||
|
||||
const NetworkMapApiException(this.statusCode);
|
||||
|
||||
@override
|
||||
String toString() => 'NetworkMapApiException($statusCode)';
|
||||
}
|
||||
|
||||
/// Read-only client for the network map. Viewing never requires the upload
|
||||
/// opt-in and sends nothing about the radio.
|
||||
class NetworkMapApiClient {
|
||||
final http.Client _client;
|
||||
final String baseUrl;
|
||||
|
||||
NetworkMapApiClient({http.Client? client, this.baseUrl = networkMapBaseUrl})
|
||||
: _client = client ?? http.Client();
|
||||
|
||||
static const Duration _timeout = Duration(seconds: 20);
|
||||
|
||||
Future<List<NetworkMapRepeater>> fetchRepeaters(NetworkMapBbox bbox) async {
|
||||
final json = await _get('/v1/repeaters', {
|
||||
'bbox': bbox.query,
|
||||
'includeUnconfirmed': 'true',
|
||||
});
|
||||
return [
|
||||
for (final item in (json['repeaters'] as List? ?? const []))
|
||||
NetworkMapRepeater.fromJson(item as Map<String, dynamic>),
|
||||
];
|
||||
}
|
||||
|
||||
/// Null when the repeater is unknown or hidden (404).
|
||||
Future<NetworkMapRepeater?> fetchRepeater(String key) async {
|
||||
try {
|
||||
return NetworkMapRepeater.fromJson(
|
||||
await _get('/v1/repeaters/${key.toLowerCase()}', const {}),
|
||||
);
|
||||
} on NetworkMapApiException catch (e) {
|
||||
if (e.statusCode == 404) return null;
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
Future<List<NetworkMapLink>> fetchLinks(
|
||||
NetworkMapBbox bbox, {
|
||||
String window = '7d',
|
||||
}) async {
|
||||
final json = await _get('/v1/links', {
|
||||
'bbox': bbox.query,
|
||||
'window': window,
|
||||
});
|
||||
return [
|
||||
for (final item in (json['links'] as List? ?? const []))
|
||||
NetworkMapLink.fromJson(item as Map<String, dynamic>),
|
||||
];
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>> _get(
|
||||
String path,
|
||||
Map<String, String> query,
|
||||
) async {
|
||||
final uri = Uri.parse(
|
||||
'$baseUrl$path',
|
||||
).replace(queryParameters: query.isEmpty ? null : query);
|
||||
final response = await _client.get(uri).timeout(_timeout);
|
||||
if (response.statusCode != 200) {
|
||||
throw NetworkMapApiException(response.statusCode);
|
||||
}
|
||||
return jsonDecode(utf8.decode(response.bodyBytes)) as Map<String, dynamic>;
|
||||
}
|
||||
|
||||
void close() => _client.close();
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export 'network_map_gzip_stub.dart'
|
||||
if (dart.library.io) 'network_map_gzip_io.dart';
|
||||
@@ -0,0 +1,3 @@
|
||||
import 'dart:io';
|
||||
|
||||
List<int>? gzipEncode(List<int> bytes) => gzip.encode(bytes);
|
||||
@@ -0,0 +1,2 @@
|
||||
/// No gzip on web; the server accepts an uncompressed body.
|
||||
List<int>? gzipEncode(List<int> bytes) => null;
|
||||
@@ -0,0 +1,421 @@
|
||||
import 'dart:math';
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:cryptography/cryptography.dart';
|
||||
|
||||
import '../../connector/meshcore_protocol.dart';
|
||||
import '../../connector/raw_packet.dart';
|
||||
import '../../utils/location_grid.dart';
|
||||
|
||||
/// Records uploaded to the network map (see the server's API contract).
|
||||
///
|
||||
/// Everything here is built from the packet header, path and signal values
|
||||
/// only. Payloads, MACs, channel hashes, DM hashes, transport codes and exact
|
||||
/// coordinates never make it into a record.
|
||||
|
||||
const String hiddenNodeMarker = '\u{1F6AB}';
|
||||
const int _maxUploadPathBytes = 64;
|
||||
const int _maxAdvertNameBytes = 32;
|
||||
const int _advertPubKeySize = 32;
|
||||
const int _advertSignatureSize = 64;
|
||||
const int _maxAdvertDataSize = 32;
|
||||
|
||||
class NetworkMapLoc {
|
||||
final double lat;
|
||||
final double lon;
|
||||
|
||||
const NetworkMapLoc(this.lat, this.lon);
|
||||
|
||||
factory NetworkMapLoc.snapped(double lat, double lon) {
|
||||
final snapped = snapToLocationGrid(lat, lon);
|
||||
return NetworkMapLoc(snapped.lat, snapped.lon);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() => {'lat': lat, 'lon': lon};
|
||||
}
|
||||
|
||||
class NetworkMapPreset {
|
||||
final int freqKhz;
|
||||
final double bwKhz;
|
||||
final int sf;
|
||||
final int cr;
|
||||
|
||||
const NetworkMapPreset({
|
||||
required this.freqKhz,
|
||||
required this.bwKhz,
|
||||
required this.sf,
|
||||
required this.cr,
|
||||
});
|
||||
|
||||
static const List<double> _allowedBwKhz = [
|
||||
7.8,
|
||||
10.4,
|
||||
15.6,
|
||||
20.8,
|
||||
31.25,
|
||||
41.7,
|
||||
62.5,
|
||||
125,
|
||||
250,
|
||||
500,
|
||||
];
|
||||
|
||||
/// From the radio's self-info values; null when any is missing or outside
|
||||
/// what the server accepts. Firmware reports frequency in kHz, bandwidth in
|
||||
/// Hz and coding rate as 1–4 or 5–8.
|
||||
static NetworkMapPreset? fromRadio({
|
||||
int? freqKhz,
|
||||
int? bwHz,
|
||||
int? sf,
|
||||
int? cr,
|
||||
}) {
|
||||
if (freqKhz == null || bwHz == null || sf == null || cr == null) {
|
||||
return null;
|
||||
}
|
||||
final bwKhz = _allowedBwKhz.where((bw) => (bw * 1000 - bwHz).abs() < 1);
|
||||
final codingRate = cr <= 4 ? cr + 4 : cr;
|
||||
if (freqKhz < 100000 ||
|
||||
freqKhz > 1100000 ||
|
||||
bwKhz.isEmpty ||
|
||||
sf < 5 ||
|
||||
sf > 12 ||
|
||||
codingRate < 5 ||
|
||||
codingRate > 8) {
|
||||
return null;
|
||||
}
|
||||
return NetworkMapPreset(
|
||||
freqKhz: freqKhz,
|
||||
bwKhz: bwKhz.first,
|
||||
sf: sf,
|
||||
cr: codingRate,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'freqKhz': freqKhz,
|
||||
'bwKhz': bwKhz,
|
||||
'sf': sf,
|
||||
'cr': cr,
|
||||
};
|
||||
}
|
||||
|
||||
class NetworkMapPacketRecord {
|
||||
final int t;
|
||||
final int pt;
|
||||
final int rt;
|
||||
final int hw;
|
||||
final String path;
|
||||
final double snr;
|
||||
final int rssi;
|
||||
final int size;
|
||||
final String h;
|
||||
final bool scoped;
|
||||
|
||||
const NetworkMapPacketRecord({
|
||||
required this.t,
|
||||
required this.pt,
|
||||
required this.rt,
|
||||
required this.hw,
|
||||
required this.path,
|
||||
required this.snr,
|
||||
required this.rssi,
|
||||
required this.size,
|
||||
required this.h,
|
||||
required this.scoped,
|
||||
});
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
't': t,
|
||||
'pt': pt,
|
||||
'rt': rt,
|
||||
'hw': hw,
|
||||
'path': path,
|
||||
'snr': snr,
|
||||
'rssi': rssi,
|
||||
'size': size,
|
||||
'h': h,
|
||||
'scoped': scoped,
|
||||
};
|
||||
}
|
||||
|
||||
class NetworkMapAdvertRecord {
|
||||
final int t;
|
||||
final String key;
|
||||
final int type;
|
||||
final String? name;
|
||||
final NetworkMapLoc? loc;
|
||||
final bool hidden;
|
||||
final double snr;
|
||||
final int rssi;
|
||||
final int rt;
|
||||
final int hw;
|
||||
final String path;
|
||||
|
||||
const NetworkMapAdvertRecord({
|
||||
required this.t,
|
||||
required this.key,
|
||||
required this.type,
|
||||
required this.name,
|
||||
required this.loc,
|
||||
required this.hidden,
|
||||
required this.snr,
|
||||
required this.rssi,
|
||||
required this.rt,
|
||||
required this.hw,
|
||||
required this.path,
|
||||
});
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
't': t,
|
||||
'key': key,
|
||||
'type': type,
|
||||
'name': name,
|
||||
'loc': loc?.toJson(),
|
||||
'hidden': hidden,
|
||||
'snr': snr,
|
||||
'rssi': rssi,
|
||||
'rt': rt,
|
||||
'hw': hw,
|
||||
'path': path,
|
||||
};
|
||||
}
|
||||
|
||||
/// Header, path and signal fields of a `PUSH_CODE_LOG_RX_DATA` frame.
|
||||
class _RxFrame {
|
||||
final double snr;
|
||||
final int rssi;
|
||||
final int rawLength;
|
||||
final int routeType;
|
||||
final int payloadType;
|
||||
final int hashWidth;
|
||||
final Uint8List pathBytes;
|
||||
final Uint8List payload;
|
||||
|
||||
_RxFrame({
|
||||
required this.snr,
|
||||
required this.rssi,
|
||||
required this.rawLength,
|
||||
required this.routeType,
|
||||
required this.payloadType,
|
||||
required this.hashWidth,
|
||||
required this.pathBytes,
|
||||
required this.payload,
|
||||
});
|
||||
|
||||
bool get scoped => routeType == 0 || routeType == 3;
|
||||
|
||||
String get pathHex => _hex(pathBytes);
|
||||
}
|
||||
|
||||
_RxFrame? _parseRxFrame(Uint8List frame) {
|
||||
if (frame.isEmpty || frame[0] != pushCodeLogRxData) return null;
|
||||
try {
|
||||
final reader = BufferReader(frame);
|
||||
reader.skipBytes(1);
|
||||
final snr = reader.readInt8() / 4.0;
|
||||
final rssi = reader.readInt8();
|
||||
final rawLength = reader.remaining;
|
||||
final header = reader.readByte();
|
||||
final routeType = header & 0x03;
|
||||
final payloadType = (header >> 2) & 0x0F;
|
||||
if (routeType == 0 || routeType == 3) {
|
||||
reader.skipBytes(4); // transport codes: never uploaded
|
||||
}
|
||||
final pathLenRaw = reader.readByte();
|
||||
final hashWidth = decodePathHashWidth(pathLenRaw);
|
||||
final pathBytes = reader.readBytes(decodePathByteLen(pathLenRaw));
|
||||
final payload = reader.readBytes(reader.remaining);
|
||||
if (hashWidth > 3 || pathBytes.length > _maxUploadPathBytes) return null;
|
||||
return _RxFrame(
|
||||
snr: snr.clamp(-32.0, 32.0).toDouble(),
|
||||
rssi: rssi.clamp(-200, 0).toInt(),
|
||||
rawLength: rawLength,
|
||||
routeType: routeType,
|
||||
payloadType: payloadType,
|
||||
hashWidth: hashWidth,
|
||||
pathBytes: pathBytes,
|
||||
payload: payload,
|
||||
);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Unix seconds rounded down to the minute.
|
||||
int networkMapMinute(DateTime time) {
|
||||
final seconds = time.millisecondsSinceEpoch ~/ 1000;
|
||||
return seconds - seconds % 60;
|
||||
}
|
||||
|
||||
/// Raw packet length rounded up to a multiple of 16, capped at 256.
|
||||
int roundUpPacketSize(int length) {
|
||||
final rounded = ((length + 15) ~/ 16) * 16;
|
||||
return rounded > 256 ? 256 : rounded;
|
||||
}
|
||||
|
||||
/// Header-only packet record for a received 0x88 frame, or null when the
|
||||
/// frame is malformed or outside what the server accepts.
|
||||
NetworkMapPacketRecord? buildPacketRecord(
|
||||
Uint8List frame,
|
||||
DateTime receivedAt,
|
||||
) {
|
||||
final rx = _parseRxFrame(frame);
|
||||
if (rx == null) return null;
|
||||
return NetworkMapPacketRecord(
|
||||
t: networkMapMinute(receivedAt),
|
||||
pt: rx.payloadType,
|
||||
rt: rx.routeType,
|
||||
hw: rx.hashWidth,
|
||||
path: rx.pathHex,
|
||||
snr: rx.snr,
|
||||
rssi: rx.rssi,
|
||||
size: roundUpPacketSize(rx.rawLength),
|
||||
h: computePacketHash(rx.payloadType, rx.payload),
|
||||
scoped: rx.scoped,
|
||||
);
|
||||
}
|
||||
|
||||
/// Advert record for a received repeater or room server advert whose Ed25519
|
||||
/// signature verifies. Chat and sensor adverts, unsigned or malformed adverts
|
||||
/// and anything that isn't an advert return null.
|
||||
Future<NetworkMapAdvertRecord?> buildAdvertRecord(
|
||||
Uint8List frame,
|
||||
DateTime receivedAt,
|
||||
) async {
|
||||
final rx = _parseRxFrame(frame);
|
||||
if (rx == null || rx.payloadType != payloadTypeADVERT) return null;
|
||||
final payload = rx.payload;
|
||||
const appDataStart = _advertPubKeySize + 4 + _advertSignatureSize;
|
||||
if (payload.length <= appDataStart) return null;
|
||||
|
||||
// Only the first 32 app-data bytes are signed (firmware Mesh.cpp truncates
|
||||
// to MAX_ADVERT_DATA_SIZE before verifying and parsing), so bytes appended
|
||||
// after them must never reach the name, location or 🚫 check.
|
||||
final appData = payload.sublist(
|
||||
appDataStart,
|
||||
min(payload.length, appDataStart + _maxAdvertDataSize),
|
||||
);
|
||||
final flags = appData[0];
|
||||
final type = flags & 0x0F;
|
||||
if (type != advTypeRepeater && type != advTypeRoom) return null;
|
||||
|
||||
final publicKey = payload.sublist(0, _advertPubKeySize);
|
||||
if (!await _verifyAdvertSignature(payload, publicKey)) return null;
|
||||
|
||||
// Same layout as the firmware's AdvertDataParser.
|
||||
var i = 1;
|
||||
NetworkMapLoc? loc;
|
||||
if (flags & 0x10 != 0) {
|
||||
if (appData.length < i + 8) return null;
|
||||
final view = ByteData.sublistView(appData);
|
||||
final lat = view.getInt32(i, Endian.little) / 1e6;
|
||||
final lon = view.getInt32(i + 4, Endian.little) / 1e6;
|
||||
i += 8;
|
||||
if (_isPlausibleLocation(lat, lon)) loc = NetworkMapLoc.snapped(lat, lon);
|
||||
}
|
||||
if (flags & 0x20 != 0) i += 2;
|
||||
if (flags & 0x40 != 0) i += 2;
|
||||
String? name;
|
||||
if (flags & 0x80 != 0 && appData.length > i) {
|
||||
var nameBytes = appData.sublist(i);
|
||||
final nul = nameBytes.indexOf(0);
|
||||
if (nul >= 0) nameBytes = nameBytes.sublist(0, nul);
|
||||
final decoded = utf8.decode(nameBytes, allowMalformed: true);
|
||||
if (decoded.isNotEmpty) name = decoded;
|
||||
}
|
||||
|
||||
final hidden = name != null && name.contains(hiddenNodeMarker);
|
||||
return NetworkMapAdvertRecord(
|
||||
t: networkMapMinute(receivedAt),
|
||||
key: _hex(publicKey),
|
||||
type: type,
|
||||
name: hidden || name == null
|
||||
? null
|
||||
: _truncateUtf8(name, _maxAdvertNameBytes),
|
||||
loc: hidden ? null : loc,
|
||||
hidden: hidden,
|
||||
snr: rx.snr,
|
||||
rssi: rx.rssi,
|
||||
rt: rx.routeType,
|
||||
hw: rx.hashWidth,
|
||||
path: rx.pathHex,
|
||||
);
|
||||
}
|
||||
|
||||
/// The firmware signs pubkey ‖ timestamp ‖ app_data (app_data capped at
|
||||
/// MAX_ADVERT_DATA_SIZE), see Mesh::createAdvert.
|
||||
Future<bool> _verifyAdvertSignature(
|
||||
Uint8List payload,
|
||||
Uint8List publicKey,
|
||||
) async {
|
||||
const sigStart = _advertPubKeySize + 4;
|
||||
const appDataStart = sigStart + _advertSignatureSize;
|
||||
var appDataEnd = payload.length;
|
||||
if (appDataEnd - appDataStart > _maxAdvertDataSize) {
|
||||
appDataEnd = appDataStart + _maxAdvertDataSize;
|
||||
}
|
||||
final message = <int>[
|
||||
...payload.sublist(0, sigStart),
|
||||
...payload.sublist(appDataStart, appDataEnd),
|
||||
];
|
||||
try {
|
||||
return await Ed25519().verify(
|
||||
message,
|
||||
signature: Signature(
|
||||
payload.sublist(sigStart, appDataStart),
|
||||
publicKey: SimplePublicKey(publicKey, type: KeyPairType.ed25519),
|
||||
),
|
||||
);
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool _isPlausibleLocation(double lat, double lon) {
|
||||
const epsilon = 1e-6;
|
||||
return (lat.abs() > epsilon || lon.abs() > epsilon) &&
|
||||
lat >= -90 &&
|
||||
lat <= 90 &&
|
||||
lon >= -180 &&
|
||||
lon <= 180;
|
||||
}
|
||||
|
||||
String _truncateUtf8(String value, int maxBytes) {
|
||||
if (utf8.encode(value).length <= maxBytes) return value;
|
||||
final buffer = StringBuffer();
|
||||
var used = 0;
|
||||
for (final rune in value.runes) {
|
||||
final char = String.fromCharCode(rune);
|
||||
final length = utf8.encode(char).length;
|
||||
if (used + length > maxBytes) break;
|
||||
buffer.write(char);
|
||||
used += length;
|
||||
}
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
String _hex(List<int> bytes) =>
|
||||
bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();
|
||||
|
||||
/// The `POST /v1/upload` body. Field names and nesting follow the contract
|
||||
/// exactly; the server rejects unknown fields.
|
||||
Map<String, dynamic> buildUploadBody({
|
||||
required String installId,
|
||||
required String app,
|
||||
required NetworkMapLoc? loc,
|
||||
required NetworkMapPreset? preset,
|
||||
required int listenSeconds,
|
||||
required List<NetworkMapPacketRecord> packets,
|
||||
required List<NetworkMapAdvertRecord> adverts,
|
||||
}) => {
|
||||
'v': 1,
|
||||
'installId': installId,
|
||||
'token': null,
|
||||
'app': app,
|
||||
'loc': loc?.toJson(),
|
||||
'preset': preset?.toJson(),
|
||||
'listenSeconds': listenSeconds.clamp(0, 600),
|
||||
'packets': [for (final p in packets) p.toJson()],
|
||||
'adverts': [for (final a in adverts) a.toJson()],
|
||||
};
|
||||
@@ -0,0 +1,413 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:package_info_plus/package_info_plus.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../../connector/meshcore_connector.dart';
|
||||
import '../../connector/meshcore_protocol.dart';
|
||||
import '../../storage/prefs_manager.dart';
|
||||
import '../../utils/app_logger.dart';
|
||||
import '../app_settings_service.dart';
|
||||
import 'network_map_api_client.dart';
|
||||
import 'network_map_gzip.dart';
|
||||
import 'network_map_records.dart';
|
||||
|
||||
/// Random per-install identifier, regenerated every 24 h and never derived
|
||||
/// from the radio key.
|
||||
class NetworkMapInstallId {
|
||||
static const _keyId = 'network_map_install_id';
|
||||
static const _keyCreatedAt = 'network_map_install_id_created_at';
|
||||
static const Duration lifetime = Duration(hours: 24);
|
||||
|
||||
final SharedPreferences _prefs;
|
||||
final DateTime Function() _now;
|
||||
final Random _random;
|
||||
|
||||
NetworkMapInstallId(this._prefs, {DateTime Function()? now, Random? random})
|
||||
: _now = now ?? DateTime.now,
|
||||
_random = random ?? Random.secure();
|
||||
|
||||
String current() {
|
||||
final now = _now();
|
||||
final id = _prefs.getString(_keyId);
|
||||
final createdMs = _prefs.getInt(_keyCreatedAt);
|
||||
if (id != null && createdMs != null) {
|
||||
final age = now.difference(
|
||||
DateTime.fromMillisecondsSinceEpoch(createdMs),
|
||||
);
|
||||
if (!age.isNegative && age < lifetime) return id;
|
||||
}
|
||||
final bytes = Uint8List.fromList(
|
||||
List<int>.generate(16, (_) => _random.nextInt(256)),
|
||||
);
|
||||
final fresh = base64Url.encode(bytes).replaceAll('=', '');
|
||||
unawaited(_prefs.setString(_keyId, fresh));
|
||||
unawaited(_prefs.setInt(_keyCreatedAt, now.millisecondsSinceEpoch));
|
||||
return fresh;
|
||||
}
|
||||
}
|
||||
|
||||
class _Queued<T> {
|
||||
final DateTime queuedAt;
|
||||
final T record;
|
||||
|
||||
_Queued(this.queuedAt, this.record);
|
||||
}
|
||||
|
||||
/// Records waiting for upload, with the contract's batch caps and age limit.
|
||||
class NetworkMapUploadQueue {
|
||||
static const int maxPacketsPerBatch = 2000;
|
||||
static const int maxAdvertsPerBatch = 200;
|
||||
static const Duration maxQueueAge = Duration(hours: 1);
|
||||
|
||||
/// The server drops records more than 65 min old, so anything past an hour
|
||||
/// is not worth sending.
|
||||
static const Duration maxRecordAge = Duration(minutes: 60);
|
||||
|
||||
// Bounds memory if uploads keep failing for the full hour.
|
||||
static const int _maxQueuedPackets = maxPacketsPerBatch * 5;
|
||||
|
||||
final List<_Queued<NetworkMapPacketRecord>> _packets = [];
|
||||
final List<_Queued<NetworkMapAdvertRecord>> _adverts = [];
|
||||
|
||||
bool get isEmpty => _packets.isEmpty && _adverts.isEmpty;
|
||||
int get packetCount => _packets.length;
|
||||
int get advertCount => _adverts.length;
|
||||
|
||||
void addPacket(NetworkMapPacketRecord record, DateTime now) {
|
||||
_packets.add(_Queued(now, record));
|
||||
if (_packets.length > _maxQueuedPackets) _packets.removeAt(0);
|
||||
}
|
||||
|
||||
void addAdvert(NetworkMapAdvertRecord record, DateTime now) {
|
||||
// Only the latest advert per key is useful within one batch window.
|
||||
_adverts.removeWhere((q) => q.record.key == record.key);
|
||||
_adverts.add(_Queued(now, record));
|
||||
}
|
||||
|
||||
void dropExpired(DateTime now) {
|
||||
final cutoffSeconds = networkMapMinute(now.subtract(maxRecordAge));
|
||||
bool expired(DateTime queuedAt, int t) =>
|
||||
now.difference(queuedAt) > maxQueueAge || t < cutoffSeconds;
|
||||
_packets.removeWhere((q) => expired(q.queuedAt, q.record.t));
|
||||
_adverts.removeWhere((q) => expired(q.queuedAt, q.record.t));
|
||||
}
|
||||
|
||||
void clear() {
|
||||
_packets.clear();
|
||||
_adverts.clear();
|
||||
}
|
||||
|
||||
/// The oldest records up to the per-batch caps. They stay queued until
|
||||
/// [remove] confirms the upload.
|
||||
({List<NetworkMapPacketRecord> packets, List<NetworkMapAdvertRecord> adverts})
|
||||
peekBatch() => (
|
||||
packets: [for (final q in _packets.take(maxPacketsPerBatch)) q.record],
|
||||
adverts: [for (final q in _adverts.take(maxAdvertsPerBatch)) q.record],
|
||||
);
|
||||
|
||||
void remove(int packets, int adverts) {
|
||||
_packets.removeRange(0, min(packets, _packets.length));
|
||||
_adverts.removeRange(0, min(adverts, _adverts.length));
|
||||
}
|
||||
}
|
||||
|
||||
/// Opt-in uploader for the network map.
|
||||
///
|
||||
/// Listens to raw RX log frames only while the user has opted in and a radio
|
||||
/// is connected, and uploads header-only records in batches.
|
||||
class NetworkMapUploadService extends ChangeNotifier {
|
||||
static const Duration uploadInterval = Duration(seconds: 60);
|
||||
static const Duration heartbeatInterval = Duration(minutes: 5);
|
||||
static const Duration maxBackoff = Duration(minutes: 15);
|
||||
static const int _maxJitterMs = 10000;
|
||||
|
||||
static const _keySentDay = 'network_map_sent_day';
|
||||
static const _keySentCount = 'network_map_sent_count';
|
||||
static const _keyLastUpload = 'network_map_last_upload';
|
||||
|
||||
final MeshCoreConnector _connector;
|
||||
final AppSettingsService _settings;
|
||||
final http.Client _client;
|
||||
final String baseUrl;
|
||||
final Random _random = Random();
|
||||
final NetworkMapUploadQueue _queue = NetworkMapUploadQueue();
|
||||
|
||||
StreamSubscription<Uint8List>? _frameSub;
|
||||
Timer? _timer;
|
||||
bool _uploading = false;
|
||||
|
||||
/// Bumped whenever sharing is turned off. An upload started under an older
|
||||
/// generation is never sent and its result is ignored, so nothing leaves the
|
||||
/// phone after consent is withdrawn and a late response can't touch a queue
|
||||
/// that was cleared and refilled in the meantime.
|
||||
int _consentGeneration = 0;
|
||||
int _failures = 0;
|
||||
Duration _retryAfter = Duration.zero;
|
||||
Duration _nextInterval = uploadInterval;
|
||||
DateTime? _listenMark;
|
||||
int _listenSeconds = 0;
|
||||
DateTime? _lastUploadAt;
|
||||
DateTime? _lastAttemptAt;
|
||||
int _packetsSentToday = 0;
|
||||
String? _appId;
|
||||
|
||||
NetworkMapUploadService({
|
||||
required MeshCoreConnector connector,
|
||||
required AppSettingsService settings,
|
||||
http.Client? client,
|
||||
this.baseUrl = networkMapBaseUrl,
|
||||
}) : _connector = connector,
|
||||
_settings = settings,
|
||||
_client = client ?? http.Client() {
|
||||
_loadStatus();
|
||||
_connector.addListener(_sync);
|
||||
_settings.addListener(_sync);
|
||||
_sync();
|
||||
}
|
||||
|
||||
bool get enabled => _settings.settings.networkMapUploadEnabled;
|
||||
|
||||
/// True while frames are being collected.
|
||||
bool get isActive => _frameSub != null;
|
||||
DateTime? get lastUploadAt => _lastUploadAt;
|
||||
int get packetsSentToday {
|
||||
final prefs = PrefsManager.instance;
|
||||
return prefs.getString(_keySentDay) == _dayKey(DateTime.now())
|
||||
? _packetsSentToday
|
||||
: 0;
|
||||
}
|
||||
|
||||
Future<void> setEnabled(bool value) =>
|
||||
_settings.setNetworkMapUploadEnabled(value);
|
||||
|
||||
void _loadStatus() {
|
||||
final prefs = PrefsManager.instance;
|
||||
final lastMs = prefs.getInt(_keyLastUpload);
|
||||
if (lastMs != null) {
|
||||
_lastUploadAt = DateTime.fromMillisecondsSinceEpoch(lastMs);
|
||||
}
|
||||
_packetsSentToday = prefs.getInt(_keySentCount) ?? 0;
|
||||
}
|
||||
|
||||
void _sync() {
|
||||
if (!enabled && (isActive || !_queue.isEmpty || _uploading)) {
|
||||
_queue.clear();
|
||||
_consentGeneration++;
|
||||
}
|
||||
// The store-review demo radio is simulated; its traffic must not reach
|
||||
// the real map.
|
||||
final shouldListen =
|
||||
enabled && _connector.isConnected && !_connector.isReviewMode;
|
||||
if (shouldListen == isActive) return;
|
||||
if (shouldListen) {
|
||||
_frameSub = _connector.receivedFrames.listen(_onFrame);
|
||||
_listenMark = DateTime.now();
|
||||
_lastAttemptAt ??= DateTime.now();
|
||||
_schedule(uploadInterval);
|
||||
} else {
|
||||
_accrueListenTime();
|
||||
_listenMark = null;
|
||||
unawaited(_frameSub?.cancel());
|
||||
_frameSub = null;
|
||||
_timer?.cancel();
|
||||
_timer = null;
|
||||
}
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void _onFrame(Uint8List frame) {
|
||||
if (frame.isEmpty || frame[0] != pushCodeLogRxData) return;
|
||||
final now = DateTime.now();
|
||||
final packet = buildPacketRecord(frame, now);
|
||||
if (packet == null) return;
|
||||
_queue.addPacket(packet, now);
|
||||
if (packet.pt == payloadTypeADVERT) {
|
||||
unawaited(
|
||||
buildAdvertRecord(frame, now).then((advert) {
|
||||
if (advert != null && isActive) _queue.addAdvert(advert, now);
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void _accrueListenTime() {
|
||||
final mark = _listenMark;
|
||||
if (mark == null) return;
|
||||
final now = DateTime.now();
|
||||
_listenSeconds += now.difference(mark).inSeconds;
|
||||
_listenMark = now;
|
||||
}
|
||||
|
||||
void _schedule(Duration base) {
|
||||
_timer?.cancel();
|
||||
final jitter = Duration(milliseconds: _random.nextInt(_maxJitterMs + 1));
|
||||
_timer = Timer(base + jitter, _tick);
|
||||
}
|
||||
|
||||
Future<void> _tick() async {
|
||||
if (!isActive || _uploading) return;
|
||||
final now = DateTime.now();
|
||||
_queue.dropExpired(now);
|
||||
final sinceLast = now.difference(_lastAttemptAt ?? now);
|
||||
if (_queue.isEmpty && sinceLast < heartbeatInterval) {
|
||||
_schedule(_nextInterval);
|
||||
return;
|
||||
}
|
||||
await _upload();
|
||||
if (isActive) {
|
||||
_schedule(_failures == 0 ? _nextInterval : _backoffDelay);
|
||||
}
|
||||
}
|
||||
|
||||
Duration get _backoffDelay {
|
||||
final exp = uploadInterval * pow(2, _failures - 1).toInt();
|
||||
final delay = exp > maxBackoff ? maxBackoff : exp;
|
||||
return _retryAfter > delay ? _retryAfter : delay;
|
||||
}
|
||||
|
||||
Future<void> _upload() async {
|
||||
_uploading = true;
|
||||
final generation = _consentGeneration;
|
||||
bool stale() => generation != _consentGeneration || !enabled;
|
||||
_lastAttemptAt = DateTime.now();
|
||||
try {
|
||||
_accrueListenTime();
|
||||
final batch = _queue.peekBatch();
|
||||
final lat = _connector.selfLatitude;
|
||||
final lon = _connector.selfLongitude;
|
||||
final hasPosition =
|
||||
lat != null &&
|
||||
lon != null &&
|
||||
(lat.abs() > 1e-6 || lon.abs() > 1e-6) &&
|
||||
lat.abs() <= 90 &&
|
||||
lon.abs() <= 180;
|
||||
final body = buildUploadBody(
|
||||
installId: NetworkMapInstallId(PrefsManager.instance).current(),
|
||||
app: await _appString(),
|
||||
loc: hasPosition ? NetworkMapLoc.snapped(lat, lon) : null,
|
||||
preset: NetworkMapPreset.fromRadio(
|
||||
freqKhz: _connector.currentFreqHz,
|
||||
bwHz: _connector.currentBwHz,
|
||||
sf: _connector.currentSf,
|
||||
cr: _connector.currentCr,
|
||||
),
|
||||
listenSeconds: min(_listenSeconds, 600),
|
||||
packets: batch.packets,
|
||||
adverts: batch.adverts,
|
||||
);
|
||||
if (stale()) return;
|
||||
final jsonBytes = utf8.encode(jsonEncode(body));
|
||||
final gzipped = gzipEncode(jsonBytes);
|
||||
final response = await _client
|
||||
.post(
|
||||
Uri.parse('$baseUrl/v1/upload'),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
if (gzipped != null) 'Content-Encoding': 'gzip',
|
||||
},
|
||||
body: gzipped ?? jsonBytes,
|
||||
)
|
||||
.timeout(const Duration(seconds: 30));
|
||||
if (stale()) return;
|
||||
final status = response.statusCode;
|
||||
if (status == 202 || status == 200) {
|
||||
_queue.remove(batch.packets.length, batch.adverts.length);
|
||||
_onUploaded(batch.packets.length, response.body);
|
||||
} else if (status == 429 || status >= 500) {
|
||||
_onFailed(response.headers['retry-after'], response.body);
|
||||
} else {
|
||||
// 400/413/415: resending the same batch can never succeed.
|
||||
appLogger.warn(
|
||||
'Network map upload rejected ($status): ${response.body}',
|
||||
tag: 'NetworkMap',
|
||||
);
|
||||
_queue.remove(batch.packets.length, batch.adverts.length);
|
||||
_listenSeconds = 0;
|
||||
_failures = 0;
|
||||
}
|
||||
} catch (e) {
|
||||
if (stale()) return;
|
||||
appLogger.warn('Network map upload failed: $e', tag: 'NetworkMap');
|
||||
_onFailed(null, null);
|
||||
} finally {
|
||||
_uploading = false;
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
void _onUploaded(int packetCount, String body) {
|
||||
final now = DateTime.now();
|
||||
_failures = 0;
|
||||
_retryAfter = Duration.zero;
|
||||
_listenSeconds = 0;
|
||||
_lastUploadAt = now;
|
||||
_nextInterval = uploadInterval;
|
||||
try {
|
||||
final next = (jsonDecode(body) as Map)['nextUploadSeconds'];
|
||||
if (next is num && next >= 30 && next <= 900) {
|
||||
_nextInterval = Duration(seconds: next.toInt());
|
||||
}
|
||||
} catch (_) {}
|
||||
|
||||
final prefs = PrefsManager.instance;
|
||||
final today = _dayKey(now);
|
||||
if (prefs.getString(_keySentDay) != today) _packetsSentToday = 0;
|
||||
_packetsSentToday += packetCount;
|
||||
unawaited(prefs.setString(_keySentDay, today));
|
||||
unawaited(prefs.setInt(_keySentCount, _packetsSentToday));
|
||||
unawaited(prefs.setInt(_keyLastUpload, now.millisecondsSinceEpoch));
|
||||
}
|
||||
|
||||
void _onFailed(String? retryAfterHeader, String? body) {
|
||||
_failures++;
|
||||
var retryAfter = int.tryParse(retryAfterHeader?.trim() ?? '');
|
||||
if (retryAfter == null && body != null) {
|
||||
try {
|
||||
final value = (jsonDecode(body) as Map)['retryAfterSeconds'];
|
||||
if (value is num) retryAfter = value.toInt();
|
||||
} catch (_) {}
|
||||
}
|
||||
_retryAfter = retryAfter == null
|
||||
? Duration.zero
|
||||
: Duration(seconds: min(retryAfter, maxBackoff.inSeconds));
|
||||
}
|
||||
|
||||
@visibleForTesting
|
||||
int get queuedPacketCount => _queue.packetCount;
|
||||
|
||||
@visibleForTesting
|
||||
void queuePacketForTest(NetworkMapPacketRecord record) =>
|
||||
_queue.addPacket(record, DateTime.now());
|
||||
|
||||
@visibleForTesting
|
||||
Future<void> uploadNowForTest() => _upload();
|
||||
|
||||
Future<String> _appString() async {
|
||||
if (_appId != null) return _appId!;
|
||||
var version = '';
|
||||
try {
|
||||
version = (await PackageInfo.fromPlatform()).version;
|
||||
} catch (_) {}
|
||||
final cleaned = version.replaceAll(RegExp(r'[^\x21-\x7E]'), '');
|
||||
final id = cleaned.isEmpty ? 'meshcore-open' : 'meshcore-open/$cleaned';
|
||||
return _appId = id.length > 64 ? id.substring(0, 64) : id;
|
||||
}
|
||||
|
||||
static String _dayKey(DateTime time) =>
|
||||
'${time.year}-${time.month}-${time.day}';
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_connector.removeListener(_sync);
|
||||
_settings.removeListener(_sync);
|
||||
_timer?.cancel();
|
||||
unawaited(_frameSub?.cancel());
|
||||
_client.close();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import 'dart:ui';
|
||||
|
||||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
|
||||
|
||||
import '../helpers/message_url_image_helper.dart';
|
||||
@@ -669,6 +670,7 @@ class NotificationService {
|
||||
Future<void> cancelAll() async {
|
||||
_conversations.clear();
|
||||
await _notifications.cancelAll();
|
||||
await _updateBadge(0);
|
||||
}
|
||||
|
||||
Future<void> cancel(int id) async {
|
||||
@@ -705,28 +707,22 @@ class NotificationService {
|
||||
}
|
||||
}
|
||||
|
||||
static const MethodChannel _badgeChannel = MethodChannel(
|
||||
'meshcore_open/app_badge',
|
||||
);
|
||||
|
||||
/// Sets the app icon badge to the current unread total.
|
||||
Future<void> setAppBadge(int count) => _updateBadge(count);
|
||||
|
||||
Future<void> _updateBadge(int count) async {
|
||||
if (PlatformInfo.isIOS || PlatformInfo.isMacOS) {
|
||||
// On Apple platforms, set the badge number directly via a silent update.
|
||||
final darwinDetails = DarwinNotificationDetails(
|
||||
presentAlert: false,
|
||||
presentSound: false,
|
||||
presentBadge: true,
|
||||
badgeNumber: count,
|
||||
);
|
||||
final details = NotificationDetails(
|
||||
iOS: darwinDetails,
|
||||
macOS: darwinDetails,
|
||||
);
|
||||
// Use a fixed ID so each update replaces the previous one.
|
||||
await _notifications.show(
|
||||
id: 'badge_update'.hashCode,
|
||||
title: null,
|
||||
body: null,
|
||||
notificationDetails: details,
|
||||
);
|
||||
// Immediately cancel the silent notification so it doesn't appear in tray.
|
||||
await _notifications.cancel(id: 'badge_update'.hashCode);
|
||||
// Set natively: a silent notification cancelled right after show() is
|
||||
// removed before iOS delivers it, so its badge number never applied.
|
||||
try {
|
||||
await _badgeChannel.invokeMethod<void>('setBadgeCount', count);
|
||||
} catch (e) {
|
||||
debugPrint('Failed to update app badge: $e');
|
||||
}
|
||||
}
|
||||
// On Android, badge count is derived from active notifications,
|
||||
// so cancelling the specific notification above is sufficient.
|
||||
|
||||
@@ -118,7 +118,7 @@ class FileReceivedImageBlobStore implements ReceivedImageBlobStore {
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _write(
|
||||
Future<bool> _write(
|
||||
String streamId,
|
||||
String extension,
|
||||
Uint8List bytes,
|
||||
@@ -127,13 +127,17 @@ class FileReceivedImageBlobStore implements ReceivedImageBlobStore {
|
||||
final path = await _pathFor(streamId, extension);
|
||||
if (path == null) {
|
||||
debugPrint('received_image_blob_store: refusing unsafe id "$streamId"');
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
await File(path).writeAsBytes(bytes, flush: true);
|
||||
return true;
|
||||
} catch (error) {
|
||||
debugPrint(
|
||||
'received_image_blob_store: write $streamId$extension: $error',
|
||||
);
|
||||
// A partial file would be counted as stored by the next startup scan.
|
||||
await _delete(streamId, extension);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -163,7 +167,7 @@ class FileReceivedImageBlobStore implements ReceivedImageBlobStore {
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> writeBitstream(String streamId, Uint8List bytes) =>
|
||||
Future<bool> writeBitstream(String streamId, Uint8List bytes) =>
|
||||
_write(streamId, _bitstreamExt, bytes);
|
||||
|
||||
@override
|
||||
@@ -178,7 +182,7 @@ class FileReceivedImageBlobStore implements ReceivedImageBlobStore {
|
||||
Future<int?> bitstreamSize(String streamId) => _size(streamId, _bitstreamExt);
|
||||
|
||||
@override
|
||||
Future<void> writePng(String streamId, Uint8List bytes) =>
|
||||
Future<bool> writePng(String streamId, Uint8List bytes) =>
|
||||
_write(streamId, _pngExt, bytes);
|
||||
|
||||
@override
|
||||
|
||||
@@ -159,6 +159,11 @@ class ReceivedImageEntry {
|
||||
final int imgId;
|
||||
final int channelIndex;
|
||||
|
||||
/// [Channel.storageId] of the channel the image belongs to. [channelIndex]
|
||||
/// is the radio slot it arrived on, which another channel may reuse later.
|
||||
/// Null only for entries written before channel IDs existed.
|
||||
final String? channelId;
|
||||
|
||||
/// Local clock at the first chunk — code 27 carries no timestamp.
|
||||
final DateTime firstSeen;
|
||||
|
||||
@@ -221,6 +226,7 @@ class ReceivedImageEntry {
|
||||
required this.senderPrefix,
|
||||
required this.imgId,
|
||||
required this.channelIndex,
|
||||
this.channelId,
|
||||
required this.firstSeen,
|
||||
required this.state,
|
||||
required this.receivedChunks,
|
||||
@@ -259,6 +265,7 @@ class ReceivedImageEntry {
|
||||
static const Object _unset = Object();
|
||||
|
||||
ReceivedImageEntry copyWith({
|
||||
String? channelId,
|
||||
ReceivedImageState? state,
|
||||
int? receivedChunks,
|
||||
int? totalChunks,
|
||||
@@ -281,6 +288,7 @@ class ReceivedImageEntry {
|
||||
senderPrefix: senderPrefix,
|
||||
imgId: imgId,
|
||||
channelIndex: channelIndex,
|
||||
channelId: channelId ?? this.channelId,
|
||||
firstSeen: firstSeen,
|
||||
state: state ?? this.state,
|
||||
receivedChunks: receivedChunks ?? this.receivedChunks,
|
||||
@@ -309,6 +317,7 @@ class ReceivedImageEntry {
|
||||
'senderPrefix': senderPrefix,
|
||||
'imgId': imgId,
|
||||
'channelIndex': channelIndex,
|
||||
if (channelId != null) 'channelId': channelId,
|
||||
'firstSeenMs': firstSeen.millisecondsSinceEpoch,
|
||||
'state': state.name,
|
||||
'receivedChunks': receivedChunks,
|
||||
@@ -335,6 +344,7 @@ class ReceivedImageEntry {
|
||||
senderPrefix: json['senderPrefix'] as int? ?? 0,
|
||||
imgId: json['imgId'] as int? ?? 0,
|
||||
channelIndex: json['channelIndex'] as int? ?? 0,
|
||||
channelId: json['channelId'] as String?,
|
||||
firstSeen: DateTime.fromMillisecondsSinceEpoch(
|
||||
json['firstSeenMs'] as int? ?? 0,
|
||||
),
|
||||
@@ -374,11 +384,14 @@ class ReceivedImageEntry {
|
||||
/// `received_images/<streamId>.aeic|.png|.json`. See
|
||||
/// `received_image_blob_store_io.dart`.
|
||||
abstract class ReceivedImageBlobStore {
|
||||
Future<void> writeBitstream(String streamId, Uint8List bytes);
|
||||
/// Returns false when the bytes could not be stored (disk full, unsafe id),
|
||||
/// so the caller never records a file that is not there.
|
||||
Future<bool> writeBitstream(String streamId, Uint8List bytes);
|
||||
Future<Uint8List?> readBitstream(String streamId);
|
||||
Future<void> deleteBitstream(String streamId);
|
||||
|
||||
Future<void> writePng(String streamId, Uint8List bytes);
|
||||
/// Same contract as [writeBitstream].
|
||||
Future<bool> writePng(String streamId, Uint8List bytes);
|
||||
Future<Uint8List?> readPng(String streamId);
|
||||
Future<void> deletePng(String streamId);
|
||||
|
||||
@@ -418,8 +431,9 @@ class InMemoryReceivedImageBlobStore implements ReceivedImageBlobStore {
|
||||
final Map<String, String> _sidecars = <String, String>{};
|
||||
|
||||
@override
|
||||
Future<void> writeBitstream(String streamId, Uint8List bytes) async {
|
||||
Future<bool> writeBitstream(String streamId, Uint8List bytes) async {
|
||||
_bitstreams[streamId] = bytes;
|
||||
return true;
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -439,8 +453,9 @@ class InMemoryReceivedImageBlobStore implements ReceivedImageBlobStore {
|
||||
Future<int?> pngSize(String streamId) async => _pngs[streamId]?.length;
|
||||
|
||||
@override
|
||||
Future<void> writePng(String streamId, Uint8List bytes) async {
|
||||
Future<bool> writePng(String streamId, Uint8List bytes) async {
|
||||
_pngs[streamId] = bytes;
|
||||
return true;
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -551,6 +566,11 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
/// Hard cap on stored PNGs.
|
||||
final int maxImages;
|
||||
|
||||
/// Hard cap on entries of any state. Undecoded entries hold no PNG, so
|
||||
/// [maxImages] never counts them; without this a flood of one-packet images
|
||||
/// grows the sidecars (and the startup scan) without bound.
|
||||
final int maxEntries;
|
||||
|
||||
/// Hard cap on total bytes across all stored files.
|
||||
final int maxBytes;
|
||||
|
||||
@@ -599,6 +619,10 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
/// Set by [handleMemoryPressure] so the decode it cancels is parked rather
|
||||
/// than reported as corrupt.
|
||||
bool _cancelRequested = false;
|
||||
|
||||
/// Set by [setForeground] when backgrounding cancels a running decode, so it
|
||||
/// goes back on the queue instead of being reported as corrupt.
|
||||
bool _backgroundCancelled = false;
|
||||
bool _foreground = true;
|
||||
bool _disposed = false;
|
||||
|
||||
@@ -606,6 +630,7 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
ReceivedImageBlobStore? blobs,
|
||||
this.decoder,
|
||||
this.maxImages = 200,
|
||||
this.maxEntries = 400,
|
||||
this.maxBytes = 64 * 1024 * 1024,
|
||||
this.maxAge = const Duration(days: 30),
|
||||
this.burstCap = 3,
|
||||
@@ -727,7 +752,7 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
}
|
||||
|
||||
_entries[entry.streamId] = entry;
|
||||
_byKey[entry.key] = entry.streamId;
|
||||
_claimKey(entry);
|
||||
_publish(entry);
|
||||
await _persist(entry);
|
||||
}
|
||||
@@ -745,6 +770,7 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
Future<ReceivedImageEntry?> handleOutcome(
|
||||
ImageChunkOutcome outcome, {
|
||||
required int channelIndex,
|
||||
String? channelId,
|
||||
DateTime? at,
|
||||
}) async {
|
||||
final now = at ?? _clock();
|
||||
@@ -795,6 +821,8 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
.toInt(),
|
||||
totalChunks: header.total,
|
||||
error: null,
|
||||
// A first chunk seen before its slot had an ID gets one now.
|
||||
channelId: existing.channelId ?? channelId,
|
||||
);
|
||||
return _store(updated);
|
||||
}
|
||||
@@ -811,6 +839,7 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
senderPrefix: header.senderPrefix,
|
||||
imgId: header.imgId,
|
||||
channelIndex: channelIndex,
|
||||
channelId: channelId,
|
||||
firstSeen: now,
|
||||
state: ReceivedImageState.receiving,
|
||||
receivedChunks: counts,
|
||||
@@ -846,13 +875,14 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
case ImageChunkStatus.completed:
|
||||
final result = outcome.result;
|
||||
if (result == null) return null;
|
||||
return _handleCompleted(result, now);
|
||||
return _handleCompleted(result, now, channelId);
|
||||
}
|
||||
}
|
||||
|
||||
Future<ReceivedImageEntry> _handleCompleted(
|
||||
ImageReassemblyResult result,
|
||||
DateTime now,
|
||||
String? channelId,
|
||||
) async {
|
||||
final key = result.key;
|
||||
var entry = entryForKey(key);
|
||||
@@ -869,17 +899,57 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
senderPrefix: key.senderPrefix,
|
||||
imgId: key.imgId,
|
||||
channelIndex: key.channelIndex,
|
||||
channelId: channelId,
|
||||
firstSeen: now,
|
||||
state: ReceivedImageState.receiving,
|
||||
receivedChunks: result.chunkCount,
|
||||
totalChunks: result.chunkCount,
|
||||
);
|
||||
} else if (entry.channelId == null && channelId != null) {
|
||||
entry = entry.copyWith(channelId: channelId);
|
||||
}
|
||||
|
||||
final metadata = result.metadata;
|
||||
// The reserved high rate (ft16) and any resolution but 512 cannot be
|
||||
// decoded by the only model this build ships; storing them as
|
||||
// `reassembled` would end in an endless "corrupt, retry" loop. Treat them
|
||||
// like an undecodable metadata byte: nothing to retry, no bytes kept.
|
||||
if (metadata != null &&
|
||||
(metadata.rate != ImageCodecRatePoint.standard ||
|
||||
metadata.squareSize != kImageCodecSquareSize)) {
|
||||
_queue.remove(entry.streamId);
|
||||
return _store(
|
||||
entry.copyWith(
|
||||
state: ReceivedImageState.failedCorrupt,
|
||||
receivedChunks: result.chunkCount,
|
||||
totalChunks: result.chunkCount,
|
||||
bitstreamStored: false,
|
||||
error: 'Unsupported image format.',
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
final tracked = _entries.containsKey(entry.streamId);
|
||||
// Bitstream first, state second: a kill between the two must be
|
||||
// recoverable, and `reassembled` with no file on disk is a lie.
|
||||
await blobs.writeBitstream(entry.streamId, result.data);
|
||||
final written = await blobs.writeBitstream(entry.streamId, result.data);
|
||||
if (tracked && !_entries.containsKey(entry.streamId)) {
|
||||
// Deleted (message removed, channel cleared) while the write was in
|
||||
// flight. Storing now would resurrect it with no message to show it.
|
||||
await blobs.deleteBitstream(entry.streamId);
|
||||
return entry;
|
||||
}
|
||||
if (!written) {
|
||||
return _store(
|
||||
entry.copyWith(
|
||||
state: ReceivedImageState.failedCorrupt,
|
||||
receivedChunks: result.chunkCount,
|
||||
totalChunks: result.chunkCount,
|
||||
bitstreamStored: false,
|
||||
error: 'Could not save the image data.',
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
final updated = entry.copyWith(
|
||||
state: ReceivedImageState.reassembled,
|
||||
@@ -900,9 +970,12 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
// Park it: the card shows "N bytes · M packets" and "Tap to process".
|
||||
// A 2.16 GiB decode is never started off the back of a radio packet
|
||||
// unless the user asked for that.
|
||||
return _store(updated.copyWith(needsManualDecode: true));
|
||||
final parked = await _store(updated.copyWith(needsManualDecode: true));
|
||||
await _enforceEntryCap(protect: parked.streamId);
|
||||
return parked;
|
||||
}
|
||||
final stored = await _store(updated);
|
||||
await _enforceEntryCap(protect: stored.streamId);
|
||||
_enqueue(stored.streamId);
|
||||
return stored;
|
||||
}
|
||||
@@ -945,6 +1018,7 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
/// ```dart
|
||||
/// final entry = await receivedImageStore.registerOutgoing(
|
||||
/// channelIndex: channelIndex,
|
||||
/// channelId: channel.storageId,
|
||||
/// senderPrefix: selfPrefix, // same 16 bits the chunk header carries
|
||||
/// imgId: chunkSet.imgId,
|
||||
/// previewPng: preview.croppedPngBytes, // the 512x512 crop, NOT a decode
|
||||
@@ -960,11 +1034,13 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
/// memory beyond the encode that already ran.
|
||||
Future<ReceivedImageEntry> registerOutgoing({
|
||||
required int channelIndex,
|
||||
String? channelId,
|
||||
required int senderPrefix,
|
||||
required int imgId,
|
||||
required Uint8List previewPng,
|
||||
required AeicRatePoint rate,
|
||||
required int chunkCount,
|
||||
int aspectCode = 0,
|
||||
DateTime? at,
|
||||
}) async {
|
||||
final now = at ?? _clock();
|
||||
@@ -973,21 +1049,28 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
imgId: imgId,
|
||||
firstSeen: now,
|
||||
);
|
||||
await blobs.writePng(streamId, previewPng);
|
||||
// A failed write still shows the photo for this session (the bytes stay
|
||||
// cached on the entry); the next launch then reports it as evicted rather
|
||||
// than pointing at a file that was never written.
|
||||
final pngWritten = await blobs.writePng(streamId, previewPng);
|
||||
final entry = ReceivedImageEntry(
|
||||
streamId: streamId,
|
||||
senderPrefix: senderPrefix,
|
||||
imgId: imgId,
|
||||
channelIndex: channelIndex,
|
||||
channelId: channelId,
|
||||
firstSeen: now,
|
||||
state: ReceivedImageState.decoded,
|
||||
receivedChunks: chunkCount,
|
||||
totalChunks: chunkCount,
|
||||
rate: rate,
|
||||
// The preview is the same stretched 512x512 square the receiver gets,
|
||||
// so the sender's bubble needs the source shape to undo it too.
|
||||
aspectCode: aspectCode,
|
||||
metadataAssumed: false,
|
||||
isOutgoing: true,
|
||||
pngStored: true,
|
||||
pngByteCount: previewPng.length,
|
||||
pngStored: pngWritten,
|
||||
pngByteCount: pngWritten ? previewPng.length : 0,
|
||||
pngBytes: previewPng,
|
||||
);
|
||||
final stored = await _store(entry);
|
||||
@@ -1003,7 +1086,12 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
if (_foreground == value) return;
|
||||
_foreground = value;
|
||||
if (!value) {
|
||||
decoder?.cancelCodecJob();
|
||||
// Only cancel OUR decode: the codec is shared with the send sheet, and an
|
||||
// encode it is running is not this store's to stop.
|
||||
if (_decodeInFlight) {
|
||||
_backgroundCancelled = true;
|
||||
decoder?.cancelCodecJob();
|
||||
}
|
||||
} else {
|
||||
_parkedOnBusyDecoder = false;
|
||||
_kick();
|
||||
@@ -1193,9 +1281,14 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
ReceivedImageDecoder decoder,
|
||||
) async {
|
||||
final bitstream = await blobs.readBitstream(entry.streamId);
|
||||
// Every await below is a window in which the user may delete the image
|
||||
// (message removed, channel cleared). Re-read the live entry after each
|
||||
// one and stop if it is gone, or the decode would store it back.
|
||||
final live = _entries[entry.streamId];
|
||||
if (live == null) return;
|
||||
if (bitstream == null || bitstream.isEmpty) {
|
||||
await _store(
|
||||
entry.copyWith(
|
||||
live.copyWith(
|
||||
state: ReceivedImageState.failedCorrupt,
|
||||
bitstreamStored: false,
|
||||
error: 'Bitstream missing.',
|
||||
@@ -1205,49 +1298,34 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
}
|
||||
final started = _clock();
|
||||
_cancelRequested = false;
|
||||
await _store(entry.copyWith(state: ReceivedImageState.decoding));
|
||||
_backgroundCancelled = false;
|
||||
await _store(live.copyWith(state: ReceivedImageState.decoding));
|
||||
|
||||
ImageCodecResult? result;
|
||||
Object? failure;
|
||||
try {
|
||||
result = await decoder.decodeBitstream(
|
||||
bitstream: bitstream,
|
||||
ratePoint: entry.rate,
|
||||
resolution: entry.resolution,
|
||||
ratePoint: live.rate,
|
||||
resolution: live.resolution,
|
||||
);
|
||||
} catch (error) {
|
||||
final current = _entries[entry.streamId] ?? entry;
|
||||
if (_cancelRequested) {
|
||||
await _store(
|
||||
current.copyWith(
|
||||
state: ReceivedImageState.reassembled,
|
||||
needsManualDecode: true,
|
||||
),
|
||||
);
|
||||
} else if (!_foreground) {
|
||||
await _store(current.copyWith(state: ReceivedImageState.reassembled));
|
||||
} else {
|
||||
await _store(
|
||||
current.copyWith(
|
||||
state: ReceivedImageState.failedCorrupt,
|
||||
error: error.toString(),
|
||||
),
|
||||
);
|
||||
}
|
||||
return;
|
||||
failure = error;
|
||||
}
|
||||
|
||||
final current = _entries[entry.streamId] ?? entry;
|
||||
if (result == null) {
|
||||
// canDecode false — the codec cannot run at all.
|
||||
await _store(
|
||||
current.copyWith(state: ReceivedImageState.decoderUnavailable),
|
||||
);
|
||||
return;
|
||||
}
|
||||
final png = result.pngBytes;
|
||||
if (result.status != ImageCodecStatus.completed || png == null) {
|
||||
final current = _entries[entry.streamId];
|
||||
if (current == null) return;
|
||||
final png = result?.pngBytes;
|
||||
final completed =
|
||||
failure == null &&
|
||||
result != null &&
|
||||
result.status == ImageCodecStatus.completed &&
|
||||
png != null;
|
||||
|
||||
if (!completed) {
|
||||
if (_cancelRequested) {
|
||||
// The codec reports a killed job as `failed`; the bitstream is fine.
|
||||
// Memory pressure: the codec reports a killed job as `failed`, but
|
||||
// the bitstream is fine. Park it behind a tap.
|
||||
await _store(
|
||||
current.copyWith(
|
||||
state: ReceivedImageState.reassembled,
|
||||
@@ -1256,27 +1334,47 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (_backgroundCancelled || !_foreground) {
|
||||
// Backgrounded mid-decode: back to the front of the queue, so coming
|
||||
// back to the app picks it up again.
|
||||
await _store(current.copyWith(state: ReceivedImageState.reassembled));
|
||||
if (!_queue.contains(current.streamId)) {
|
||||
_queue.insert(0, current.streamId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (failure == null && result == null) {
|
||||
// canDecode false — the codec cannot run at all.
|
||||
await _store(
|
||||
current.copyWith(state: ReceivedImageState.decoderUnavailable),
|
||||
);
|
||||
return;
|
||||
}
|
||||
await _store(
|
||||
current.copyWith(
|
||||
state: ReceivedImageState.failedCorrupt,
|
||||
error: 'Decoder rejected the bitstream.',
|
||||
error: failure?.toString() ?? 'Decoder rejected the bitstream.',
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!_foreground) {
|
||||
// Backgrounded mid-decode: keep the pixels, but do not claim a decode we
|
||||
// may have half-cancelled.
|
||||
await _store(current.copyWith(state: ReceivedImageState.reassembled));
|
||||
|
||||
// A completed result is a finished decode even if the app went to the
|
||||
// background in the meantime; throwing the pixels away would only make
|
||||
// the user wait for a second 2 GiB run.
|
||||
final written = await blobs.writePng(current.streamId, png);
|
||||
final afterWrite = _entries[entry.streamId];
|
||||
if (afterWrite == null) {
|
||||
await blobs.deletePng(current.streamId);
|
||||
return;
|
||||
}
|
||||
|
||||
await blobs.writePng(current.streamId, png);
|
||||
await _store(
|
||||
current.copyWith(
|
||||
afterWrite.copyWith(
|
||||
state: ReceivedImageState.decoded,
|
||||
pngStored: true,
|
||||
pngByteCount: png.length,
|
||||
// A failed write keeps the pixels cached for this session; the next
|
||||
// launch reports the image as evicted ("Decode again") instead.
|
||||
pngStored: written,
|
||||
pngByteCount: written ? png.length : 0,
|
||||
pngBytes: png,
|
||||
decodeMs: result.durationMs > 0
|
||||
? result.durationMs
|
||||
@@ -1288,7 +1386,7 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
// Without `protect` the freshly decoded image is the budget's own victim
|
||||
// whenever it is also the oldest: decode -> evict -> "Decode again" ->
|
||||
// evict, forever.
|
||||
await evictToBudget(protect: current.streamId);
|
||||
await evictToBudget(protect: afterWrite.streamId);
|
||||
}
|
||||
|
||||
// ---- pixels --------------------------------------------------------------
|
||||
@@ -1330,7 +1428,10 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
Future<void> deleteImage(String streamId) async {
|
||||
final entry = _entries.remove(streamId);
|
||||
_queue.remove(streamId);
|
||||
if (entry != null) {
|
||||
// Only unlink the key if it still points here: a newer image reusing the
|
||||
// same sender/id/channel owns it now, and losing that mapping strands the
|
||||
// newer one on "receiving" while its next chunk opens a third entry.
|
||||
if (entry != null && _byKey[entry.key] == streamId) {
|
||||
_byKey.remove(entry.key);
|
||||
}
|
||||
await blobs.deletePng(streamId);
|
||||
@@ -1349,9 +1450,9 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
///
|
||||
/// Returns the stream ids that were removed, so the caller can strip their
|
||||
/// sentinels from the channel's message list in one pass.
|
||||
Future<List<String>> deleteImagesForChannel(int channelIndex) async {
|
||||
Future<List<String>> deleteImagesForChannelId(String channelId) async {
|
||||
final doomed = _entries.values
|
||||
.where((e) => e.channelIndex == channelIndex)
|
||||
.where((e) => e.channelId == channelId)
|
||||
.map((e) => e.streamId)
|
||||
.toList();
|
||||
for (final streamId in doomed) {
|
||||
@@ -1360,6 +1461,32 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
return doomed;
|
||||
}
|
||||
|
||||
/// Images of [channelId], newest first.
|
||||
List<ReceivedImageEntry> entriesForChannel(String? channelId) {
|
||||
if (channelId == null) return const <ReceivedImageEntry>[];
|
||||
return entries.where((e) => e.channelId == channelId).toList();
|
||||
}
|
||||
|
||||
/// Gives entries saved before channel IDs existed the ID of the channel
|
||||
/// their slot held then ([slotIds], from the radio's cached channel list).
|
||||
/// The store is app-wide, so with several radios the first one migrated
|
||||
/// claims the unstamped images.
|
||||
Future<void> stampLegacyChannelIds(Map<int, String> slotIds) async {
|
||||
for (final entry in _entries.values.toList()) {
|
||||
if (entry.channelId != null) continue;
|
||||
final channelId = slotIds[entry.channelIndex];
|
||||
if (channelId == null) continue;
|
||||
await _store(entry.copyWith(channelId: channelId));
|
||||
}
|
||||
}
|
||||
|
||||
/// Forgets which in-progress streams arrived on [channelIndex] after the
|
||||
/// radio slot was given to another channel, so a new image on that slot
|
||||
/// never continues an old one.
|
||||
void forgetChannelSlot(int channelIndex) {
|
||||
_byKey.removeWhere((key, _) => key.channelIndex == channelIndex);
|
||||
}
|
||||
|
||||
/// Deletes an image for each sentinel that is still present in a channel's
|
||||
/// message list, and drops everything else this store holds for that channel.
|
||||
///
|
||||
@@ -1468,10 +1595,58 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
evicted.addAll(await _enforceEntryCap(protect: protect));
|
||||
|
||||
if (evicted.isNotEmpty) _notify();
|
||||
return evicted;
|
||||
}
|
||||
|
||||
/// Brings the entry count inside [maxEntries], oldest first: failures, then
|
||||
/// entries with nothing left on disk, then undecoded incoming images. Never
|
||||
/// touches an outgoing image that still has data on disk, a running decode
|
||||
/// or a stream still receiving.
|
||||
Future<List<String>> _enforceEntryCap({String? protect}) async {
|
||||
final removed = <String>[];
|
||||
if (_entries.length <= maxEntries) return removed;
|
||||
int rank(ReceivedImageEntry e) {
|
||||
if (e.state.isFailure) return 0;
|
||||
if (e.state == ReceivedImageState.evicted && !e.bitstreamStored) {
|
||||
return 1;
|
||||
}
|
||||
return 2;
|
||||
}
|
||||
|
||||
final victims =
|
||||
_entries.values
|
||||
.where(
|
||||
(e) =>
|
||||
e.streamId != protect &&
|
||||
// An outgoing image may go once nothing of it is left on
|
||||
// disk (age eviction only marks it evicted), or it failed;
|
||||
// otherwise frequent senders grow sidecars without bound.
|
||||
(!e.isOutgoing ||
|
||||
e.state.isFailure ||
|
||||
(e.state == ReceivedImageState.evicted &&
|
||||
!e.pngStored &&
|
||||
!e.bitstreamStored)) &&
|
||||
(e.state.isFailure ||
|
||||
e.state == ReceivedImageState.evicted ||
|
||||
e.state == ReceivedImageState.reassembled ||
|
||||
e.state == ReceivedImageState.decoderUnavailable),
|
||||
)
|
||||
.toList()
|
||||
..sort((a, b) {
|
||||
final byRank = rank(a).compareTo(rank(b));
|
||||
return byRank != 0 ? byRank : a.firstSeen.compareTo(b.firstSeen);
|
||||
});
|
||||
for (final victim in victims) {
|
||||
if (_entries.length <= maxEntries) break;
|
||||
await deleteImage(victim.streamId);
|
||||
removed.add(victim.streamId);
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
|
||||
// ---- plumbing ------------------------------------------------------------
|
||||
|
||||
String _uniqueStreamId({
|
||||
@@ -1507,11 +1682,25 @@ class ReceivedImageStore extends ChangeNotifier {
|
||||
|
||||
void _storeSync(ReceivedImageEntry entry) {
|
||||
_entries[entry.streamId] = entry;
|
||||
_byKey[entry.key] = entry.streamId;
|
||||
_claimKey(entry);
|
||||
_publish(entry);
|
||||
_notify();
|
||||
}
|
||||
|
||||
/// Points the entry's key at it unless a newer image already holds the key.
|
||||
/// Updating an old entry (eviction, a late decode) must not steal the key
|
||||
/// back from a newer stream that reused the same 8-bit id.
|
||||
void _claimKey(ReceivedImageEntry entry) {
|
||||
final holderId = _byKey[entry.key];
|
||||
if (holderId != null && holderId != entry.streamId) {
|
||||
final holder = _entries[holderId];
|
||||
if (holder != null && holder.firstSeen.isAfter(entry.firstSeen)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
_byKey[entry.key] = entry.streamId;
|
||||
}
|
||||
|
||||
Future<void> _persist(ReceivedImageEntry entry) async {
|
||||
try {
|
||||
await blobs.writeSidecar(entry.streamId, jsonEncode(entry.toJson()));
|
||||
|
||||
@@ -14,12 +14,21 @@ String normalizeRepeaterClockSyncCommand(String command, {int? nowSeconds}) {
|
||||
return command.trim().toLowerCase() == 'clock sync' ? 'time $epoch' : command;
|
||||
}
|
||||
|
||||
/// One [RepeaterCommandService.sendCommand] call. Every retry adds a fresh
|
||||
/// `XX|` prefix, and a reply to any of them completes the call, so a late
|
||||
/// reply to an earlier attempt is not mistaken for silence.
|
||||
class _PendingCommand {
|
||||
_PendingCommand(this.repeaterKey);
|
||||
|
||||
final String repeaterKey;
|
||||
final Completer<String> completer = Completer<String>();
|
||||
final Set<String> prefixes = {};
|
||||
}
|
||||
|
||||
class RepeaterCommandService {
|
||||
final MeshCoreConnector _connector;
|
||||
final Map<String, Completer<String>> _pendingCommands = {};
|
||||
final Map<String, Timer> _commandTimeouts = {};
|
||||
final Map<String, String> _commandPrefixes = {};
|
||||
final Map<String, String> _pendingByPrefix = {};
|
||||
final Set<_PendingCommand> _pendingCommands = {};
|
||||
final Map<String, _PendingCommand> _pendingByPrefix = {};
|
||||
int _prefixCounter = 0;
|
||||
|
||||
static const int maxRetries = 5;
|
||||
@@ -40,26 +49,33 @@ class RepeaterCommandService {
|
||||
}) async {
|
||||
if (!raw) command = normalizeRepeaterClockSyncCommand(command);
|
||||
final attemptCount = retries < 1 ? 1 : retries;
|
||||
final selection = await _connector.preparePathForContactSend(repeater);
|
||||
final pending = _PendingCommand(repeater.publicKeyHex);
|
||||
_pendingCommands.add(pending);
|
||||
try {
|
||||
final selection = await _connector.preparePathForContactSend(repeater);
|
||||
|
||||
for (int attempt = 0; attempt < attemptCount; attempt++) {
|
||||
onAttempt?.call(attempt + 1);
|
||||
try {
|
||||
final response = await _sendCommandAttempt(
|
||||
repeater,
|
||||
command,
|
||||
selection,
|
||||
attempt,
|
||||
raw,
|
||||
);
|
||||
onResponse?.call(response);
|
||||
return response;
|
||||
} catch (e) {
|
||||
if (attempt == attemptCount - 1) rethrow;
|
||||
for (int attempt = 0; attempt < attemptCount; attempt++) {
|
||||
onAttempt?.call(attempt + 1);
|
||||
try {
|
||||
final response = await _sendCommandAttempt(
|
||||
repeater,
|
||||
command,
|
||||
selection,
|
||||
attempt,
|
||||
raw,
|
||||
pending,
|
||||
);
|
||||
onResponse?.call(response);
|
||||
return response;
|
||||
} catch (e) {
|
||||
if (attempt == attemptCount - 1) rethrow;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw Exception('Command failed after $attemptCount attempts');
|
||||
throw Exception('Command failed after $attemptCount attempts');
|
||||
} finally {
|
||||
_cleanup(pending);
|
||||
}
|
||||
}
|
||||
|
||||
Future<String> _sendCommandAttempt(
|
||||
@@ -68,15 +84,16 @@ class RepeaterCommandService {
|
||||
PathSelection selection,
|
||||
int attempt,
|
||||
bool raw,
|
||||
_PendingCommand pending,
|
||||
) async {
|
||||
final repeaterKey = repeater.publicKeyHex;
|
||||
final prefix = _nextPrefixToken();
|
||||
final commandId = '${repeaterKey}_$prefix';
|
||||
final completer = Completer<String>();
|
||||
_pendingCommands[commandId] = completer;
|
||||
_commandPrefixes[commandId] = prefix;
|
||||
_pendingByPrefix[prefix] = commandId;
|
||||
// A reply to an earlier attempt may have arrived during the backoff.
|
||||
if (pending.completer.isCompleted) return pending.completer.future;
|
||||
|
||||
final prefix = _nextPrefixToken();
|
||||
pending.prefixes.add(prefix);
|
||||
_pendingByPrefix[prefix] = pending;
|
||||
|
||||
final int timeoutMs;
|
||||
try {
|
||||
final framedCommand = raw ? command : '$prefix$command';
|
||||
final pathLengthValue = selection.useFlood ? -1 : selection.hopCount;
|
||||
@@ -97,35 +114,29 @@ class RepeaterCommandService {
|
||||
final responseBytes = frame.length > maxFrameSize
|
||||
? frame.length
|
||||
: maxFrameSize;
|
||||
final timeoutMs = _connector.calculateTimeout(
|
||||
timeoutMs = _connector.calculateTimeout(
|
||||
pathLength: pathLengthValue,
|
||||
messageBytes: responseBytes,
|
||||
);
|
||||
final timeoutSeconds = (timeoutMs / 1000).ceil();
|
||||
await _connector.sendFrame(frame);
|
||||
_commandTimeouts[commandId]?.cancel();
|
||||
_commandTimeouts[commandId] = Timer(
|
||||
Duration(milliseconds: timeoutMs),
|
||||
() {
|
||||
final completer = _pendingCommands[commandId];
|
||||
if (completer != null && !completer.isCompleted) {
|
||||
completer.completeError(
|
||||
'Command timeout after $timeoutSeconds seconds',
|
||||
);
|
||||
_cleanup(commandId);
|
||||
}
|
||||
},
|
||||
);
|
||||
} catch (e) {
|
||||
_cleanup(commandId);
|
||||
throw Exception('Failed to send command: $e');
|
||||
}
|
||||
|
||||
try {
|
||||
return await completer.future;
|
||||
} finally {
|
||||
_cleanup(commandId);
|
||||
}
|
||||
final timeoutSeconds = (timeoutMs / 1000).ceil();
|
||||
return pending.completer.future.timeout(
|
||||
Duration(milliseconds: timeoutMs),
|
||||
onTimeout: () =>
|
||||
Future<String>.error('Command timeout after $timeoutSeconds seconds'),
|
||||
);
|
||||
}
|
||||
|
||||
/// The text [sendCommand] would put on the wire for its next attempt: the
|
||||
/// clock-sync rewrite plus the `XX|` reply prefix (unless [raw]). Used for
|
||||
/// debug previews so they match what is actually sent.
|
||||
String previewFramedCommand(String command, {bool raw = false}) {
|
||||
if (raw) return command;
|
||||
return '${_peekPrefixToken()}${normalizeRepeaterClockSyncCommand(command)}';
|
||||
}
|
||||
|
||||
/// Send [line] verbatim and don't wait for a reply. While `region load` is
|
||||
@@ -142,51 +153,57 @@ class RepeaterCommandService {
|
||||
// Find pending command for this repeater and complete it
|
||||
final repeaterKey = repeater.publicKeyHex;
|
||||
|
||||
String? commandId;
|
||||
_PendingCommand? pending;
|
||||
String responsePayload = responseText;
|
||||
if (_prefixPattern.hasMatch(responseText)) {
|
||||
final prefix = responseText.substring(0, 3).toUpperCase();
|
||||
commandId = _pendingByPrefix[prefix];
|
||||
if (commandId == null || !commandId.startsWith('${repeaterKey}_')) {
|
||||
pending = _pendingByPrefix[prefix];
|
||||
if (pending == null || pending.repeaterKey != repeaterKey) {
|
||||
return;
|
||||
}
|
||||
responsePayload = responseText.substring(3).trimLeft();
|
||||
}
|
||||
|
||||
commandId ??= _pendingCommands.keys.firstWhere(
|
||||
(id) => id.startsWith('${repeaterKey}_'),
|
||||
orElse: () => '',
|
||||
);
|
||||
if (pending == null) {
|
||||
for (final candidate in _pendingCommands) {
|
||||
if (candidate.repeaterKey == repeaterKey &&
|
||||
!candidate.completer.isCompleted) {
|
||||
pending = candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (commandId.isEmpty) return;
|
||||
|
||||
final completer = _pendingCommands[commandId];
|
||||
if (completer != null && !completer.isCompleted) {
|
||||
completer.complete(responsePayload);
|
||||
_cleanup(commandId);
|
||||
if (pending != null && !pending.completer.isCompleted) {
|
||||
pending.completer.complete(responsePayload);
|
||||
}
|
||||
}
|
||||
|
||||
void _cleanup(String commandId) {
|
||||
_commandTimeouts[commandId]?.cancel();
|
||||
_commandTimeouts.remove(commandId);
|
||||
_pendingCommands.remove(commandId);
|
||||
final prefix = _commandPrefixes.remove(commandId);
|
||||
if (prefix != null) {
|
||||
_pendingByPrefix.remove(prefix);
|
||||
void _cleanup(_PendingCommand pending) {
|
||||
_pendingCommands.remove(pending);
|
||||
for (final prefix in pending.prefixes) {
|
||||
if (identical(_pendingByPrefix[prefix], pending)) {
|
||||
_pendingByPrefix.remove(prefix);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
for (final timer in _commandTimeouts.values) {
|
||||
timer.cancel();
|
||||
}
|
||||
_commandTimeouts.clear();
|
||||
_pendingCommands.clear();
|
||||
_commandPrefixes.clear();
|
||||
_pendingByPrefix.clear();
|
||||
}
|
||||
|
||||
String _peekPrefixToken() {
|
||||
for (var i = 0; i < 256; i++) {
|
||||
final value = (_prefixCounter + i) & 0xFF;
|
||||
final token = '${value.toRadixString(16).padLeft(2, '0').toUpperCase()}|';
|
||||
if (!_pendingByPrefix.containsKey(token)) {
|
||||
return token;
|
||||
}
|
||||
}
|
||||
return '00|';
|
||||
}
|
||||
|
||||
String _nextPrefixToken() {
|
||||
for (var i = 0; i < 256; i++) {
|
||||
final value = _prefixCounter++ & 0xFF;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'dart:convert';
|
||||
import '../models/delivery_observation.dart';
|
||||
import '../models/path_history.dart';
|
||||
import '../storage/legacy_key_migration.dart';
|
||||
import '../storage/prefs_manager.dart';
|
||||
import '../utils/app_logger.dart';
|
||||
|
||||
@@ -12,6 +13,13 @@ class StorageService {
|
||||
'repeater_auto_clock_sync_after_login';
|
||||
static const String _deliveryObservationsKey = 'delivery_observations';
|
||||
|
||||
/// App-wide keys (not scoped to a radio) that hold per-repeater data. Review
|
||||
/// mode snapshots and restores them so simulated logins leave nothing behind.
|
||||
static const List<String> globalRepeaterKeys = [
|
||||
_repeaterPasswordsKey,
|
||||
_repeaterAutoClockSyncAfterLoginKey,
|
||||
];
|
||||
|
||||
String _publicKeyHex = '';
|
||||
set setPublicKeyHex(String value) =>
|
||||
_publicKeyHex = value.length > 10 ? value.substring(0, 10) : '';
|
||||
@@ -65,10 +73,22 @@ class StorageService {
|
||||
Future<ContactPathHistory?> loadPathHistory(String contactPubKeyHex) async {
|
||||
final prefs = PrefsManager.instance;
|
||||
final key = _pathHistoryKey(contactPubKeyHex);
|
||||
// Fall back to the pre-scoping key so learned routes survive the upgrade.
|
||||
final jsonStr =
|
||||
prefs.getString(key) ??
|
||||
prefs.getString('$_pathHistoryPrefix$contactPubKeyHex');
|
||||
var jsonStr = prefs.getString(key);
|
||||
final legacyKey = '$_pathHistoryPrefix$contactPubKeyHex';
|
||||
if (jsonStr == null &&
|
||||
_publicKeyHex.isNotEmpty &&
|
||||
canMigrateLegacyKeys(_publicKeyHex)) {
|
||||
// Move the pre-scoping history into the first radio that loads it so
|
||||
// learned routes survive the upgrade without leaking into other radios.
|
||||
final legacy = prefs.getString(legacyKey);
|
||||
if (legacy != null) {
|
||||
await prefs.setString(key, legacy);
|
||||
await prefs.remove(legacyKey);
|
||||
jsonStr = legacy;
|
||||
}
|
||||
} else if (jsonStr == null && _publicKeyHex.isEmpty) {
|
||||
jsonStr = prefs.getString(legacyKey);
|
||||
}
|
||||
|
||||
if (jsonStr == null) return null;
|
||||
|
||||
@@ -86,12 +106,23 @@ class StorageService {
|
||||
await prefs.remove('$_pathHistoryPrefix$contactPubKeyHex');
|
||||
}
|
||||
|
||||
/// Clears the path histories of the connected radio only. Histories of other
|
||||
/// radios are left alone; with no radio scope set, everything is cleared.
|
||||
Future<void> clearAllPathHistories() async {
|
||||
final prefs = PrefsManager.instance;
|
||||
final keys = prefs.getKeys();
|
||||
final pathHistoryKeys = keys.where(
|
||||
(key) => key.startsWith(_pathHistoryPrefix),
|
||||
);
|
||||
final scopedPrefix = _publicKeyHex.isEmpty
|
||||
? _pathHistoryPrefix
|
||||
: '$_pathHistoryPrefix${_publicKeyHex}_';
|
||||
// Pre-scoping keys (no radio prefix) would otherwise be migrated into this
|
||||
// radio on the next load and bring the cleared routes back.
|
||||
final clearLegacy =
|
||||
_publicKeyHex.isNotEmpty && canMigrateLegacyKeys(_publicKeyHex);
|
||||
final pathHistoryKeys = prefs.getKeys().where((key) {
|
||||
if (key.startsWith(scopedPrefix)) return true;
|
||||
return clearLegacy &&
|
||||
key.startsWith(_pathHistoryPrefix) &&
|
||||
!key.substring(_pathHistoryPrefix.length).contains('_');
|
||||
}).toList();
|
||||
|
||||
for (final key in pathHistoryKeys) {
|
||||
await prefs.remove(key);
|
||||
|
||||
@@ -64,6 +64,7 @@ class TcpTransportService {
|
||||
return;
|
||||
}
|
||||
socket.setOption(SocketOption.tcpNoDelay, true);
|
||||
_enableKeepAlive(socket);
|
||||
_socket = socket;
|
||||
_activeHost = trimmedHost;
|
||||
_activePort = port;
|
||||
@@ -139,6 +140,85 @@ class TcpTransportService {
|
||||
unawaited(disconnect().whenComplete(_closeFrameController));
|
||||
}
|
||||
|
||||
/// Seconds of silence before the first keepalive probe, the gap between
|
||||
/// probes, and how many unanswered probes drop the socket: a dead peer or
|
||||
/// a link killed by Wi-Fi power saving surfaces in about a minute instead
|
||||
/// of the OS default of two hours, so the connector can reconnect.
|
||||
static const int _keepAliveIdleSeconds = 30;
|
||||
static const int _keepAliveIntervalSeconds = 10;
|
||||
static const int _keepAliveProbeCount = 3;
|
||||
|
||||
/// Dart's [Socket] has no keepalive option, so the raw socket options are
|
||||
/// set per platform. Every option is best-effort: a platform that rejects
|
||||
/// one keeps a working (if slower to notice a dead peer) connection.
|
||||
void _enableKeepAlive(Socket socket) {
|
||||
final int soKeepAlive;
|
||||
final int? tcpKeepIdle;
|
||||
final int? tcpKeepInterval;
|
||||
final int? tcpKeepCount;
|
||||
if (Platform.isLinux || Platform.isAndroid) {
|
||||
soKeepAlive = 9;
|
||||
tcpKeepIdle = 4;
|
||||
tcpKeepInterval = 5;
|
||||
tcpKeepCount = 6;
|
||||
} else if (Platform.isMacOS || Platform.isIOS) {
|
||||
soKeepAlive = 0x0008;
|
||||
tcpKeepIdle = 0x10; // TCP_KEEPALIVE
|
||||
tcpKeepInterval = 0x101;
|
||||
tcpKeepCount = 0x102;
|
||||
} else if (Platform.isWindows) {
|
||||
soKeepAlive = 0x0008;
|
||||
tcpKeepIdle = null;
|
||||
tcpKeepInterval = null;
|
||||
tcpKeepCount = null;
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
void trySet(String name, RawSocketOption option) {
|
||||
try {
|
||||
socket.setRawOption(option);
|
||||
} catch (error) {
|
||||
_debugLogService?.warn('TCP $name not set: $error', tag: 'TCP');
|
||||
}
|
||||
}
|
||||
|
||||
trySet(
|
||||
'SO_KEEPALIVE',
|
||||
RawSocketOption.fromBool(RawSocketOption.levelSocket, soKeepAlive, true),
|
||||
);
|
||||
if (tcpKeepIdle != null) {
|
||||
trySet(
|
||||
'keepalive idle',
|
||||
RawSocketOption.fromInt(
|
||||
RawSocketOption.levelTcp,
|
||||
tcpKeepIdle,
|
||||
_keepAliveIdleSeconds,
|
||||
),
|
||||
);
|
||||
}
|
||||
if (tcpKeepInterval != null) {
|
||||
trySet(
|
||||
'keepalive interval',
|
||||
RawSocketOption.fromInt(
|
||||
RawSocketOption.levelTcp,
|
||||
tcpKeepInterval,
|
||||
_keepAliveIntervalSeconds,
|
||||
),
|
||||
);
|
||||
}
|
||||
if (tcpKeepCount != null) {
|
||||
trySet(
|
||||
'keepalive count',
|
||||
RawSocketOption.fromInt(
|
||||
RawSocketOption.levelTcp,
|
||||
tcpKeepCount,
|
||||
_keepAliveProbeCount,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _cleanupFailedConnect() async {
|
||||
final subscription = _socketSubscription;
|
||||
_socketSubscription = null;
|
||||
|
||||
@@ -36,6 +36,10 @@ class TimeoutPredictionService extends ChangeNotifier {
|
||||
final Map<String, _ContactStats> _contactStats = {};
|
||||
Timer? _persistTimer;
|
||||
|
||||
/// When true, [recordObservation] ignores new deliveries. Review mode sets
|
||||
/// this so the simulated radio's fixed ACK delay never trains the real model.
|
||||
static bool recordingSuspended = false;
|
||||
|
||||
TimeoutPredictionService(StorageService storage) : _storage = storage;
|
||||
TimeoutPredictionService.noStorage() : _storage = null;
|
||||
|
||||
@@ -63,6 +67,7 @@ class TimeoutPredictionService extends ChangeNotifier {
|
||||
required int tripTimeMs,
|
||||
int secondsSinceLastRx = 0,
|
||||
}) {
|
||||
if (recordingSuspended) return;
|
||||
final isFlood = pathLength < 0;
|
||||
final observation = DeliveryObservation(
|
||||
contactKey: contactKey,
|
||||
|
||||
@@ -9,6 +9,10 @@ const String contactsAllGroupsValue = '__all__';
|
||||
|
||||
enum ChannelSortOption { manual, name, latestMessages, unread }
|
||||
|
||||
/// Which nodes the map draws: the radio's own contacts, the online network
|
||||
/// map, or both.
|
||||
enum MapSourceOption { local, online, both }
|
||||
|
||||
class UiViewStateService extends ChangeNotifier {
|
||||
static const _keyContactsSelectedGroupName = 'ui_contacts_selected_group';
|
||||
static const _keyContactsSortOption = 'ui_contacts_sort_option';
|
||||
@@ -16,6 +20,7 @@ class UiViewStateService extends ChangeNotifier {
|
||||
static const _keyContactsTypeFilter = 'ui_contacts_type_filter';
|
||||
static const _keyChannelsSortOption = 'ui_channels_sort_option';
|
||||
static const _keyChannelsSortIndexLegacy = 'ui_channels_sort_index';
|
||||
static const _keyMapSource = 'ui_map_source';
|
||||
|
||||
String _contactsSelectedGroupName = contactsAllGroupsValue;
|
||||
String _contactsSearchText = '';
|
||||
@@ -26,6 +31,7 @@ class UiViewStateService extends ChangeNotifier {
|
||||
|
||||
String _channelsSearchText = '';
|
||||
ChannelSortOption _channelsSortOption = ChannelSortOption.manual;
|
||||
MapSourceOption _mapSource = MapSourceOption.local;
|
||||
|
||||
String get contactsSelectedGroupName => _contactsSelectedGroupName;
|
||||
String get contactsSearchText => _contactsSearchText;
|
||||
@@ -35,6 +41,7 @@ class UiViewStateService extends ChangeNotifier {
|
||||
ContactTypeFilter get contactsTypeFilter => _contactsTypeFilter;
|
||||
String get channelsSearchText => _channelsSearchText;
|
||||
ChannelSortOption get channelsSortOption => _channelsSortOption;
|
||||
MapSourceOption get mapSource => _mapSource;
|
||||
|
||||
Future<void> initialize() async {
|
||||
final prefs = PrefsManager.instance;
|
||||
@@ -63,6 +70,14 @@ class UiViewStateService extends ChangeNotifier {
|
||||
);
|
||||
}
|
||||
|
||||
final mapSourceStr = prefs.getString(_keyMapSource);
|
||||
if (mapSourceStr != null) {
|
||||
_mapSource = MapSourceOption.values.firstWhere(
|
||||
(e) => e.name == mapSourceStr,
|
||||
orElse: () => MapSourceOption.local,
|
||||
);
|
||||
}
|
||||
|
||||
final channelSortStr = prefs.getString(_keyChannelsSortOption);
|
||||
if (channelSortStr != null) {
|
||||
_channelsSortOption = ChannelSortOption.values.firstWhere(
|
||||
@@ -151,4 +166,11 @@ class UiViewStateService extends ChangeNotifier {
|
||||
PrefsManager.instance.setString(_keyChannelsSortOption, value.name),
|
||||
);
|
||||
}
|
||||
|
||||
void setMapSource(MapSourceOption value) {
|
||||
if (_mapSource == value) return;
|
||||
_mapSource = value;
|
||||
notifyListeners();
|
||||
unawaited(PrefsManager.instance.setString(_keyMapSource, value.name));
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,11 @@ import 'dart:typed_data';
|
||||
const int usbSerialTxFrameStart = 0x3c;
|
||||
const int usbSerialRxFrameStart = 0x3e;
|
||||
const int usbSerialHeaderLength = 3;
|
||||
// Outgoing (app → radio) payload cap; matches the app's TX frame budget.
|
||||
const int usbSerialMaxPayloadLength = 172;
|
||||
// Incoming (radio → app) payload cap; firmware MAX_FRAME_SIZE is 176 (it
|
||||
// grew by 4 bytes for region transport codes).
|
||||
const int usbSerialMaxRxPayloadLength = 176;
|
||||
|
||||
Uint8List wrapUsbSerialTxFrame(Uint8List payload) {
|
||||
if (payload.length > usbSerialMaxPayloadLength) {
|
||||
@@ -72,7 +76,7 @@ class UsbSerialFrameDecoder {
|
||||
|
||||
final payloadLength =
|
||||
_rxBuffer[_startIndex + 1] | (_rxBuffer[_startIndex + 2] << 8);
|
||||
if (payloadLength > usbSerialMaxPayloadLength) {
|
||||
if (payloadLength > usbSerialMaxRxPayloadLength) {
|
||||
_startIndex++;
|
||||
_compactBufferIfNeeded();
|
||||
continue;
|
||||
|
||||
@@ -86,6 +86,10 @@ class UsbSerialService {
|
||||
if (!_isSupported) {
|
||||
throw UnsupportedError('Web Serial is not supported by this browser.');
|
||||
}
|
||||
if (_port != null || _reader != null || _writer != null) {
|
||||
// Leftovers from a link that died on a read error.
|
||||
await disconnect();
|
||||
}
|
||||
|
||||
_status = UsbSerialStatus.connecting;
|
||||
_lastError = null;
|
||||
@@ -169,7 +173,15 @@ class UsbSerialService {
|
||||
}
|
||||
|
||||
Future<void> disconnect() async {
|
||||
if (_status == UsbSerialStatus.disconnected) return;
|
||||
// A read error or end of stream marks the link disconnected without
|
||||
// closing the port, so still tear down anything left open; otherwise the
|
||||
// next connect() fails with "port already open".
|
||||
if (_status == UsbSerialStatus.disconnected &&
|
||||
_port == null &&
|
||||
_reader == null &&
|
||||
_writer == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
final portLabel = _connectedPortName ?? _connectedPortKey;
|
||||
_debugLogService?.info(
|
||||
|
||||
Reference in new issue
Block a user