Add opt-in network map uploads and online map view

- Opt-in upload of header-only packet records and repeater/room server
  adverts to map.meshcoreopen.org about once a minute; payloads, channel
  and DM hashes and transport codes are stripped on the phone, locations
  snapped to a ~2 km grid, install ID rotates daily
- One-time opt-in dialog on first radio connection; toggle and status in
  App settings
- Local / Online / Both switch on the map screen with online repeater
  hexagons, links, add-to-contacts and manage
- Node purchase banner on the connect screen (affiliate link, disclosed)
- Privacy policy and network map documentation
- Translations for all locales
This commit is contained in:
zjs81 committed 2026-10-11 21:54:16 -07:00
1 parent d30744aa31
commit bc14de586f
68 files changed
+6719 -76

No files matched your search

@@ -0,0 +1,236 @@
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;
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,414 @@
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;
final appData = payload.sublist(appDataStart);
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,389 @@
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;
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) _queue.clear();
// 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;
_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,
);
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));
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) {
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));
}
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();
}
}