mirror of
https://github.com/dz0ny/meshcore-sar.git
synced 2026-08-11 16:30:28 +00:00
Compare commits
14 Commits
v2026.0402
...
v2026.0403
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d66bbca82c | ||
|
|
d2fee94678 | ||
|
|
61a856e84c | ||
|
|
5feb07aad7 | ||
|
|
59931f402a | ||
|
|
0cd563063a | ||
|
|
9244368b49 | ||
|
|
c089db5c62 | ||
|
|
7c1bc3b84f | ||
|
|
724f4b38e8 | ||
|
|
caefbdbcef | ||
|
|
79f8f8dd04 | ||
|
|
e4eb40cd34 | ||
|
|
7c9dfd6f63 |
6
.gitignore
vendored
6
.gitignore
vendored
@@ -79,9 +79,15 @@ play-store/
|
||||
create_feature_graphic.py
|
||||
|
||||
# Tool caches and local state
|
||||
.devenv/
|
||||
.cachebro/
|
||||
.osgrep/
|
||||
third_party/lpcnet_flutter/
|
||||
worker/node_modules/
|
||||
worker/.wrangler/
|
||||
worker/.bun/
|
||||
worker/.astro/
|
||||
worker/dist/
|
||||
|
||||
# Claude Code local settings (permissions, personal config)
|
||||
.claude/settings.local.json
|
||||
|
||||
@@ -489,7 +489,7 @@
|
||||
buildSettings = {
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CURRENT_PROJECT_VERSION = 129;
|
||||
CURRENT_PROJECT_VERSION = 131;
|
||||
DEVELOPMENT_TEAM = JND55328G8;
|
||||
ENABLE_BITCODE = NO;
|
||||
INFOPLIST_FILE = Runner/Info.plist;
|
||||
@@ -511,7 +511,7 @@
|
||||
buildSettings = {
|
||||
BUNDLE_LOADER = "$(TEST_HOST)";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 129;
|
||||
CURRENT_PROJECT_VERSION = 131;
|
||||
DEVELOPMENT_TEAM = JND55328G8;
|
||||
GENERATE_INFOPLIST_FILE = YES;
|
||||
MARKETING_VERSION = 1.0;
|
||||
@@ -530,7 +530,7 @@
|
||||
buildSettings = {
|
||||
BUNDLE_LOADER = "$(TEST_HOST)";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 129;
|
||||
CURRENT_PROJECT_VERSION = 131;
|
||||
DEVELOPMENT_TEAM = JND55328G8;
|
||||
GENERATE_INFOPLIST_FILE = YES;
|
||||
MARKETING_VERSION = 1.0;
|
||||
@@ -547,7 +547,7 @@
|
||||
buildSettings = {
|
||||
BUNDLE_LOADER = "$(TEST_HOST)";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 129;
|
||||
CURRENT_PROJECT_VERSION = 131;
|
||||
DEVELOPMENT_TEAM = JND55328G8;
|
||||
GENERATE_INFOPLIST_FILE = YES;
|
||||
MARKETING_VERSION = 1.0;
|
||||
@@ -679,7 +679,7 @@
|
||||
buildSettings = {
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CURRENT_PROJECT_VERSION = 129;
|
||||
CURRENT_PROJECT_VERSION = 131;
|
||||
DEVELOPMENT_TEAM = JND55328G8;
|
||||
ENABLE_BITCODE = NO;
|
||||
INFOPLIST_FILE = Runner/Info.plist;
|
||||
@@ -702,7 +702,7 @@
|
||||
buildSettings = {
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CURRENT_PROJECT_VERSION = 129;
|
||||
CURRENT_PROJECT_VERSION = 131;
|
||||
DEVELOPMENT_TEAM = JND55328G8;
|
||||
ENABLE_BITCODE = NO;
|
||||
INFOPLIST_FILE = Runner/Info.plist;
|
||||
|
||||
@@ -43,7 +43,7 @@
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>129</string>
|
||||
<string>131</string>
|
||||
<key>LSRequiresIPhoneOS</key>
|
||||
<true/>
|
||||
<key>ITSAppUsesNonExemptEncryption</key>
|
||||
|
||||
@@ -5,22 +5,22 @@
|
||||
|
||||
|
||||
|
||||
<testcase classname="fastlane.lanes" name="0: default_platform" time="0.000201">
|
||||
<testcase classname="fastlane.lanes" name="0: default_platform" time="0.000729">
|
||||
|
||||
</testcase>
|
||||
|
||||
|
||||
<testcase classname="fastlane.lanes" name="1: increment_build_number" time="0.700922">
|
||||
<testcase classname="fastlane.lanes" name="1: increment_build_number" time="1.008455">
|
||||
|
||||
</testcase>
|
||||
|
||||
|
||||
<testcase classname="fastlane.lanes" name="2: build_app" time="102.603385">
|
||||
<testcase classname="fastlane.lanes" name="2: build_app" time="224.694344">
|
||||
|
||||
</testcase>
|
||||
|
||||
|
||||
<testcase classname="fastlane.lanes" name="3: upload_to_app_store" time="2538.71069">
|
||||
<testcase classname="fastlane.lanes" name="3: upload_to_app_store" time="170.718455">
|
||||
|
||||
</testcase>
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ import '../services/messaging_route_preferences.dart';
|
||||
import '../services/nearest_router_selector.dart';
|
||||
import '../services/packet_capture_storage_service.dart';
|
||||
import '../services/path_history_service.dart';
|
||||
import '../services/traffic_stats_reporting_service.dart';
|
||||
import '../utils/rssi_location_estimator.dart';
|
||||
import '../services/profiles_feature_service.dart';
|
||||
import '../services/route_hash_preferences.dart';
|
||||
@@ -159,6 +160,8 @@ class AppProvider with ChangeNotifier {
|
||||
LocationTrackingService();
|
||||
final PacketCaptureStorageService packetCaptureStorageService =
|
||||
PacketCaptureStorageService();
|
||||
final TrafficStatsReportingService trafficStatsReportingService =
|
||||
TrafficStatsReportingService();
|
||||
final NotificationService _notificationService = NotificationService();
|
||||
|
||||
bool _isInitialized = false;
|
||||
@@ -264,6 +267,11 @@ class AppProvider with ChangeNotifier {
|
||||
_loadVoiceNoiseSuppressionEnabled();
|
||||
_loadMessageFontScale();
|
||||
_loadMessagingRouteSettings();
|
||||
unawaited(
|
||||
trafficStatsReportingService.initialize(
|
||||
deviceKey6Provider: _deviceKey6Hex,
|
||||
),
|
||||
);
|
||||
unawaited(_pathHistoryService.initialize());
|
||||
_startPacketCapturePersistence();
|
||||
_startLowBatteryWatcher();
|
||||
@@ -397,6 +405,7 @@ class AppProvider with ChangeNotifier {
|
||||
|
||||
if (toPersist.isNotEmpty) {
|
||||
await packetCaptureStorageService.appendLogs(toPersist);
|
||||
await trafficStatsReportingService.processLogs(toPersist);
|
||||
}
|
||||
_lastPersistedPacketSignature = _packetLogSignature(logs.last);
|
||||
} catch (e) {
|
||||
@@ -4135,6 +4144,7 @@ class AppProvider with ChangeNotifier {
|
||||
}
|
||||
_pendingChannelVoicePackets.clear();
|
||||
_pendingChannelImageFragments.clear();
|
||||
trafficStatsReportingService.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import 'package:crypto/crypto.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:geolocator/geolocator.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
import '../models/ble_packet_log.dart';
|
||||
import '../models/contact.dart';
|
||||
@@ -12,6 +13,7 @@ import '../providers/connection_provider.dart';
|
||||
import '../services/live_traffic_summary.dart';
|
||||
import '../services/location_tracking_service.dart';
|
||||
import '../services/route_hash_preferences.dart';
|
||||
import '../services/traffic_stats_reporting_service.dart';
|
||||
import '../utils/log_rx_route_decoder.dart';
|
||||
import '../widgets/compact_signal_indicator.dart';
|
||||
import '../widgets/messages/message_trace_sheet.dart';
|
||||
@@ -156,6 +158,11 @@ class _LiveTrafficScreenState extends State<LiveTrafficScreen> {
|
||||
tooltip: 'Open packet logs',
|
||||
icon: const Icon(Icons.list_alt_rounded),
|
||||
),
|
||||
IconButton(
|
||||
onPressed: _openStatsDashboard,
|
||||
tooltip: 'View public stats',
|
||||
icon: const Icon(Icons.open_in_new),
|
||||
),
|
||||
IconButton(
|
||||
onPressed: () => _showPacketTypeHelpSheet(context),
|
||||
tooltip: 'Packet type help',
|
||||
@@ -256,6 +263,13 @@ class _LiveTrafficScreenState extends State<LiveTrafficScreen> {
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _openStatsDashboard() async {
|
||||
final url = TrafficStatsReportingService.dashboardUri;
|
||||
if (await canLaunchUrl(url)) {
|
||||
await launchUrl(url, mode: LaunchMode.externalApplication);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _showWindowPicker(BuildContext context) async {
|
||||
final selected = await showModalBottomSheet<Duration>(
|
||||
context: context,
|
||||
|
||||
@@ -8,6 +8,7 @@ import '../providers/connection_provider.dart';
|
||||
import '../providers/contacts_provider.dart';
|
||||
import '../providers/map_provider.dart';
|
||||
import '../providers/sensors_provider.dart';
|
||||
import '../widgets/contacts/ping_contact_sheet.dart';
|
||||
import '../widgets/sensors/bthome_met_history_sheet.dart';
|
||||
import '../widgets/sensors/sensor_telemetry_card.dart';
|
||||
import '../l10n/app_localizations.dart';
|
||||
@@ -337,6 +338,7 @@ class _SensorsTabState extends State<SensorsTab> {
|
||||
child: SensorTelemetryCard(
|
||||
contact: contact,
|
||||
state: sensorsProvider.stateFor(key),
|
||||
showActionSheetOnTap: true,
|
||||
visibleFields: visibleFields,
|
||||
fieldOrder: sensorsProvider.metricOrderFor(
|
||||
key,
|
||||
@@ -369,6 +371,23 @@ class _SensorsTabState extends State<SensorsTab> {
|
||||
contactsProvider: contactsProvider,
|
||||
connectionProvider: connectionProvider,
|
||||
),
|
||||
onPing: contact == null
|
||||
? null
|
||||
: () async {
|
||||
await showModalBottomSheet<void>(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
backgroundColor:
|
||||
Theme.of(context).colorScheme.surface,
|
||||
shape: const RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.vertical(
|
||||
top: Radius.circular(16),
|
||||
),
|
||||
),
|
||||
builder: (context) =>
|
||||
PingContactSheet(contact: contact),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -38,6 +38,7 @@ import '../utils/voice_message_parser.dart';
|
||||
import '../theme/app_theme.dart';
|
||||
import '../l10n/app_localizations.dart';
|
||||
import '../widgets/update_dialog.dart';
|
||||
import '../widgets/settings/traffic_stats_reporting_section.dart';
|
||||
import 'sar_template_management_screen.dart';
|
||||
import 'profiles_screen.dart';
|
||||
import 'welcome_wizard_screen.dart';
|
||||
@@ -2162,6 +2163,14 @@ class _SettingsScreenState extends State<SettingsScreen> {
|
||||
),
|
||||
_buildSectionHeader('Developer & Data'),
|
||||
_buildSettingsCard([
|
||||
Consumer<AppProvider>(
|
||||
builder: (context, appProvider, child) => ListenableBuilder(
|
||||
listenable: appProvider.trafficStatsReportingService,
|
||||
builder: (context, child) => TrafficStatsReportingSection(
|
||||
service: appProvider.trafficStatsReportingService,
|
||||
),
|
||||
),
|
||||
),
|
||||
ListTile(
|
||||
leading: Icon(Icons.bug_report),
|
||||
title: Text(AppLocalizations.of(context)!.packageName),
|
||||
|
||||
@@ -11,34 +11,59 @@ import '../utils/log_rx_route_decoder.dart';
|
||||
|
||||
class PathHistoryService {
|
||||
static const String _storageKey = 'contact_path_history_v2';
|
||||
static const String _suppressedRouteStorageKey =
|
||||
'contact_path_history_suppressed_routes_v1';
|
||||
static const int _maxDirectPaths = 20;
|
||||
static const int _topRotationCount = 3;
|
||||
|
||||
final Map<String, ContactPathHistory> _cache = {};
|
||||
final Map<String, String> _suppressedCurrentRoutes = {};
|
||||
bool _isLoaded = false;
|
||||
|
||||
Future<void> initialize() async {
|
||||
if (_isLoaded) return;
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final raw = prefs.getString(_storageKey);
|
||||
final suppressedRaw = prefs.getString(_suppressedRouteStorageKey);
|
||||
if (raw == null || raw.isEmpty) {
|
||||
_isLoaded = true;
|
||||
return;
|
||||
if (suppressedRaw == null || suppressedRaw.isEmpty) {
|
||||
_isLoaded = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
final decoded = jsonDecode(raw);
|
||||
if (decoded is Map<String, dynamic>) {
|
||||
for (final entry in decoded.entries) {
|
||||
final value = entry.value;
|
||||
if (value is Map<String, dynamic>) {
|
||||
_cache[entry.key] = ContactPathHistory.fromJson(entry.key, value);
|
||||
if (raw != null && raw.isNotEmpty) {
|
||||
final decoded = jsonDecode(raw);
|
||||
if (decoded is Map<String, dynamic>) {
|
||||
for (final entry in decoded.entries) {
|
||||
final value = entry.value;
|
||||
if (value is Map<String, dynamic>) {
|
||||
_cache[entry.key] = ContactPathHistory.fromJson(entry.key, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
debugPrint('⚠️ [PathHistoryService] Failed to load history: $error');
|
||||
}
|
||||
try {
|
||||
if (suppressedRaw != null && suppressedRaw.isNotEmpty) {
|
||||
final decoded = jsonDecode(suppressedRaw);
|
||||
if (decoded is Map<String, dynamic>) {
|
||||
for (final entry in decoded.entries) {
|
||||
final value = entry.value;
|
||||
if (value is String && value.isNotEmpty) {
|
||||
_suppressedCurrentRoutes[entry.key] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
debugPrint(
|
||||
'⚠️ [PathHistoryService] Failed to load suppressed routes: $error',
|
||||
);
|
||||
}
|
||||
_isLoaded = true;
|
||||
}
|
||||
|
||||
@@ -50,6 +75,9 @@ class PathHistoryService {
|
||||
|
||||
final history = _historyFor(contact.publicKeyHex);
|
||||
final signature = _signature(contact.routePathBytes);
|
||||
if (_suppressedCurrentRoutes[contact.publicKeyHex] == signature) {
|
||||
return;
|
||||
}
|
||||
final existing = _findDirectPath(history.directPaths, signature);
|
||||
final updated = PathRecord(
|
||||
pathBytes: contact.routePathBytes.toList(),
|
||||
@@ -100,6 +128,10 @@ class PathHistoryService {
|
||||
final signature = normalizedPathBytes
|
||||
.map((byte) => byte.toRadixString(16).padLeft(2, '0'))
|
||||
.join();
|
||||
_clearSuppressedRoute(
|
||||
contactPublicKeyHex,
|
||||
signature: signature,
|
||||
);
|
||||
final existing = _findDirectPath(history.directPaths, signature);
|
||||
final updated = PathRecord(
|
||||
pathBytes: normalizedPathBytes,
|
||||
@@ -209,12 +241,18 @@ class PathHistoryService {
|
||||
}
|
||||
|
||||
final signature = _signature(selection.pathBytes);
|
||||
_clearSuppressedRoute(
|
||||
contactPublicKeyHex,
|
||||
signature: signature,
|
||||
);
|
||||
final existing = _findDirectPath(history.directPaths, signature);
|
||||
final updated = PathRecord(
|
||||
pathBytes: selection.pathBytes.toList(),
|
||||
hopCount: selection.hopCount,
|
||||
hashSize: selection.hashSize,
|
||||
source: existing?.source ?? PathRecordSource.learned,
|
||||
source: success
|
||||
? PathRecordSource.learned
|
||||
: existing?.source ?? PathRecordSource.learned,
|
||||
successCount: (existing?.successCount ?? 0) + (success ? 1 : 0),
|
||||
failureCount: (existing?.failureCount ?? 0) + (success ? 0 : 1),
|
||||
lastRoundTripTimeMs: success
|
||||
@@ -293,12 +331,21 @@ class PathHistoryService {
|
||||
Future<void> clearHistoryFor(String contactPublicKeyHex) async {
|
||||
await initialize();
|
||||
_cache.remove(contactPublicKeyHex);
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final payload = <String, dynamic>{};
|
||||
for (final entry in _cache.entries) {
|
||||
payload[entry.key] = entry.value.toJson();
|
||||
_suppressedCurrentRoutes.remove(contactPublicKeyHex);
|
||||
await _persistState();
|
||||
}
|
||||
|
||||
Future<void> clearHistoryForContact(Contact contact) async {
|
||||
await initialize();
|
||||
_cache.remove(contact.publicKeyHex);
|
||||
if (contact.routeHasPath && contact.routeHopCount > 0) {
|
||||
_suppressedCurrentRoutes[contact.publicKeyHex] = _signature(
|
||||
contact.routePathBytes,
|
||||
);
|
||||
} else {
|
||||
_suppressedCurrentRoutes.remove(contact.publicKeyHex);
|
||||
}
|
||||
await prefs.setString(_storageKey, jsonEncode(payload));
|
||||
await _persistState();
|
||||
}
|
||||
|
||||
ContactPathHistory _historyFor(String contactPublicKeyHex) {
|
||||
@@ -313,12 +360,34 @@ class PathHistoryService {
|
||||
ContactPathHistory history,
|
||||
) async {
|
||||
_cache[contactPublicKeyHex] = history;
|
||||
await _persistState();
|
||||
}
|
||||
|
||||
void _clearSuppressedRoute(String contactPublicKeyHex, {String? signature}) {
|
||||
final suppressedSignature = _suppressedCurrentRoutes[contactPublicKeyHex];
|
||||
if (suppressedSignature == null) {
|
||||
return;
|
||||
}
|
||||
if (signature == null || suppressedSignature == signature) {
|
||||
_suppressedCurrentRoutes.remove(contactPublicKeyHex);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _persistState() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final payload = <String, dynamic>{};
|
||||
for (final entry in _cache.entries) {
|
||||
payload[entry.key] = entry.value.toJson();
|
||||
}
|
||||
final suppressedPayload = <String, dynamic>{};
|
||||
for (final entry in _suppressedCurrentRoutes.entries) {
|
||||
suppressedPayload[entry.key] = entry.value;
|
||||
}
|
||||
await prefs.setString(_storageKey, jsonEncode(payload));
|
||||
await prefs.setString(
|
||||
_suppressedRouteStorageKey,
|
||||
jsonEncode(suppressedPayload),
|
||||
);
|
||||
}
|
||||
|
||||
List<PathRecord> _upsertDirectPath(
|
||||
|
||||
508
lib/services/traffic_stats_reporting_service.dart
Normal file
508
lib/services/traffic_stats_reporting_service.dart
Normal file
@@ -0,0 +1,508 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
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 '../models/ble_packet_log.dart';
|
||||
import '../utils/log_rx_route_decoder.dart';
|
||||
import 'live_traffic_summary.dart';
|
||||
|
||||
class TrafficStatsCounts {
|
||||
static const List<String> packetTypeKeys = <String>[
|
||||
'pt_00',
|
||||
'pt_01',
|
||||
'pt_02',
|
||||
'pt_03',
|
||||
'pt_04',
|
||||
'pt_05',
|
||||
'pt_06',
|
||||
'pt_07',
|
||||
'pt_08',
|
||||
'pt_09',
|
||||
'pt_0a',
|
||||
'pt_0b',
|
||||
'pt_0c',
|
||||
'pt_0d',
|
||||
'pt_0e',
|
||||
'pt_0f',
|
||||
];
|
||||
static const List<String> pathModeKeys = <String>[
|
||||
'path_mode_1b',
|
||||
'path_mode_2b',
|
||||
'path_mode_3b',
|
||||
'path_mode_none',
|
||||
'path_mode_unknown',
|
||||
];
|
||||
static const String decodeFailKey = 'decode_fail';
|
||||
static const List<String> allKeys = <String>[
|
||||
...packetTypeKeys,
|
||||
decodeFailKey,
|
||||
...pathModeKeys,
|
||||
];
|
||||
|
||||
final Map<String, int> _values;
|
||||
|
||||
TrafficStatsCounts._(this._values);
|
||||
|
||||
factory TrafficStatsCounts.empty() {
|
||||
return TrafficStatsCounts._(
|
||||
<String, int>{for (final key in allKeys) key: 0},
|
||||
);
|
||||
}
|
||||
|
||||
factory TrafficStatsCounts.fromJson(Map<String, dynamic>? json) {
|
||||
final counts = TrafficStatsCounts.empty();
|
||||
if (json == null) {
|
||||
return counts;
|
||||
}
|
||||
for (final key in allKeys) {
|
||||
counts._values[key] = (json[key] as num?)?.toInt() ?? 0;
|
||||
}
|
||||
return counts;
|
||||
}
|
||||
|
||||
int operator [](String key) => _values[key] ?? 0;
|
||||
|
||||
bool get isEmpty => _values.values.every((value) => value == 0);
|
||||
|
||||
Map<String, int> toJson() {
|
||||
return <String, int>{
|
||||
for (final key in allKeys) key: _values[key] ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
void increment(String key, [int amount = 1]) {
|
||||
_values[key] = (_values[key] ?? 0) + amount;
|
||||
}
|
||||
|
||||
void incrementPacketType(int payloadType) {
|
||||
if (payloadType < 0 || payloadType > 0x0F) {
|
||||
increment(decodeFailKey);
|
||||
return;
|
||||
}
|
||||
increment('pt_${payloadType.toRadixString(16).padLeft(2, '0')}');
|
||||
}
|
||||
|
||||
void mergeFrom(TrafficStatsCounts other) {
|
||||
for (final key in allKeys) {
|
||||
increment(key, other[key]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class TrafficStatsQueuedReport {
|
||||
final String reportId;
|
||||
final String deviceKey6;
|
||||
final DateTime windowStart;
|
||||
final DateTime windowEnd;
|
||||
final String appVersion;
|
||||
final TrafficStatsCounts counts;
|
||||
|
||||
const TrafficStatsQueuedReport({
|
||||
required this.reportId,
|
||||
required this.deviceKey6,
|
||||
required this.windowStart,
|
||||
required this.windowEnd,
|
||||
required this.appVersion,
|
||||
required this.counts,
|
||||
});
|
||||
|
||||
factory TrafficStatsQueuedReport.fromJson(Map<String, dynamic> json) {
|
||||
return TrafficStatsQueuedReport(
|
||||
reportId: (json['reportId'] as String?) ?? '',
|
||||
deviceKey6: (json['deviceKey6'] as String?) ?? '',
|
||||
windowStart: DateTime.parse(json['windowStart'] as String).toUtc(),
|
||||
windowEnd: DateTime.parse(json['windowEnd'] as String).toUtc(),
|
||||
appVersion: (json['appVersion'] as String?) ?? 'unknown',
|
||||
counts: TrafficStatsCounts.fromJson(
|
||||
json['counts'] as Map<String, dynamic>?,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return <String, dynamic>{
|
||||
'reportId': reportId,
|
||||
'deviceKey6': deviceKey6,
|
||||
'windowStart': windowStart.toIso8601String(),
|
||||
'windowEnd': windowEnd.toIso8601String(),
|
||||
'appVersion': appVersion,
|
||||
'counts': counts.toJson(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class TrafficStatsReportingService extends ChangeNotifier {
|
||||
static const String workerBaseUrl = 'https://mcstats.dz0ny.dev';
|
||||
static final Uri dashboardUri = Uri.parse(workerBaseUrl);
|
||||
static final Uri ingestUri = Uri.parse('$workerBaseUrl/api/ingest');
|
||||
|
||||
static const bool defaultEnabled = true;
|
||||
static const int defaultIntervalMinutes = 5;
|
||||
static const String _enabledKey = 'traffic_stats_reporting_enabled';
|
||||
static const String _legacyIntervalKey =
|
||||
'traffic_stats_reporting_interval_minutes';
|
||||
static const String _queueKey = 'traffic_stats_reporting_queue';
|
||||
static const String _lastSuccessAtKey =
|
||||
'traffic_stats_reporting_last_success_at';
|
||||
static const String _lastErrorKey = 'traffic_stats_reporting_last_error';
|
||||
static const Duration _retryInterval = Duration(seconds: 30);
|
||||
|
||||
final http.Client _client;
|
||||
final bool _ownsClient;
|
||||
final DateTime Function() _now;
|
||||
final Future<SharedPreferences> Function() _prefsProvider;
|
||||
final Future<String> Function() _appVersionProvider;
|
||||
final Map<int, TrafficStatsCounts> _openWindows =
|
||||
<int, TrafficStatsCounts>{};
|
||||
final List<TrafficStatsQueuedReport> _queue = <TrafficStatsQueuedReport>[];
|
||||
|
||||
String? Function()? _deviceKey6Provider;
|
||||
Timer? _retryTimer;
|
||||
String? _appVersion;
|
||||
bool _enabled = defaultEnabled;
|
||||
DateTime? _lastSuccessAt;
|
||||
String? _lastError;
|
||||
bool _isInitialized = false;
|
||||
bool _isFlushingQueue = false;
|
||||
|
||||
TrafficStatsReportingService({
|
||||
http.Client? client,
|
||||
DateTime Function()? now,
|
||||
Future<SharedPreferences> Function()? prefsProvider,
|
||||
Future<String> Function()? appVersionProvider,
|
||||
}) : _client = client ?? http.Client(),
|
||||
_ownsClient = client == null,
|
||||
_now = now ?? DateTime.now,
|
||||
_prefsProvider = prefsProvider ?? SharedPreferences.getInstance,
|
||||
_appVersionProvider = appVersionProvider ?? _defaultAppVersionProvider;
|
||||
|
||||
bool get isEnabled => _enabled;
|
||||
int get intervalMinutes => defaultIntervalMinutes;
|
||||
DateTime? get lastSuccessAt => _lastSuccessAt;
|
||||
String? get lastError => _lastError;
|
||||
bool get isInitialized => _isInitialized;
|
||||
bool get isFlushingQueue => _isFlushingQueue;
|
||||
int get pendingUploadCount => _queue.length;
|
||||
|
||||
Future<void> initialize({
|
||||
required String? Function() deviceKey6Provider,
|
||||
}) async {
|
||||
_deviceKey6Provider = deviceKey6Provider;
|
||||
final prefs = await _prefsProvider();
|
||||
_enabled = prefs.getBool(_enabledKey) ?? defaultEnabled;
|
||||
if (prefs.containsKey(_legacyIntervalKey)) {
|
||||
await prefs.remove(_legacyIntervalKey);
|
||||
}
|
||||
final queueJson = prefs.getString(_queueKey);
|
||||
if (queueJson != null && queueJson.isNotEmpty) {
|
||||
final decoded = jsonDecode(queueJson);
|
||||
if (decoded is List) {
|
||||
_queue
|
||||
..clear()
|
||||
..addAll(
|
||||
decoded.whereType<Map<String, dynamic>>().map(
|
||||
TrafficStatsQueuedReport.fromJson,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
final lastSuccessAt = prefs.getString(_lastSuccessAtKey);
|
||||
if (lastSuccessAt != null && lastSuccessAt.isNotEmpty) {
|
||||
_lastSuccessAt = DateTime.tryParse(lastSuccessAt)?.toUtc();
|
||||
}
|
||||
final lastError = prefs.getString(_lastErrorKey);
|
||||
if (lastError != null && lastError.isNotEmpty) {
|
||||
_lastError = lastError;
|
||||
}
|
||||
try {
|
||||
_appVersion = await _appVersionProvider();
|
||||
} catch (_) {
|
||||
_appVersion = 'unknown';
|
||||
}
|
||||
_retryTimer?.cancel();
|
||||
_retryTimer = Timer.periodic(_retryInterval, (_) {
|
||||
unawaited(flushPendingUploads());
|
||||
});
|
||||
_isInitialized = true;
|
||||
notifyListeners();
|
||||
await flushPendingUploads();
|
||||
}
|
||||
|
||||
Future<void> setEnabled(bool enabled) async {
|
||||
if (_enabled == enabled) {
|
||||
return;
|
||||
}
|
||||
_enabled = enabled;
|
||||
_lastError = null;
|
||||
if (!enabled) {
|
||||
_openWindows.clear();
|
||||
}
|
||||
await _saveState();
|
||||
notifyListeners();
|
||||
if (enabled) {
|
||||
unawaited(flushPendingUploads());
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> processLogs(List<BlePacketLog> logs) async {
|
||||
if (!_enabled || logs.isEmpty) {
|
||||
if (_enabled) {
|
||||
await flushPendingUploads();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
var changed = false;
|
||||
for (final log in logs) {
|
||||
if (!LiveTrafficSummary.isRxDataLog(log)) {
|
||||
continue;
|
||||
}
|
||||
final counts = _openWindows.putIfAbsent(
|
||||
_windowStartFor(log.timestamp).millisecondsSinceEpoch,
|
||||
TrafficStatsCounts.empty,
|
||||
);
|
||||
final route = LogRxRouteDecoder.decode(log.rawData);
|
||||
if (route == null) {
|
||||
counts.increment(TrafficStatsCounts.decodeFailKey);
|
||||
} else {
|
||||
counts.incrementPacketType(route.payloadType);
|
||||
}
|
||||
counts.increment(_pathModeKeyFor(log.rawData, route));
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if (!changed) {
|
||||
await flushPendingUploads();
|
||||
return;
|
||||
}
|
||||
|
||||
final queuedReports = _queueClosedWindows();
|
||||
if (queuedReports > 0) {
|
||||
await _saveState();
|
||||
}
|
||||
notifyListeners();
|
||||
await flushPendingUploads();
|
||||
}
|
||||
|
||||
Future<void> flushPendingUploads() async {
|
||||
if (!_enabled || _queue.isEmpty || _isFlushingQueue) {
|
||||
return;
|
||||
}
|
||||
final deviceKey6 = _deviceKey6Provider?.call();
|
||||
if (deviceKey6 == null || deviceKey6.isEmpty) {
|
||||
return;
|
||||
}
|
||||
|
||||
_isFlushingQueue = true;
|
||||
notifyListeners();
|
||||
try {
|
||||
while (_queue.isNotEmpty && _enabled) {
|
||||
final report = _queue.first;
|
||||
final response = await _client.post(
|
||||
ingestUri,
|
||||
headers: const <String, String>{
|
||||
'content-type': 'application/json',
|
||||
},
|
||||
body: jsonEncode(report.toJson()),
|
||||
);
|
||||
|
||||
if (response.statusCode < 200 || response.statusCode >= 300) {
|
||||
_lastError = 'Upload failed (${response.statusCode})';
|
||||
await _saveState();
|
||||
notifyListeners();
|
||||
return;
|
||||
}
|
||||
|
||||
_queue.removeAt(0);
|
||||
_lastError = null;
|
||||
_lastSuccessAt = _now().toUtc();
|
||||
await _saveState();
|
||||
notifyListeners();
|
||||
}
|
||||
} catch (error) {
|
||||
_lastError = 'Upload failed: $error';
|
||||
await _saveState();
|
||||
notifyListeners();
|
||||
} finally {
|
||||
_isFlushingQueue = false;
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
int _queueClosedWindows() {
|
||||
final deviceKey6 = _deviceKey6Provider?.call();
|
||||
if (deviceKey6 == null || deviceKey6.isEmpty) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
final now = _now().toUtc();
|
||||
final closable = _openWindows.keys
|
||||
.where((windowStartMs) {
|
||||
final windowStart = DateTime.fromMillisecondsSinceEpoch(
|
||||
windowStartMs,
|
||||
isUtc: true,
|
||||
);
|
||||
final windowEnd = windowStart.add(
|
||||
Duration(minutes: defaultIntervalMinutes),
|
||||
);
|
||||
return !windowEnd.isAfter(now);
|
||||
})
|
||||
.toList()
|
||||
..sort();
|
||||
|
||||
for (final windowStartMs in closable) {
|
||||
final windowStart = DateTime.fromMillisecondsSinceEpoch(
|
||||
windowStartMs,
|
||||
isUtc: true,
|
||||
);
|
||||
final counts = _openWindows.remove(windowStartMs);
|
||||
if (counts == null || counts.isEmpty) {
|
||||
continue;
|
||||
}
|
||||
final reportId = '$deviceKey6:${windowStart.toIso8601String()}';
|
||||
final existingIndex = _queue.indexWhere(
|
||||
(report) => report.reportId == reportId,
|
||||
);
|
||||
if (existingIndex != -1) {
|
||||
_queue[existingIndex].counts.mergeFrom(counts);
|
||||
continue;
|
||||
}
|
||||
_queue.add(
|
||||
TrafficStatsQueuedReport(
|
||||
reportId: reportId,
|
||||
deviceKey6: deviceKey6,
|
||||
windowStart: windowStart,
|
||||
windowEnd: windowStart.add(
|
||||
Duration(minutes: defaultIntervalMinutes),
|
||||
),
|
||||
appVersion: _appVersion ?? 'unknown',
|
||||
counts: counts,
|
||||
),
|
||||
);
|
||||
}
|
||||
return closable.length;
|
||||
}
|
||||
|
||||
DateTime _windowStartFor(DateTime timestamp) {
|
||||
final utc = timestamp.toUtc();
|
||||
final alignedMinute =
|
||||
utc.minute - (utc.minute % defaultIntervalMinutes);
|
||||
return DateTime.utc(
|
||||
utc.year,
|
||||
utc.month,
|
||||
utc.day,
|
||||
utc.hour,
|
||||
alignedMinute,
|
||||
);
|
||||
}
|
||||
|
||||
String _pathModeKeyFor(Uint8List rawData, DecodedLogRxRoute? route) {
|
||||
if (route != null) {
|
||||
if (route.pathBytes.isEmpty) {
|
||||
return 'path_mode_none';
|
||||
}
|
||||
switch (route.hashSize) {
|
||||
case 1:
|
||||
return 'path_mode_1b';
|
||||
case 2:
|
||||
return 'path_mode_2b';
|
||||
case 3:
|
||||
return 'path_mode_3b';
|
||||
}
|
||||
return 'path_mode_unknown';
|
||||
}
|
||||
return _pathModeKeyFromRawData(rawData);
|
||||
}
|
||||
|
||||
String _pathModeKeyFromRawData(Uint8List rawData) {
|
||||
if (rawData.length < 5 ||
|
||||
rawData.first != LiveTrafficSummary.logRxDataResponseCode) {
|
||||
return 'path_mode_unknown';
|
||||
}
|
||||
|
||||
final rawPacketData = rawData.sublist(3);
|
||||
if (rawPacketData.length < 2) {
|
||||
return 'path_mode_unknown';
|
||||
}
|
||||
|
||||
final header = rawPacketData[0];
|
||||
final routeType = header & 0x03;
|
||||
var index = 1;
|
||||
if (routeType == 0x00 || routeType == 0x03) {
|
||||
if (rawPacketData.length < index + 5) {
|
||||
return 'path_mode_unknown';
|
||||
}
|
||||
index += 4;
|
||||
}
|
||||
|
||||
if (rawPacketData.length <= index) {
|
||||
return 'path_mode_unknown';
|
||||
}
|
||||
|
||||
final pathDescriptor = rawPacketData[index];
|
||||
final pathByteLen = LogRxRouteDecoder.descriptorByteLength(pathDescriptor);
|
||||
if (pathByteLen == null) {
|
||||
return 'path_mode_unknown';
|
||||
}
|
||||
if (rawPacketData.length < index + 1 + pathByteLen) {
|
||||
return 'path_mode_unknown';
|
||||
}
|
||||
if (pathByteLen == 0) {
|
||||
return 'path_mode_none';
|
||||
}
|
||||
|
||||
final hashSize = LogRxRouteDecoder.descriptorHashSize(pathDescriptor);
|
||||
switch (hashSize) {
|
||||
case 1:
|
||||
return 'path_mode_1b';
|
||||
case 2:
|
||||
return 'path_mode_2b';
|
||||
case 3:
|
||||
return 'path_mode_3b';
|
||||
}
|
||||
return 'path_mode_unknown';
|
||||
}
|
||||
|
||||
Future<void> _saveState() async {
|
||||
final prefs = await _prefsProvider();
|
||||
await prefs.setBool(_enabledKey, _enabled);
|
||||
await prefs.remove(_legacyIntervalKey);
|
||||
await prefs.setString(
|
||||
_queueKey,
|
||||
jsonEncode(_queue.map((report) => report.toJson()).toList()),
|
||||
);
|
||||
if (_lastSuccessAt == null) {
|
||||
await prefs.remove(_lastSuccessAtKey);
|
||||
} else {
|
||||
await prefs.setString(
|
||||
_lastSuccessAtKey,
|
||||
_lastSuccessAt!.toIso8601String(),
|
||||
);
|
||||
}
|
||||
if (_lastError == null || _lastError!.isEmpty) {
|
||||
await prefs.remove(_lastErrorKey);
|
||||
} else {
|
||||
await prefs.setString(_lastErrorKey, _lastError!);
|
||||
}
|
||||
}
|
||||
|
||||
static Future<String> _defaultAppVersionProvider() async {
|
||||
final info = await PackageInfo.fromPlatform();
|
||||
if (info.buildNumber.isEmpty || info.buildNumber == '0') {
|
||||
return info.version;
|
||||
}
|
||||
return '${info.version}+${info.buildNumber}';
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_retryTimer?.cancel();
|
||||
if (_ownsClient) {
|
||||
_client.close();
|
||||
}
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -721,9 +721,7 @@ class _ContactRouteDialogState extends State<ContactRouteDialog> {
|
||||
alignment: Alignment.centerRight,
|
||||
child: TextButton(
|
||||
onPressed: () async {
|
||||
await _pathHistoryService.clearHistoryFor(
|
||||
widget.contact.publicKeyHex,
|
||||
);
|
||||
await _pathHistoryService.clearHistoryForContact(widget.contact);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_pathHistory = _pathHistoryService.historyFor(
|
||||
|
||||
@@ -13,7 +13,9 @@ import '../../providers/messages_provider.dart';
|
||||
import '../../providers/sensors_provider.dart';
|
||||
import '../../services/location_tracking_service.dart';
|
||||
import '../../services/message_destination_preferences.dart';
|
||||
import '../../services/path_history_service.dart';
|
||||
import 'contact_route_dialog.dart';
|
||||
import 'ping_contact_sheet.dart';
|
||||
import 'contact_trace_sheet.dart';
|
||||
import 'room_login_sheet.dart';
|
||||
import '../common/contact_avatar.dart';
|
||||
@@ -683,7 +685,7 @@ class ContactTile extends StatelessWidget {
|
||||
shape: const RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
|
||||
),
|
||||
builder: (context) => _PingRelaySheet(contact: contact),
|
||||
builder: (context) => PingContactSheet(contact: contact),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -786,6 +788,7 @@ class ContactTile extends StatelessWidget {
|
||||
) async {
|
||||
final contactsProvider = context.read<ContactsProvider>();
|
||||
final connectionProvider = context.read<ConnectionProvider>();
|
||||
final pathHistoryService = PathHistoryService();
|
||||
final availableContacts = contactsProvider.contacts
|
||||
.where((candidate) => candidate.publicKeyHex != contact.publicKeyHex)
|
||||
.toList();
|
||||
@@ -846,6 +849,12 @@ class ContactTile extends StatelessWidget {
|
||||
signedEncodedPathLen: parsedRoute.signedEncodedPathLen,
|
||||
paddedPathBytes: parsedRoute.paddedPathBytes,
|
||||
);
|
||||
await pathHistoryService.clearHistoryForContact(
|
||||
contact.copyWith(
|
||||
outPathLen: parsedRoute.signedEncodedPathLen,
|
||||
outPath: Uint8List.fromList(parsedRoute.paddedPathBytes),
|
||||
),
|
||||
);
|
||||
if (context.mounted) {
|
||||
final routeLabel = parsedRoute.hopCount == 0
|
||||
? AppLocalizations.of(context)!.direct
|
||||
|
||||
638
lib/widgets/contacts/ping_contact_sheet.dart
Normal file
638
lib/widgets/contacts/ping_contact_sheet.dart
Normal file
@@ -0,0 +1,638 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
import 'dart:math' as math;
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:audioplayers/audioplayers.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:geolocator/geolocator.dart';
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
|
||||
import '../../models/contact.dart';
|
||||
import '../../providers/connection_provider.dart';
|
||||
import '../../services/location_tracking_service.dart';
|
||||
import '../../utils/link_quality.dart';
|
||||
import '../../utils/time_ago_extensions.dart';
|
||||
|
||||
class PingContactSheet extends StatefulWidget {
|
||||
final Contact contact;
|
||||
|
||||
const PingContactSheet({super.key, required this.contact});
|
||||
|
||||
@override
|
||||
State<PingContactSheet> createState() => _PingContactSheetState();
|
||||
}
|
||||
|
||||
class _PingEntry {
|
||||
final RelayPingResult result;
|
||||
final DateTime timestamp;
|
||||
final String? distance;
|
||||
|
||||
const _PingEntry({
|
||||
required this.result,
|
||||
required this.timestamp,
|
||||
this.distance,
|
||||
});
|
||||
}
|
||||
|
||||
class _PingContactSheetState extends State<PingContactSheet> {
|
||||
static const Duration _autoPingInterval = Duration(seconds: 2);
|
||||
static const Duration _maxAutoPingDelay = Duration(seconds: 5);
|
||||
static const int _maxHistoryEntries = 24;
|
||||
static const double _maxHistoryHeight = 320;
|
||||
static const Duration _timeoutPenalty = Duration(seconds: 10);
|
||||
|
||||
bool _pinging = false;
|
||||
bool _autoPingEnabled = false;
|
||||
final List<_PingEntry> _history = [];
|
||||
final _PingCuePlayer _cuePlayer = _PingCuePlayer();
|
||||
Timer? _autoPingTimer;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_doPing();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_autoPingTimer?.cancel();
|
||||
_cuePlayer.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _doPing() async {
|
||||
if (_pinging) {
|
||||
return;
|
||||
}
|
||||
setState(() => _pinging = true);
|
||||
final connectionProvider = context.read<ConnectionProvider>();
|
||||
final distance = _distanceText();
|
||||
final result = await connectionProvider.pingRelay(widget.contact);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_pinging = false;
|
||||
_history.insert(
|
||||
0,
|
||||
_PingEntry(
|
||||
result: result,
|
||||
timestamp: DateTime.now(),
|
||||
distance: distance,
|
||||
),
|
||||
);
|
||||
if (_history.length > _maxHistoryEntries) {
|
||||
_history.removeRange(_maxHistoryEntries, _history.length);
|
||||
}
|
||||
});
|
||||
await _maybePlayCue(result);
|
||||
_scheduleNextAutoPing(result);
|
||||
}
|
||||
|
||||
Future<void> _maybePlayCue(RelayPingResult result) async {
|
||||
if (!_autoPingEnabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
final previous = _history.length >= 2 ? _history[1].result : null;
|
||||
await _cuePlayer.playCue(result, previous: previous);
|
||||
}
|
||||
|
||||
void _setAutoPingEnabled(bool enabled) {
|
||||
setState(() {
|
||||
_autoPingEnabled = enabled;
|
||||
});
|
||||
_autoPingTimer?.cancel();
|
||||
if (!enabled) {
|
||||
return;
|
||||
}
|
||||
_scheduleNextAutoPing();
|
||||
}
|
||||
|
||||
void _scheduleNextAutoPing([RelayPingResult? result]) {
|
||||
_autoPingTimer?.cancel();
|
||||
if (!_autoPingEnabled || !mounted) {
|
||||
return;
|
||||
}
|
||||
final responseDelay = result == null
|
||||
? Duration.zero
|
||||
: result.success
|
||||
? Duration(milliseconds: result.durationMs)
|
||||
: _timeoutPenalty;
|
||||
final nextDelay = _autoPingInterval + responseDelay;
|
||||
final clampedDelay = nextDelay > _maxAutoPingDelay
|
||||
? _maxAutoPingDelay
|
||||
: nextDelay;
|
||||
_autoPingTimer = Timer(clampedDelay, () {
|
||||
unawaited(_doPing());
|
||||
});
|
||||
}
|
||||
|
||||
String? _distanceText() {
|
||||
final location = widget.contact.displayLocation;
|
||||
if (location == null) return null;
|
||||
final currentPosition = LocationTrackingService().currentPosition;
|
||||
if (currentPosition == null) return null;
|
||||
final meters = Geolocator.distanceBetween(
|
||||
currentPosition.latitude,
|
||||
currentPosition.longitude,
|
||||
location.latitude,
|
||||
location.longitude,
|
||||
);
|
||||
if (meters < 1000) return '${meters.round()} m';
|
||||
if (meters < 10000) return '${(meters / 1000).toStringAsFixed(2)} km';
|
||||
return '${(meters / 1000).toStringAsFixed(1)} km';
|
||||
}
|
||||
|
||||
Widget _buildPill(
|
||||
BuildContext context, {
|
||||
required IconData icon,
|
||||
required String label,
|
||||
Color? iconColor,
|
||||
}) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.surfaceContainerHighest.withValues(alpha: 0.75),
|
||||
borderRadius: BorderRadius.circular(999),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(icon, size: 12, color: iconColor ?? colorScheme.onSurfaceVariant),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
label,
|
||||
style: Theme.of(context).textTheme.labelSmall?.copyWith(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildSnrPill(BuildContext context, String direction, double snrDb) {
|
||||
final quality = linkQualityLabel(null, snrDb);
|
||||
final color = linkQualityColor(quality);
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: color.withValues(alpha: 0.15),
|
||||
borderRadius: BorderRadius.circular(999),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
direction == 'there'
|
||||
? Icons.arrow_upward_rounded
|
||||
: Icons.arrow_downward_rounded,
|
||||
size: 12,
|
||||
color: color,
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
'${snrDb.toStringAsFixed(1)} dB',
|
||||
style: Theme.of(context).textTheme.labelSmall?.copyWith(
|
||||
color: color,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildResultRow(BuildContext context, _PingEntry entry, int seq) {
|
||||
final theme = Theme.of(context);
|
||||
final colorScheme = theme.colorScheme;
|
||||
final r = entry.result;
|
||||
final age = DateTime.now().difference(entry.timestamp);
|
||||
final timeAgo = age.toLocalizedTimeAgoWithSeconds(context);
|
||||
|
||||
if (!r.success) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
child: Row(
|
||||
children: [
|
||||
CircleAvatar(
|
||||
radius: 12,
|
||||
backgroundColor: colorScheme.error.withValues(alpha: 0.15),
|
||||
child: Text(
|
||||
'$seq',
|
||||
style: TextStyle(
|
||||
color: colorScheme.error,
|
||||
fontSize: 10,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Text(
|
||||
'Timeout',
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: colorScheme.error,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
Text(
|
||||
timeAgo,
|
||||
style: theme.textTheme.labelSmall?.copyWith(
|
||||
color: colorScheme.onSurfaceVariant.withValues(alpha: 0.6),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 6),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
CircleAvatar(
|
||||
radius: 12,
|
||||
backgroundColor: colorScheme.surfaceContainerHighest,
|
||||
child: Text(
|
||||
'$seq',
|
||||
style: TextStyle(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
fontSize: 10,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
_buildPill(
|
||||
context,
|
||||
icon: Icons.timer_outlined,
|
||||
label: '${r.durationMs} ms',
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
_buildSnrPill(context, 'there', r.snrThere),
|
||||
const SizedBox(width: 6),
|
||||
_buildSnrPill(context, 'back', r.snrBack),
|
||||
const Spacer(),
|
||||
Text(
|
||||
timeAgo,
|
||||
style: theme.textTheme.labelSmall?.copyWith(
|
||||
color: colorScheme.onSurfaceVariant.withValues(alpha: 0.6),
|
||||
fontSize: 10,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(left: 34, top: 4),
|
||||
child: Row(
|
||||
children: [
|
||||
if (entry.distance != null) ...[
|
||||
Icon(
|
||||
Icons.straighten,
|
||||
size: 10,
|
||||
color: colorScheme.onSurfaceVariant.withValues(alpha: 0.5),
|
||||
),
|
||||
const SizedBox(width: 3),
|
||||
Text(
|
||||
entry.distance!,
|
||||
style: theme.textTheme.labelSmall?.copyWith(
|
||||
color: colorScheme.onSurfaceVariant.withValues(alpha: 0.6),
|
||||
fontSize: 10,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final colorScheme = theme.colorScheme;
|
||||
|
||||
return SafeArea(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 12, 16, 24),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
'Ping ${widget.contact.displayName}',
|
||||
style: theme.textTheme.titleLarge?.copyWith(
|
||||
fontWeight: FontWeight.w800,
|
||||
),
|
||||
),
|
||||
),
|
||||
FilledButton.icon(
|
||||
onPressed: _pinging ? null : _doPing,
|
||||
icon: _pinging
|
||||
? SizedBox(
|
||||
width: 16,
|
||||
height: 16,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
color: colorScheme.onPrimary,
|
||||
),
|
||||
)
|
||||
: const Icon(Icons.network_ping, size: 18),
|
||||
label: Text(_pinging ? 'Pinging...' : 'Ping again'),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
widget.contact.publicKeyShort,
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
fontFamily: 'monospace',
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.surfaceContainerLow,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(
|
||||
color: colorScheme.outlineVariant.withValues(alpha: 0.4),
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
_autoPingEnabled
|
||||
? Icons.radar_rounded
|
||||
: Icons.radar_outlined,
|
||||
color: _autoPingEnabled
|
||||
? colorScheme.primary
|
||||
: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Auto ping',
|
||||
style: theme.textTheme.titleSmall?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
'2s sonar cues for there/back SNR',
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Switch.adaptive(
|
||||
value: _autoPingEnabled,
|
||||
onChanged: _setAutoPingEnabled,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
if (_history.isEmpty && !_pinging)
|
||||
Text(
|
||||
'No ping results yet.',
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
)
|
||||
else
|
||||
ConstrainedBox(
|
||||
constraints: const BoxConstraints(
|
||||
maxHeight: _maxHistoryHeight,
|
||||
),
|
||||
child: ListView.separated(
|
||||
shrinkWrap: true,
|
||||
itemCount: _history.length,
|
||||
separatorBuilder: (_, _) => Divider(
|
||||
height: 1,
|
||||
color: colorScheme.outlineVariant.withValues(alpha: 0.4),
|
||||
),
|
||||
itemBuilder: (context, index) =>
|
||||
_buildResultRow(context, _history[index], index + 1),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _PingCuePlayer {
|
||||
static const double _fairSnrThresholdDb = 0;
|
||||
|
||||
AudioPlayer? _player;
|
||||
|
||||
Future<void> playCue(
|
||||
RelayPingResult result, {
|
||||
RelayPingResult? previous,
|
||||
}) async {
|
||||
_player ??= AudioPlayer();
|
||||
final player = _player!;
|
||||
final filePath = await _writeCueFile(
|
||||
result,
|
||||
previous: previous,
|
||||
);
|
||||
await player.stop();
|
||||
await player.setVolume(1.0);
|
||||
await player.play(DeviceFileSource(filePath));
|
||||
}
|
||||
|
||||
Future<String> _writeCueFile(
|
||||
RelayPingResult result, {
|
||||
RelayPingResult? previous,
|
||||
}) async {
|
||||
final tempDir = await getTemporaryDirectory();
|
||||
final file = File('${tempDir.path}/ping_sonar_alert.wav');
|
||||
final samples = _buildCueSamples(result, previous: previous);
|
||||
final wavBytes = _buildWav(samples, sampleRate: 16000);
|
||||
await file.writeAsBytes(wavBytes, flush: true);
|
||||
return file.path;
|
||||
}
|
||||
|
||||
Int16List _buildCueSamples(
|
||||
RelayPingResult result, {
|
||||
RelayPingResult? previous,
|
||||
}) {
|
||||
const sampleRate = 16000;
|
||||
final segments = <double>[];
|
||||
if (!result.success) {
|
||||
segments.addAll(
|
||||
_timeoutAlert(sampleRate),
|
||||
);
|
||||
} else {
|
||||
segments.addAll(
|
||||
_tone(
|
||||
sampleRate,
|
||||
frequencyHz: _frequencyForSnr(result.snrThere),
|
||||
durationMs: 90,
|
||||
amplitude: 0.42,
|
||||
),
|
||||
);
|
||||
segments.addAll(_silence(sampleRate, durationMs: 35));
|
||||
segments.addAll(
|
||||
_tone(
|
||||
sampleRate,
|
||||
frequencyHz: _frequencyForSnr(result.snrBack),
|
||||
durationMs: 90,
|
||||
amplitude: 0.42,
|
||||
),
|
||||
);
|
||||
final belowFair =
|
||||
result.snrThere < _fairSnrThresholdDb &&
|
||||
result.snrBack < _fairSnrThresholdDb;
|
||||
final worsening =
|
||||
previous != null &&
|
||||
result.snrThere < previous.snrThere &&
|
||||
result.snrBack < previous.snrBack;
|
||||
if (belowFair && worsening) {
|
||||
segments.addAll(_silence(sampleRate, durationMs: 40));
|
||||
segments.addAll(
|
||||
_descendingAlert(sampleRate, baseFrequencyHz: 520),
|
||||
);
|
||||
}
|
||||
}
|
||||
final pcm = Int16List(segments.length);
|
||||
for (var i = 0; i < segments.length; i++) {
|
||||
pcm[i] = (segments[i] * 32767).round().clamp(-32768, 32767);
|
||||
}
|
||||
return pcm;
|
||||
}
|
||||
|
||||
double _frequencyForSnr(double snrDb) {
|
||||
final clamped = snrDb.clamp(-12.0, 12.0);
|
||||
final normalized = (clamped + 12.0) / 24.0;
|
||||
return 320 + (normalized * 900);
|
||||
}
|
||||
|
||||
List<double> _descendingAlert(int sampleRate, {required double baseFrequencyHz}) {
|
||||
return <double>[
|
||||
..._tone(
|
||||
sampleRate,
|
||||
frequencyHz: baseFrequencyHz,
|
||||
durationMs: 80,
|
||||
amplitude: 0.44,
|
||||
),
|
||||
..._silence(sampleRate, durationMs: 30),
|
||||
..._tone(
|
||||
sampleRate,
|
||||
frequencyHz: baseFrequencyHz * 0.82,
|
||||
durationMs: 110,
|
||||
amplitude: 0.40,
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
List<double> _timeoutAlert(int sampleRate) {
|
||||
return <double>[
|
||||
..._tone(
|
||||
sampleRate,
|
||||
frequencyHz: 240,
|
||||
durationMs: 180,
|
||||
amplitude: 0.46,
|
||||
),
|
||||
..._silence(sampleRate, durationMs: 60),
|
||||
..._tone(
|
||||
sampleRate,
|
||||
frequencyHz: 180,
|
||||
durationMs: 220,
|
||||
amplitude: 0.52,
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
List<double> _tone(
|
||||
int sampleRate, {
|
||||
required double frequencyHz,
|
||||
required int durationMs,
|
||||
required double amplitude,
|
||||
}) {
|
||||
final sampleCount = (sampleRate * durationMs / 1000).round();
|
||||
return List<double>.generate(sampleCount, (index) {
|
||||
final t = index / sampleRate;
|
||||
final envelope = math.sin(math.pi * index / sampleCount);
|
||||
return math.sin(2 * math.pi * frequencyHz * t) * amplitude * envelope;
|
||||
});
|
||||
}
|
||||
|
||||
List<double> _silence(int sampleRate, {required int durationMs}) {
|
||||
final sampleCount = (sampleRate * durationMs / 1000).round();
|
||||
return List<double>.filled(sampleCount, 0);
|
||||
}
|
||||
|
||||
Uint8List _buildWav(Int16List samples, {required int sampleRate}) {
|
||||
const numChannels = 1;
|
||||
const bitsPerSample = 16;
|
||||
const audioFormat = 1;
|
||||
final dataSize = samples.length * 2;
|
||||
final byteRate = sampleRate * numChannels * bitsPerSample ~/ 8;
|
||||
final blockAlign = numChannels * bitsPerSample ~/ 8;
|
||||
final totalSize = 36 + dataSize;
|
||||
final buffer = ByteData(44 + dataSize);
|
||||
var offset = 0;
|
||||
|
||||
void writeString(String value) {
|
||||
for (final codeUnit in value.codeUnits) {
|
||||
buffer.setUint8(offset++, codeUnit);
|
||||
}
|
||||
}
|
||||
|
||||
void writeUint32(int value) {
|
||||
buffer.setUint32(offset, value, Endian.little);
|
||||
offset += 4;
|
||||
}
|
||||
|
||||
void writeUint16(int value) {
|
||||
buffer.setUint16(offset, value, Endian.little);
|
||||
offset += 2;
|
||||
}
|
||||
|
||||
writeString('RIFF');
|
||||
writeUint32(totalSize);
|
||||
writeString('WAVE');
|
||||
writeString('fmt ');
|
||||
writeUint32(16);
|
||||
writeUint16(audioFormat);
|
||||
writeUint16(numChannels);
|
||||
writeUint32(sampleRate);
|
||||
writeUint32(byteRate);
|
||||
writeUint16(blockAlign);
|
||||
writeUint16(bitsPerSample);
|
||||
writeString('data');
|
||||
writeUint32(dataSize);
|
||||
|
||||
for (final sample in samples) {
|
||||
buffer.setInt16(offset, sample, Endian.little);
|
||||
offset += 2;
|
||||
}
|
||||
|
||||
return buffer.buffer.asUint8List();
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
_player?.dispose();
|
||||
}
|
||||
}
|
||||
@@ -88,24 +88,26 @@ Widget buildBubbleMetaFooter(
|
||||
).textTheme.labelSmall?.copyWith(color: metaColor),
|
||||
),
|
||||
]);
|
||||
} else if (!isSarMarker && _effectivePathLen(message, routeMetadata) < 255) {
|
||||
final effectivePathLen = _effectivePathLen(message, routeMetadata);
|
||||
items.addAll([
|
||||
Icon(Icons.alt_route, size: 11, color: metaColor),
|
||||
const SizedBox(width: 3),
|
||||
Text(
|
||||
effectivePathLen == 0 ? 'direct' : '${effectivePathLen}hop',
|
||||
style: Theme.of(
|
||||
context,
|
||||
).textTheme.labelSmall?.copyWith(color: metaColor),
|
||||
),
|
||||
Text(
|
||||
' • ',
|
||||
style: Theme.of(
|
||||
context,
|
||||
).textTheme.labelSmall?.copyWith(color: metaColor),
|
||||
),
|
||||
]);
|
||||
} else if (!isSarMarker) {
|
||||
final routeLabel = _effectiveRouteFooterLabel(message, routeMetadata);
|
||||
if (routeLabel != null) {
|
||||
items.addAll([
|
||||
Icon(Icons.alt_route, size: 11, color: metaColor),
|
||||
const SizedBox(width: 3),
|
||||
Text(
|
||||
routeLabel,
|
||||
style: Theme.of(
|
||||
context,
|
||||
).textTheme.labelSmall?.copyWith(color: metaColor),
|
||||
),
|
||||
Text(
|
||||
' • ',
|
||||
style: Theme.of(
|
||||
context,
|
||||
).textTheme.labelSmall?.copyWith(color: metaColor),
|
||||
),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
items.add(
|
||||
@@ -127,8 +129,31 @@ Widget buildBubbleMetaFooter(
|
||||
);
|
||||
}
|
||||
|
||||
int _effectivePathLen(Message message, MessageRouteMetadata? routeMetadata) =>
|
||||
routeMetadata?.hopCount ?? message.pathLen;
|
||||
String? _effectiveRouteFooterLabel(
|
||||
Message message,
|
||||
MessageRouteMetadata? routeMetadata,
|
||||
) {
|
||||
if (routeMetadata?.mode.name == 'flood') {
|
||||
return 'flood';
|
||||
}
|
||||
|
||||
final effectivePathLen = _effectivePathLen(message, routeMetadata);
|
||||
if (effectivePathLen >= 255) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return effectivePathLen == 0 ? 'direct' : '${effectivePathLen}hop';
|
||||
}
|
||||
|
||||
int _effectivePathLen(Message message, MessageRouteMetadata? routeMetadata) {
|
||||
if (routeMetadata?.hopCount != null) {
|
||||
return routeMetadata!.hopCount!;
|
||||
}
|
||||
if (routeMetadata?.mode.name == 'flood') {
|
||||
return 255;
|
||||
}
|
||||
return message.pathLen;
|
||||
}
|
||||
|
||||
Widget buildChannelHeaderPill(
|
||||
BuildContext context, {
|
||||
|
||||
@@ -1064,6 +1064,7 @@ class SensorTelemetryCard extends StatelessWidget {
|
||||
final Map<String, int> fieldSpans;
|
||||
final Future<void> Function()? onRemove;
|
||||
final Future<void> Function()? onRefresh;
|
||||
final Future<void> Function()? onPing;
|
||||
final VoidCallback? onCustomize;
|
||||
final Future<void> Function(Contact contact)? onShowMetHistory;
|
||||
final Future<void> Function()? onMoveUp;
|
||||
@@ -1071,6 +1072,7 @@ class SensorTelemetryCard extends StatelessWidget {
|
||||
final EdgeInsetsGeometry margin;
|
||||
final String emptyMetricsMessage;
|
||||
final Map<String, String> labelOverrides;
|
||||
final bool showActionSheetOnTap;
|
||||
|
||||
const SensorTelemetryCard({
|
||||
super.key,
|
||||
@@ -1081,6 +1083,7 @@ class SensorTelemetryCard extends StatelessWidget {
|
||||
required this.fieldSpans,
|
||||
this.onRemove,
|
||||
this.onRefresh,
|
||||
this.onPing,
|
||||
this.onCustomize,
|
||||
this.onShowMetHistory,
|
||||
this.onMoveUp,
|
||||
@@ -1089,6 +1092,7 @@ class SensorTelemetryCard extends StatelessWidget {
|
||||
this.emptyMetricsMessage =
|
||||
'All fields are hidden. Use Visible fields to choose what to show.',
|
||||
this.labelOverrides = const <String, String>{},
|
||||
this.showActionSheetOnTap = false,
|
||||
});
|
||||
|
||||
String _formatSpeed(num metersPerSecond) {
|
||||
@@ -1103,6 +1107,7 @@ class SensorTelemetryCard extends StatelessWidget {
|
||||
|
||||
bool get _showsMenu =>
|
||||
onRefresh != null ||
|
||||
onPing != null ||
|
||||
onCustomize != null ||
|
||||
onRemove != null ||
|
||||
onMoveUp != null ||
|
||||
@@ -1112,6 +1117,116 @@ class SensorTelemetryCard extends StatelessWidget {
|
||||
onShowMetHistory != null &&
|
||||
supportsBTHomeMetHistory(contact));
|
||||
|
||||
Future<void> _handleAction(BuildContext context, String value) async {
|
||||
if (value == 'refresh' && onRefresh != null) {
|
||||
await onRefresh!();
|
||||
return;
|
||||
}
|
||||
if (value == 'ping' && onPing != null) {
|
||||
await onPing!();
|
||||
return;
|
||||
}
|
||||
if (value == 'move_up' && onMoveUp != null) {
|
||||
await onMoveUp!();
|
||||
return;
|
||||
}
|
||||
if (value == 'move_down' && onMoveDown != null) {
|
||||
await onMoveDown!();
|
||||
return;
|
||||
}
|
||||
if (value == 'copy_raw') {
|
||||
final rawTelemetry = _rawTelemetryHex(contact?.telemetry);
|
||||
if (rawTelemetry != null && context.mounted) {
|
||||
await Clipboard.setData(ClipboardData(text: rawTelemetry));
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Raw response copied')),
|
||||
);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (value == 'remove' && onRemove != null) {
|
||||
await onRemove!();
|
||||
return;
|
||||
}
|
||||
if (value == 'customize' && onCustomize != null) {
|
||||
onCustomize!();
|
||||
return;
|
||||
}
|
||||
if (value == 'met_history' &&
|
||||
contact != null &&
|
||||
onShowMetHistory != null) {
|
||||
await onShowMetHistory!(contact!);
|
||||
}
|
||||
}
|
||||
|
||||
List<_SensorSheetAction> _buildSheetActions(BuildContext context) {
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
final actions = <_SensorSheetAction>[
|
||||
if (onRefresh != null)
|
||||
_SensorSheetAction(
|
||||
icon: Icons.refresh,
|
||||
label: l10n.refresh,
|
||||
onTap: () => _handleAction(context, 'refresh'),
|
||||
),
|
||||
if (onPing != null)
|
||||
_SensorSheetAction(
|
||||
icon: Icons.network_ping,
|
||||
label: 'Ping',
|
||||
onTap: () => _handleAction(context, 'ping'),
|
||||
),
|
||||
if (_rawTelemetryHex(contact?.telemetry) != null)
|
||||
_SensorSheetAction(
|
||||
icon: Icons.copy_all_outlined,
|
||||
label: 'Copy raw response',
|
||||
onTap: () => _handleAction(context, 'copy_raw'),
|
||||
),
|
||||
if (onCustomize != null)
|
||||
_SensorSheetAction(
|
||||
icon: Icons.tune,
|
||||
label: l10n.customizeFields,
|
||||
onTap: () => _handleAction(context, 'customize'),
|
||||
),
|
||||
if (contact != null &&
|
||||
onShowMetHistory != null &&
|
||||
supportsBTHomeMetHistory(contact))
|
||||
_SensorSheetAction(
|
||||
icon: Icons.show_chart,
|
||||
label: 'MET history',
|
||||
onTap: () => _handleAction(context, 'met_history'),
|
||||
),
|
||||
if (onRemove != null)
|
||||
_SensorSheetAction(
|
||||
icon: Icons.delete_outline_rounded,
|
||||
label: l10n.remove,
|
||||
destructive: true,
|
||||
onTap: () => _handleAction(context, 'remove'),
|
||||
),
|
||||
];
|
||||
return actions;
|
||||
}
|
||||
|
||||
Future<void> _showActionSheet(BuildContext context) async {
|
||||
if (!_showsMenu) {
|
||||
return;
|
||||
}
|
||||
final actions = _buildSheetActions(context);
|
||||
if (actions.isEmpty) {
|
||||
return;
|
||||
}
|
||||
await showModalBottomSheet<void>(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
backgroundColor: Colors.transparent,
|
||||
builder: (sheetContext) => _SensorActionSheet(
|
||||
contact: contact,
|
||||
actions: actions,
|
||||
onClose: () => Navigator.pop(sheetContext),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = AppLocalizations.of(context)!;
|
||||
@@ -1124,7 +1239,7 @@ class SensorTelemetryCard extends StatelessWidget {
|
||||
_buildMetricCards(l10n, telemetry, contact!),
|
||||
);
|
||||
|
||||
return Container(
|
||||
final card = Container(
|
||||
margin: margin,
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(28),
|
||||
@@ -1212,102 +1327,11 @@ class SensorTelemetryCard extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
if (_showsMenu)
|
||||
PopupMenuButton<String>(
|
||||
onSelected: (value) async {
|
||||
if (value == 'refresh' && onRefresh != null) {
|
||||
await onRefresh!();
|
||||
} else if (value == 'move_up' && onMoveUp != null) {
|
||||
await onMoveUp!();
|
||||
} else if (value == 'move_down' && onMoveDown != null) {
|
||||
await onMoveDown!();
|
||||
} else if (value == 'copy_raw') {
|
||||
final rawTelemetry = _rawTelemetryHex(
|
||||
contact?.telemetry,
|
||||
);
|
||||
if (rawTelemetry != null && context.mounted) {
|
||||
await Clipboard.setData(
|
||||
ClipboardData(text: rawTelemetry),
|
||||
);
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Raw response copied'),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
} else if (value == 'remove' && onRemove != null) {
|
||||
await onRemove!();
|
||||
} else if (value == 'customize' && onCustomize != null) {
|
||||
onCustomize!();
|
||||
} else if (value == 'met_history' &&
|
||||
contact != null &&
|
||||
onShowMetHistory != null) {
|
||||
await onShowMetHistory!(contact!);
|
||||
}
|
||||
},
|
||||
itemBuilder: (context) {
|
||||
final items = <PopupMenuEntry<String>>[];
|
||||
if (onRefresh != null) {
|
||||
items.add(
|
||||
PopupMenuItem<String>(
|
||||
value: 'refresh',
|
||||
child: Text(l10n.refresh),
|
||||
),
|
||||
);
|
||||
}
|
||||
if (onMoveUp != null) {
|
||||
items.add(
|
||||
const PopupMenuItem<String>(
|
||||
value: 'move_up',
|
||||
child: Text('Move up'),
|
||||
),
|
||||
);
|
||||
}
|
||||
if (onMoveDown != null) {
|
||||
items.add(
|
||||
const PopupMenuItem<String>(
|
||||
value: 'move_down',
|
||||
child: Text('Move down'),
|
||||
),
|
||||
);
|
||||
}
|
||||
if (_rawTelemetryHex(contact?.telemetry) != null) {
|
||||
items.add(
|
||||
const PopupMenuItem<String>(
|
||||
value: 'copy_raw',
|
||||
child: Text('Copy raw response'),
|
||||
),
|
||||
);
|
||||
}
|
||||
if (onCustomize != null) {
|
||||
items.add(
|
||||
PopupMenuItem<String>(
|
||||
value: 'customize',
|
||||
child: Text(l10n.customizeFields),
|
||||
),
|
||||
);
|
||||
}
|
||||
if (contact != null &&
|
||||
onShowMetHistory != null &&
|
||||
supportsBTHomeMetHistory(contact)) {
|
||||
items.add(
|
||||
const PopupMenuItem<String>(
|
||||
value: 'met_history',
|
||||
child: Text('MET history'),
|
||||
),
|
||||
);
|
||||
}
|
||||
if (onRemove != null) {
|
||||
items.add(
|
||||
PopupMenuItem<String>(
|
||||
value: 'remove',
|
||||
child: Text(l10n.remove),
|
||||
),
|
||||
);
|
||||
}
|
||||
return items;
|
||||
},
|
||||
Icon(
|
||||
showActionSheetOnTap
|
||||
? Icons.chevron_right_rounded
|
||||
: Icons.more_horiz,
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
],
|
||||
),
|
||||
@@ -1355,6 +1379,16 @@ class SensorTelemetryCard extends StatelessWidget {
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
if (!_showsMenu || !showActionSheetOnTap) {
|
||||
return card;
|
||||
}
|
||||
|
||||
return GestureDetector(
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onTap: () => _showActionSheet(context),
|
||||
child: card,
|
||||
);
|
||||
}
|
||||
|
||||
List<SensorMetricCardData> _buildMetricCards(
|
||||
@@ -2826,6 +2860,213 @@ class SensorMetricCardData {
|
||||
});
|
||||
}
|
||||
|
||||
class _SensorSheetAction {
|
||||
final IconData icon;
|
||||
final String label;
|
||||
final Future<void> Function() onTap;
|
||||
final bool destructive;
|
||||
|
||||
const _SensorSheetAction({
|
||||
required this.icon,
|
||||
required this.label,
|
||||
required this.onTap,
|
||||
this.destructive = false,
|
||||
});
|
||||
}
|
||||
|
||||
class _SensorActionSheet extends StatelessWidget {
|
||||
final Contact? contact;
|
||||
final List<_SensorSheetAction> actions;
|
||||
final VoidCallback onClose;
|
||||
|
||||
const _SensorActionSheet({
|
||||
required this.contact,
|
||||
required this.actions,
|
||||
required this.onClose,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final colorScheme = theme.colorScheme;
|
||||
final bottomInset = MediaQuery.of(context).viewPadding.bottom;
|
||||
final title = contact?.displayName ?? 'Sensor';
|
||||
final subtitle = contact == null ? 'Unavailable node' : contact!.publicKeyShort;
|
||||
|
||||
return Container(
|
||||
constraints: BoxConstraints(
|
||||
maxHeight: MediaQuery.of(context).size.height * 0.82,
|
||||
),
|
||||
clipBehavior: Clip.antiAlias,
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.surface,
|
||||
borderRadius: const BorderRadius.vertical(top: Radius.circular(32)),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: colorScheme.shadow.withValues(alpha: 0.12),
|
||||
blurRadius: 24,
|
||||
offset: const Offset(0, -4),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Material(
|
||||
color: colorScheme.surface,
|
||||
child: SingleChildScrollView(
|
||||
padding: EdgeInsets.fromLTRB(16, 12, 16, 16 + bottomInset),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Center(
|
||||
child: Container(
|
||||
width: 44,
|
||||
height: 4,
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.outlineVariant,
|
||||
borderRadius: BorderRadius.circular(999),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Container(
|
||||
width: 56,
|
||||
height: 56,
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(18),
|
||||
gradient: LinearGradient(
|
||||
colors: [
|
||||
colorScheme.primaryContainer,
|
||||
colorScheme.secondaryContainer,
|
||||
],
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
),
|
||||
),
|
||||
child: Icon(
|
||||
Icons.sensors_rounded,
|
||||
color: colorScheme.onPrimaryContainer,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 14),
|
||||
Expanded(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(top: 2),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
title,
|
||||
style: theme.textTheme.titleLarge?.copyWith(
|
||||
fontWeight: FontWeight.w900,
|
||||
letterSpacing: -0.45,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
subtitle,
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
fontFamily: contact == null ? null : 'monospace',
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
onPressed: onClose,
|
||||
icon: const Icon(Icons.close),
|
||||
tooltip: MaterialLocalizations.of(context).closeButtonTooltip,
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 18),
|
||||
...actions.map(
|
||||
(action) => _SensorActionTile(
|
||||
action: action,
|
||||
onClose: onClose,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _SensorActionTile extends StatelessWidget {
|
||||
final _SensorSheetAction action;
|
||||
final VoidCallback onClose;
|
||||
|
||||
const _SensorActionTile({
|
||||
required this.action,
|
||||
required this.onClose,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final colorScheme = theme.colorScheme;
|
||||
final foreground = action.destructive
|
||||
? colorScheme.error
|
||||
: colorScheme.onSurface;
|
||||
final iconBackground = action.destructive
|
||||
? colorScheme.error.withValues(alpha: 0.12)
|
||||
: colorScheme.surfaceContainerHigh;
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 10),
|
||||
child: InkWell(
|
||||
borderRadius: BorderRadius.circular(22),
|
||||
onTap: () async {
|
||||
onClose();
|
||||
await action.onTap();
|
||||
},
|
||||
child: Ink(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 14),
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.surfaceContainerLow,
|
||||
borderRadius: BorderRadius.circular(22),
|
||||
border: Border.all(
|
||||
color: colorScheme.outlineVariant.withValues(alpha: 0.45),
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
width: 40,
|
||||
height: 40,
|
||||
decoration: BoxDecoration(
|
||||
color: iconBackground,
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
),
|
||||
child: Icon(action.icon, color: foreground),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
action.label,
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
color: foreground,
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
),
|
||||
Icon(
|
||||
Icons.chevron_right_rounded,
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ParsedMetricKey {
|
||||
final String baseKey;
|
||||
final int? channel;
|
||||
|
||||
107
lib/widgets/settings/traffic_stats_reporting_section.dart
Normal file
107
lib/widgets/settings/traffic_stats_reporting_section.dart
Normal file
@@ -0,0 +1,107 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
import '../../services/traffic_stats_reporting_service.dart';
|
||||
|
||||
class TrafficStatsReportingSection extends StatelessWidget {
|
||||
final TrafficStatsReportingService service;
|
||||
|
||||
const TrafficStatsReportingSection({super.key, required this.service});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
SwitchListTile(
|
||||
secondary: const Icon(Icons.cloud_upload_outlined),
|
||||
title: const Text('Anonymous RX stats reporting'),
|
||||
subtitle: const Text(
|
||||
'Upload RX live-traffic packet type and path mode totals to the fixed Cloudflare worker every 5 minutes.',
|
||||
),
|
||||
value: service.isEnabled,
|
||||
onChanged: (value) async {
|
||||
await service.setEnabled(value);
|
||||
},
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
|
||||
child: DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surfaceContainerLow,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(
|
||||
color: theme.colorScheme.outlineVariant.withValues(alpha: 0.5),
|
||||
),
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Upload status',
|
||||
style: theme.textTheme.titleSmall,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
_statusText(service),
|
||||
style: theme.textTheme.bodyMedium,
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
'Ingest URL: ${TrafficStatsReportingService.ingestUri}',
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
TextButton.icon(
|
||||
onPressed: _openStatsDashboard,
|
||||
icon: const Icon(Icons.open_in_new),
|
||||
label: const Text('View public stats'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
static Future<void> _openStatsDashboard() async {
|
||||
final url = TrafficStatsReportingService.dashboardUri;
|
||||
if (await canLaunchUrl(url)) {
|
||||
await launchUrl(url, mode: LaunchMode.externalApplication);
|
||||
}
|
||||
}
|
||||
|
||||
static String _statusText(TrafficStatsReportingService service) {
|
||||
final buffer = StringBuffer();
|
||||
buffer.write('Pending uploads: ${service.pendingUploadCount}');
|
||||
if (service.lastSuccessAt != null) {
|
||||
buffer.write(
|
||||
'\nLast sent: ${_formatDateTime(service.lastSuccessAt!.toLocal())}',
|
||||
);
|
||||
} else {
|
||||
buffer.write('\nLast sent: Never');
|
||||
}
|
||||
if (service.lastError != null && service.lastError!.isNotEmpty) {
|
||||
buffer.write('\nLast error: ${service.lastError}');
|
||||
} else {
|
||||
buffer.write('\nLast error: None');
|
||||
}
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
static String _formatDateTime(DateTime value) {
|
||||
final month = value.month.toString().padLeft(2, '0');
|
||||
final day = value.day.toString().padLeft(2, '0');
|
||||
final hour = value.hour.toString().padLeft(2, '0');
|
||||
final minute = value.minute.toString().padLeft(2, '0');
|
||||
final second = value.second.toString().padLeft(2, '0');
|
||||
return '${value.year}-$month-$day $hour:$minute:$second';
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
|
||||
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
|
||||
# In Windows, build-name is used as the major, minor, and patch parts
|
||||
# of the product and file versions while build-number is used as the build suffix.
|
||||
version: 2026.0324.1+43
|
||||
version: 2026.0403.1+45
|
||||
|
||||
environment:
|
||||
sdk: ^3.9.2
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:meshcore_sar_app/models/channel.dart';
|
||||
import 'package:meshcore_sar_app/models/ble_packet_log.dart';
|
||||
@@ -67,6 +66,39 @@ Widget _testApp(Widget child, {ChannelsProvider? channelsProvider}) {
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
final launchedUrls = <String>[];
|
||||
|
||||
setUp(() {
|
||||
launchedUrls.clear();
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(
|
||||
const MethodChannel('plugins.flutter.io/url_launcher'),
|
||||
(call) async {
|
||||
switch (call.method) {
|
||||
case 'canLaunch':
|
||||
return true;
|
||||
case 'launch':
|
||||
final arguments = Map<dynamic, dynamic>.from(
|
||||
call.arguments as Map<dynamic, dynamic>,
|
||||
);
|
||||
launchedUrls.add(arguments['url'] as String);
|
||||
return true;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(
|
||||
const MethodChannel('plugins.flutter.io/url_launcher'),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('shows empty state before traffic arrives', (tester) async {
|
||||
final logs = <BlePacketLog>[];
|
||||
final refresh = ValueNotifier<int>(0);
|
||||
@@ -273,6 +305,27 @@ void main() {
|
||||
expect(find.text('FLOOD CONTROL'), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('opens public stats from the app bar', (tester) async {
|
||||
final logs = <BlePacketLog>[];
|
||||
final refresh = ValueNotifier<int>(0);
|
||||
final now = DateTime(2026, 3, 12, 12, 0, 0);
|
||||
|
||||
await tester.pumpWidget(
|
||||
_testApp(
|
||||
LiveTrafficScreen(
|
||||
logReader: () => logs,
|
||||
refreshListenable: refresh,
|
||||
now: () => now,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
await tester.tap(find.byTooltip('View public stats'));
|
||||
await tester.pump();
|
||||
|
||||
expect(launchedUrls, ['https://mcstats.dz0ny.dev']);
|
||||
});
|
||||
|
||||
testWidgets('summary metrics expand across wide layouts', (tester) async {
|
||||
tester.view.physicalSize = const Size(1200, 900);
|
||||
tester.view.devicePixelRatio = 1;
|
||||
|
||||
@@ -207,6 +207,42 @@ void main() {
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'confirmed direct delivery promotes an observed path to learned',
|
||||
() async {
|
||||
final service = PathHistoryService();
|
||||
final contact = _buildContact(
|
||||
seed: 4,
|
||||
pathBytes: [0xAA, 0xBB],
|
||||
hopCount: 2,
|
||||
hashSize: 1,
|
||||
);
|
||||
|
||||
await service.initialize();
|
||||
await service.recordReceivedBytePath(contact.publicKeyHex, [
|
||||
0xBB,
|
||||
0xAA,
|
||||
], 1);
|
||||
await service.recordPathResult(
|
||||
contact.publicKeyHex,
|
||||
PathSelection(
|
||||
mode: PathSelectionMode.directHistorical,
|
||||
pathBytes: Uint8List.fromList([0xAA, 0xBB]),
|
||||
hopCount: 2,
|
||||
hashSize: 1,
|
||||
),
|
||||
success: true,
|
||||
roundTripTimeMs: 150,
|
||||
);
|
||||
|
||||
final history = service.historyFor(contact.publicKeyHex);
|
||||
expect(history.directPaths, hasLength(1));
|
||||
expect(history.directPaths.single.source, PathRecordSource.learned);
|
||||
expect(history.directPaths.single.successCount, 1);
|
||||
expect(history.directPaths.single.lastRoundTripTimeMs, 150);
|
||||
},
|
||||
);
|
||||
|
||||
test('clear history removes stored direct paths for one contact', () async {
|
||||
final service = PathHistoryService();
|
||||
|
||||
@@ -223,6 +259,47 @@ void main() {
|
||||
expect(service.historyFor('def456').directPaths, hasLength(1));
|
||||
});
|
||||
|
||||
test(
|
||||
'clear history for contact suppresses immediate relearn of current route',
|
||||
() async {
|
||||
final service = PathHistoryService();
|
||||
final contact = _buildContact(
|
||||
seed: 5,
|
||||
pathBytes: [0xAA, 0xBB],
|
||||
hopCount: 2,
|
||||
hashSize: 1,
|
||||
);
|
||||
|
||||
await service.initialize();
|
||||
await service.recordLearnedPath(contact);
|
||||
expect(service.historyFor(contact.publicKeyHex).directPaths, hasLength(1));
|
||||
|
||||
await service.clearHistoryForContact(contact);
|
||||
expect(service.historyFor(contact.publicKeyHex).directPaths, isEmpty);
|
||||
|
||||
await service.recordLearnedPath(contact);
|
||||
expect(service.historyFor(contact.publicKeyHex).directPaths, isEmpty);
|
||||
|
||||
await service.recordPathResult(
|
||||
contact.publicKeyHex,
|
||||
PathSelection(
|
||||
mode: PathSelectionMode.directHistorical,
|
||||
pathBytes: Uint8List.fromList([0xAA, 0xBB]),
|
||||
hopCount: 2,
|
||||
hashSize: 1,
|
||||
),
|
||||
success: true,
|
||||
roundTripTimeMs: 120,
|
||||
);
|
||||
|
||||
expect(service.historyFor(contact.publicKeyHex).directPaths, hasLength(1));
|
||||
expect(
|
||||
service.historyFor(contact.publicKeyHex).directPaths.single.source,
|
||||
PathRecordSource.learned,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test('last successful direct path is chosen by location fit', () async {
|
||||
final service = PathHistoryService();
|
||||
final contact = _buildContact(
|
||||
|
||||
280
test/services/traffic_stats_reporting_service_test.dart
Normal file
280
test/services/traffic_stats_reporting_service_test.dart
Normal file
@@ -0,0 +1,280 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:http/testing.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import 'package:meshcore_sar_app/models/ble_packet_log.dart';
|
||||
import 'package:meshcore_sar_app/services/profiles_feature_service.dart';
|
||||
import 'package:meshcore_sar_app/services/traffic_stats_reporting_service.dart';
|
||||
|
||||
BlePacketLog _log({
|
||||
required DateTime timestamp,
|
||||
required List<int> rawData,
|
||||
int responseCode = 0x88,
|
||||
}) {
|
||||
return BlePacketLog(
|
||||
timestamp: timestamp,
|
||||
rawData: Uint8List.fromList(rawData),
|
||||
direction: PacketDirection.rx,
|
||||
responseCode: responseCode,
|
||||
);
|
||||
}
|
||||
|
||||
List<int> _routeRaw({
|
||||
required int payloadType,
|
||||
required int pathDescriptor,
|
||||
List<int> pathBytes = const <int>[],
|
||||
}) {
|
||||
return <int>[
|
||||
0x88,
|
||||
0x00,
|
||||
0x00,
|
||||
payloadType << 2,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
0x00,
|
||||
pathDescriptor,
|
||||
...pathBytes,
|
||||
];
|
||||
}
|
||||
|
||||
void main() {
|
||||
setUp(() {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
ProfileStorageScope.setScope(
|
||||
profilesEnabled: true,
|
||||
activeProfileId: 'alpha',
|
||||
);
|
||||
});
|
||||
|
||||
test('uploads fixed packet type and path mode counters', () async {
|
||||
final capturedPayloads = <Map<String, dynamic>>[];
|
||||
DateTime now = DateTime.utc(2026, 4, 3, 10, 6);
|
||||
final service = TrafficStatsReportingService(
|
||||
client: MockClient((request) async {
|
||||
capturedPayloads.add(
|
||||
jsonDecode(request.body) as Map<String, dynamic>,
|
||||
);
|
||||
return http.Response('{}', 200);
|
||||
}),
|
||||
now: () => now,
|
||||
appVersionProvider: () async => '2026.0402.1+44',
|
||||
);
|
||||
|
||||
await service.initialize(
|
||||
deviceKey6Provider: () => 'a1b2c3d4e5f6',
|
||||
);
|
||||
expect(service.isEnabled, isTrue);
|
||||
await service.processLogs(<BlePacketLog>[
|
||||
_log(
|
||||
timestamp: DateTime.utc(2026, 4, 3, 10, 0, 5),
|
||||
rawData: _routeRaw(
|
||||
payloadType: 0x04,
|
||||
pathDescriptor: 0x01,
|
||||
pathBytes: const <int>[0xC0],
|
||||
),
|
||||
),
|
||||
_log(
|
||||
timestamp: DateTime.utc(2026, 4, 3, 10, 0, 10),
|
||||
rawData: _routeRaw(
|
||||
payloadType: 0x05,
|
||||
pathDescriptor: 0x41,
|
||||
pathBytes: const <int>[0xC0, 0x10],
|
||||
),
|
||||
),
|
||||
_log(
|
||||
timestamp: DateTime.utc(2026, 4, 3, 10, 0, 15),
|
||||
rawData: _routeRaw(
|
||||
payloadType: 0x08,
|
||||
pathDescriptor: 0x81,
|
||||
pathBytes: const <int>[0xC0, 0x10, 0x63],
|
||||
),
|
||||
),
|
||||
_log(
|
||||
timestamp: DateTime.utc(2026, 4, 3, 10, 0, 20),
|
||||
rawData: _routeRaw(
|
||||
payloadType: 0x01,
|
||||
pathDescriptor: 0x00,
|
||||
),
|
||||
),
|
||||
]);
|
||||
|
||||
expect(capturedPayloads, hasLength(1));
|
||||
|
||||
final payload = capturedPayloads.single;
|
||||
final counts = payload['counts'] as Map<String, dynamic>;
|
||||
expect(payload['deviceKey6'], 'a1b2c3d4e5f6');
|
||||
expect(payload.containsKey('publicKey'), isFalse);
|
||||
expect(payload.containsKey('location'), isFalse);
|
||||
expect(counts['pt_04'], 1);
|
||||
expect(counts['pt_05'], 1);
|
||||
expect(counts['pt_08'], 1);
|
||||
expect(counts['pt_01'], 1);
|
||||
expect(counts['path_mode_1b'], 1);
|
||||
expect(counts['path_mode_2b'], 1);
|
||||
expect(counts['path_mode_3b'], 1);
|
||||
expect(counts['path_mode_none'], 1);
|
||||
expect(service.pendingUploadCount, 0);
|
||||
|
||||
service.dispose();
|
||||
});
|
||||
|
||||
test('classifies malformed route descriptors as decode and path failures', () async {
|
||||
final capturedPayloads = <Map<String, dynamic>>[];
|
||||
final service = TrafficStatsReportingService(
|
||||
client: MockClient((request) async {
|
||||
capturedPayloads.add(
|
||||
jsonDecode(request.body) as Map<String, dynamic>,
|
||||
);
|
||||
return http.Response('{}', 200);
|
||||
}),
|
||||
now: () => DateTime.utc(2026, 4, 3, 10, 6),
|
||||
appVersionProvider: () async => '2026.0402.1+44',
|
||||
);
|
||||
|
||||
await service.initialize(
|
||||
deviceKey6Provider: () => 'a1b2c3d4e5f6',
|
||||
);
|
||||
await service.setEnabled(true);
|
||||
await service.processLogs(<BlePacketLog>[
|
||||
_log(
|
||||
timestamp: DateTime.utc(2026, 4, 3, 10, 0, 30),
|
||||
rawData: _routeRaw(
|
||||
payloadType: 0x04,
|
||||
pathDescriptor: 0x41,
|
||||
),
|
||||
),
|
||||
]);
|
||||
|
||||
final counts =
|
||||
(capturedPayloads.single['counts'] as Map<String, dynamic>);
|
||||
expect(counts['decode_fail'], 1);
|
||||
expect(counts['path_mode_unknown'], 1);
|
||||
|
||||
service.dispose();
|
||||
});
|
||||
|
||||
test('persists queue and retries deterministically', () async {
|
||||
final requestBodies = <Map<String, dynamic>>[];
|
||||
var shouldFail = true;
|
||||
DateTime now = DateTime.utc(2026, 4, 3, 10, 6);
|
||||
|
||||
final failingService = TrafficStatsReportingService(
|
||||
client: MockClient((request) async {
|
||||
requestBodies.add(
|
||||
jsonDecode(request.body) as Map<String, dynamic>,
|
||||
);
|
||||
if (shouldFail) {
|
||||
return http.Response('nope', 503);
|
||||
}
|
||||
return http.Response('{}', 200);
|
||||
}),
|
||||
now: () => now,
|
||||
appVersionProvider: () async => '2026.0402.1+44',
|
||||
);
|
||||
|
||||
await failingService.initialize(
|
||||
deviceKey6Provider: () => 'a1b2c3d4e5f6',
|
||||
);
|
||||
await failingService.setEnabled(true);
|
||||
await failingService.processLogs(<BlePacketLog>[
|
||||
_log(
|
||||
timestamp: DateTime.utc(2026, 4, 3, 10, 0, 5),
|
||||
rawData: _routeRaw(
|
||||
payloadType: 0x04,
|
||||
pathDescriptor: 0x01,
|
||||
pathBytes: const <int>[0xC0],
|
||||
),
|
||||
),
|
||||
]);
|
||||
|
||||
expect(failingService.pendingUploadCount, 1);
|
||||
expect(failingService.lastError, 'Upload failed (503)');
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
expect(
|
||||
prefs.containsKey('traffic_stats_reporting_queue'),
|
||||
isTrue,
|
||||
);
|
||||
expect(
|
||||
requestBodies.single['reportId'],
|
||||
'a1b2c3d4e5f6:2026-04-03T10:00:00.000Z',
|
||||
);
|
||||
failingService.dispose();
|
||||
|
||||
shouldFail = false;
|
||||
now = DateTime.utc(2026, 4, 3, 10, 7);
|
||||
final retryService = TrafficStatsReportingService(
|
||||
client: MockClient((request) async {
|
||||
requestBodies.add(
|
||||
jsonDecode(request.body) as Map<String, dynamic>,
|
||||
);
|
||||
return http.Response('{}', 200);
|
||||
}),
|
||||
now: () => now,
|
||||
appVersionProvider: () async => '2026.0402.1+44',
|
||||
);
|
||||
await retryService.initialize(
|
||||
deviceKey6Provider: () => 'a1b2c3d4e5f6',
|
||||
);
|
||||
await retryService.flushPendingUploads();
|
||||
|
||||
expect(retryService.pendingUploadCount, 0);
|
||||
expect(retryService.lastError, isNull);
|
||||
expect(retryService.lastSuccessAt, now);
|
||||
retryService.dispose();
|
||||
});
|
||||
|
||||
test('ignores legacy interval preferences and keeps 5 minute windows', () async {
|
||||
SharedPreferences.setMockInitialValues({
|
||||
'traffic_stats_reporting_interval_minutes': 15,
|
||||
});
|
||||
final capturedPayloads = <Map<String, dynamic>>[];
|
||||
final service = TrafficStatsReportingService(
|
||||
client: MockClient((request) async {
|
||||
capturedPayloads.add(
|
||||
jsonDecode(request.body) as Map<String, dynamic>,
|
||||
);
|
||||
return http.Response('{}', 200);
|
||||
}),
|
||||
now: () => DateTime.utc(2026, 4, 3, 10, 6),
|
||||
appVersionProvider: () async => '2026.0402.1+44',
|
||||
);
|
||||
|
||||
await service.initialize(
|
||||
deviceKey6Provider: () => 'a1b2c3d4e5f6',
|
||||
);
|
||||
await service.setEnabled(true);
|
||||
await service.processLogs(<BlePacketLog>[
|
||||
_log(
|
||||
timestamp: DateTime.utc(2026, 4, 3, 10, 0, 5),
|
||||
rawData: _routeRaw(
|
||||
payloadType: 0x04,
|
||||
pathDescriptor: 0x01,
|
||||
pathBytes: const <int>[0xC0],
|
||||
),
|
||||
),
|
||||
]);
|
||||
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
expect(prefs.getBool('traffic_stats_reporting_enabled'), isTrue);
|
||||
expect(prefs.containsKey('traffic_stats_reporting_interval_minutes'), isFalse);
|
||||
expect(
|
||||
prefs.containsKey('profile.alpha.traffic_stats_reporting_enabled'),
|
||||
isFalse,
|
||||
);
|
||||
expect(
|
||||
prefs.containsKey(
|
||||
'profile.alpha.traffic_stats_reporting_interval_minutes',
|
||||
),
|
||||
isFalse,
|
||||
);
|
||||
expect(service.intervalMinutes, 5);
|
||||
expect(capturedPayloads, hasLength(1));
|
||||
|
||||
service.dispose();
|
||||
});
|
||||
}
|
||||
94
test/widgets/traffic_stats_reporting_section_test.dart
Normal file
94
test/widgets/traffic_stats_reporting_section_test.dart
Normal file
@@ -0,0 +1,94 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:http/testing.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import 'package:meshcore_sar_app/services/traffic_stats_reporting_service.dart';
|
||||
import 'package:meshcore_sar_app/widgets/settings/traffic_stats_reporting_section.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
final launchedUrls = <String>[];
|
||||
|
||||
setUp(() {
|
||||
launchedUrls.clear();
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(
|
||||
const MethodChannel('plugins.flutter.io/url_launcher'),
|
||||
(call) async {
|
||||
switch (call.method) {
|
||||
case 'canLaunch':
|
||||
return true;
|
||||
case 'launch':
|
||||
final arguments = Map<dynamic, dynamic>.from(
|
||||
call.arguments as Map<dynamic, dynamic>,
|
||||
);
|
||||
launchedUrls.add(arguments['url'] as String);
|
||||
return true;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(
|
||||
const MethodChannel('plugins.flutter.io/url_launcher'),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('starts enabled by default and can be disabled', (
|
||||
tester,
|
||||
) async {
|
||||
SharedPreferences.setMockInitialValues({});
|
||||
final service = TrafficStatsReportingService(
|
||||
client: MockClient((request) async => http.Response('{}', 200)),
|
||||
now: () => DateTime.utc(2026, 4, 3, 10, 6),
|
||||
appVersionProvider: () async => '2026.0402.1+44',
|
||||
);
|
||||
await service.initialize(
|
||||
deviceKey6Provider: () => 'a1b2c3d4e5f6',
|
||||
);
|
||||
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: Scaffold(
|
||||
body: ListenableBuilder(
|
||||
listenable: service,
|
||||
builder: (context, child) => TrafficStatsReportingSection(
|
||||
service: service,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
expect(find.text('Anonymous RX stats reporting'), findsOneWidget);
|
||||
expect(
|
||||
find.text(
|
||||
'Upload RX live-traffic packet type and path mode totals to the fixed Cloudflare worker every 5 minutes.',
|
||||
),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(find.text('Reporting interval'), findsNothing);
|
||||
expect(service.isEnabled, isTrue);
|
||||
|
||||
await tester.tap(find.byType(Switch));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(service.isEnabled, isFalse);
|
||||
expect(service.intervalMinutes, 5);
|
||||
|
||||
await tester.tap(find.widgetWithText(TextButton, 'View public stats'));
|
||||
await tester.pump();
|
||||
|
||||
expect(launchedUrls, ['https://mcstats.dz0ny.dev']);
|
||||
|
||||
service.dispose();
|
||||
});
|
||||
}
|
||||
29
worker/README.md
Normal file
29
worker/README.md
Normal file
@@ -0,0 +1,29 @@
|
||||
# MeshCore SAR Stats Worker
|
||||
|
||||
This worker follows the same split as `/Users/dz0ny/site-vendorvigilance`:
|
||||
|
||||
- Astro builds the dashboard UI into `dist`
|
||||
- a small Cloudflare Worker handles `/api/*` before assets are served
|
||||
|
||||
## Layout
|
||||
|
||||
- `src/pages/index.astro` - dashboard shell
|
||||
- `worker/index.ts` - Cloudflare Worker entrypoint
|
||||
- `worker/stats.ts` - D1 queries, payload validation, and aggregation helpers
|
||||
- `public/.assetsignore` - keeps Astro's private `_worker.js` bundle out of public asset uploads
|
||||
- `schema.sql` - D1 schema
|
||||
|
||||
## Setup
|
||||
|
||||
1. Install dependencies with `bun install`.
|
||||
2. Create a D1 database with `bunx wrangler d1 create meshcore_sar_rx_stats`.
|
||||
3. Apply the schema with `bunx wrangler d1 execute meshcore_sar_rx_stats --remote --file=./schema.sql`.
|
||||
4. Add the real D1 binding id to `wrangler.toml` when deploying.
|
||||
5. Build the dashboard with `bun run build`.
|
||||
6. Run checks with `bun run check`, `bun run test`, and `bun run typecheck`.
|
||||
|
||||
## Routes
|
||||
|
||||
- `GET /` - static Astro dashboard
|
||||
- `GET /api/dashboard?window=24h|7d|30d` - aggregated dashboard JSON
|
||||
- `POST /api/ingest` - anonymous RX stats ingest
|
||||
30
worker/astro.config.mjs
Normal file
30
worker/astro.config.mjs
Normal file
@@ -0,0 +1,30 @@
|
||||
import { defineConfig } from "astro/config";
|
||||
import cloudflare from "@astrojs/cloudflare";
|
||||
import react from "@astrojs/react";
|
||||
import tailwindcss from "@tailwindcss/vite";
|
||||
|
||||
export default defineConfig({
|
||||
imageService: "compile",
|
||||
integrations: [react()],
|
||||
vite: {
|
||||
cacheDir: ".astro/vite",
|
||||
plugins: [tailwindcss()],
|
||||
resolve: {
|
||||
alias: {
|
||||
"@": "/src",
|
||||
},
|
||||
},
|
||||
},
|
||||
build: {
|
||||
concurrency: 4,
|
||||
},
|
||||
server: {
|
||||
port: 4321,
|
||||
host: "0.0.0.0",
|
||||
allowedHosts: true,
|
||||
},
|
||||
devToolbar: {
|
||||
enabled: false,
|
||||
},
|
||||
adapter: cloudflare(),
|
||||
});
|
||||
1304
worker/bun.lock
Normal file
1304
worker/bun.lock
Normal file
File diff suppressed because it is too large
Load Diff
41
worker/package.json
Normal file
41
worker/package.json
Normal file
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"name": "meshcore-sar-stats",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"packageManager": "bun@1.3.8",
|
||||
"scripts": {
|
||||
"dev": "astro dev --host 0.0.0.0",
|
||||
"build": "astro build",
|
||||
"check": "astro check",
|
||||
"test": "bun test",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"deploy": "wrangler deploy"
|
||||
},
|
||||
"dependencies": {
|
||||
"@astrojs/check": "^0.9.6",
|
||||
"@astrojs/cloudflare": "^12.6.12",
|
||||
"@astrojs/react": "^4.4.2",
|
||||
"@radix-ui/react-slot": "^1.2.4",
|
||||
"@radix-ui/react-tabs": "^1.1.13",
|
||||
"@tailwindcss/vite": "^4.1.18",
|
||||
"@types/leaflet": "^1.9.21",
|
||||
"astro": "^5.17.1",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"leaflet": "^1.9.4",
|
||||
"react": "^19.2.0",
|
||||
"react-dom": "^19.2.0",
|
||||
"react-leaflet": "^5.0.0",
|
||||
"tailwind-merge": "^3.4.0",
|
||||
"tailwindcss": "^4.1.18"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@cloudflare/workers-types": "^4.20260403.1",
|
||||
"@types/bun": "^1.3.11",
|
||||
"@types/react": "^19.2.2",
|
||||
"@types/react-dom": "^19.2.2",
|
||||
"typescript": "^5.9.3",
|
||||
"wrangler": "^4.80.0"
|
||||
}
|
||||
}
|
||||
2
worker/public/.assetsignore
Normal file
2
worker/public/.assetsignore
Normal file
@@ -0,0 +1,2 @@
|
||||
_worker.js
|
||||
_routes.json
|
||||
BIN
worker/public/favicon.png
Normal file
BIN
worker/public/favicon.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 668 B |
42
worker/schema.sql
Normal file
42
worker/schema.sql
Normal file
@@ -0,0 +1,42 @@
|
||||
CREATE TABLE IF NOT EXISTS reports (
|
||||
report_id TEXT PRIMARY KEY,
|
||||
device_key6 TEXT NOT NULL,
|
||||
window_start TEXT NOT NULL,
|
||||
window_end TEXT NOT NULL,
|
||||
received_at TEXT NOT NULL,
|
||||
app_version TEXT,
|
||||
cf_country TEXT,
|
||||
cf_region TEXT,
|
||||
cf_city TEXT,
|
||||
cf_latitude REAL,
|
||||
cf_longitude REAL,
|
||||
cf_colo TEXT,
|
||||
pt_00 INTEGER NOT NULL DEFAULT 0,
|
||||
pt_01 INTEGER NOT NULL DEFAULT 0,
|
||||
pt_02 INTEGER NOT NULL DEFAULT 0,
|
||||
pt_03 INTEGER NOT NULL DEFAULT 0,
|
||||
pt_04 INTEGER NOT NULL DEFAULT 0,
|
||||
pt_05 INTEGER NOT NULL DEFAULT 0,
|
||||
pt_06 INTEGER NOT NULL DEFAULT 0,
|
||||
pt_07 INTEGER NOT NULL DEFAULT 0,
|
||||
pt_08 INTEGER NOT NULL DEFAULT 0,
|
||||
pt_09 INTEGER NOT NULL DEFAULT 0,
|
||||
pt_0a INTEGER NOT NULL DEFAULT 0,
|
||||
pt_0b INTEGER NOT NULL DEFAULT 0,
|
||||
pt_0c INTEGER NOT NULL DEFAULT 0,
|
||||
pt_0d INTEGER NOT NULL DEFAULT 0,
|
||||
pt_0e INTEGER NOT NULL DEFAULT 0,
|
||||
pt_0f INTEGER NOT NULL DEFAULT 0,
|
||||
decode_fail INTEGER NOT NULL DEFAULT 0,
|
||||
path_mode_1b INTEGER NOT NULL DEFAULT 0,
|
||||
path_mode_2b INTEGER NOT NULL DEFAULT 0,
|
||||
path_mode_3b INTEGER NOT NULL DEFAULT 0,
|
||||
path_mode_none INTEGER NOT NULL DEFAULT 0,
|
||||
path_mode_unknown INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_reports_device_window_end
|
||||
ON reports (device_key6, window_end);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_reports_window_end
|
||||
ON reports (window_end);
|
||||
904
worker/src/components/dashboard/dashboard-shell.tsx
Normal file
904
worker/src/components/dashboard/dashboard-shell.tsx
Normal file
@@ -0,0 +1,904 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
|
||||
type WindowKey = "24h" | "7d" | "30d";
|
||||
|
||||
type PacketTypeEntry = {
|
||||
key: string;
|
||||
label: string;
|
||||
total: number;
|
||||
};
|
||||
|
||||
type PathModeEntry = {
|
||||
key: string;
|
||||
label: string;
|
||||
total: number;
|
||||
};
|
||||
|
||||
type ReporterSummary = {
|
||||
key6: string;
|
||||
lastSeen: string;
|
||||
packetTotal: number;
|
||||
country: string;
|
||||
city: string;
|
||||
latitude: number | null;
|
||||
longitude: number | null;
|
||||
};
|
||||
|
||||
type ChartPoint = {
|
||||
label: string;
|
||||
totalPackets: number;
|
||||
reports: number;
|
||||
};
|
||||
|
||||
type LocationPoint = {
|
||||
key6: string;
|
||||
city: string;
|
||||
country: string;
|
||||
latitude: number;
|
||||
longitude: number;
|
||||
};
|
||||
|
||||
type AppVersionEntry = {
|
||||
version: string;
|
||||
reporters: number;
|
||||
packets: number;
|
||||
};
|
||||
|
||||
type TrafficComposition = {
|
||||
human: number;
|
||||
overhead: number;
|
||||
acks: number;
|
||||
};
|
||||
|
||||
type MultiHopRatio = {
|
||||
direct: number;
|
||||
multiHop: number;
|
||||
};
|
||||
|
||||
type CompositionPoint = {
|
||||
label: string;
|
||||
human: number;
|
||||
overhead: number;
|
||||
};
|
||||
|
||||
type DashboardResponse = {
|
||||
generatedAt: string;
|
||||
filter: {
|
||||
windowKey: WindowKey;
|
||||
label: string;
|
||||
sinceIso: string;
|
||||
bucket: "hour" | "day";
|
||||
};
|
||||
reportCount: number;
|
||||
uniqueDevices: number;
|
||||
decodedPackets: number;
|
||||
decodeFailures: number;
|
||||
packetTypeTotals: PacketTypeEntry[];
|
||||
pathModeTotals: PathModeEntry[];
|
||||
recentReporters: ReporterSummary[];
|
||||
chartPoints: ChartPoint[];
|
||||
locationPoints: LocationPoint[];
|
||||
appVersions: AppVersionEntry[];
|
||||
trafficComposition: TrafficComposition;
|
||||
multiHopRatio: MultiHopRatio;
|
||||
compositionOverTime: CompositionPoint[];
|
||||
};
|
||||
|
||||
const WINDOW_OPTIONS: Array<{ key: WindowKey; label: string }> = [
|
||||
{ key: "24h", label: "24h" },
|
||||
{ key: "7d", label: "7 days" },
|
||||
{ key: "30d", label: "30 days" },
|
||||
];
|
||||
|
||||
const PACKET_TYPE_INFO: Record<string, { title: string; summary: string }> = {
|
||||
pt_00: { title: "FLOOD REQUEST", summary: "Encrypted request to a known peer" },
|
||||
pt_01: { title: "FLOOD RESPONSE", summary: "Encrypted reply to a request" },
|
||||
pt_02: { title: "FLOOD TEXT", summary: "Encrypted direct text with timestamp and retry flags" },
|
||||
pt_03: { title: "FLOOD ACK", summary: "4-byte acknowledgement for an earlier message" },
|
||||
pt_04: { title: "FLOOD ADVERTISEMENT", summary: "Signed node identity broadcast" },
|
||||
pt_05: { title: "FLOOD GROUP_TEXT", summary: "Encrypted channel text matched by channel hash" },
|
||||
pt_06: { title: "FLOOD GROUP_DATA", summary: "Encrypted channel data with type and length" },
|
||||
pt_07: { title: "FLOOD ANON_REQUEST", summary: "Request using an ephemeral sender key" },
|
||||
pt_08: { title: "FLOOD RETURNED_PATH", summary: "Return route back to sender, with optional bundled ACK" },
|
||||
pt_09: { title: "FLOOD TRACE_PATH", summary: "Direct trace that records SNR at each hop" },
|
||||
pt_0a: { title: "FLOOD MULTIPART", summary: "Wrapper for one packet in a multipart sequence" },
|
||||
pt_0b: { title: "FLOOD CONTROL", summary: "Discovery or other control data" },
|
||||
pt_0c: { title: "RESERVED 0x0C", summary: "Reserved protocol type" },
|
||||
pt_0d: { title: "RESERVED 0x0D", summary: "Reserved protocol type" },
|
||||
pt_0e: { title: "RESERVED 0x0E", summary: "Reserved protocol type" },
|
||||
pt_0f: { title: "RAW CUSTOM", summary: "Application-defined custom packet" },
|
||||
};
|
||||
|
||||
const PATH_MODE_ICONS: Record<string, string> = {
|
||||
path_mode_1b: "1B",
|
||||
path_mode_2b: "2B",
|
||||
path_mode_3b: "3B",
|
||||
path_mode_none: "--",
|
||||
path_mode_unknown: "??",
|
||||
};
|
||||
|
||||
export function DashboardShell() {
|
||||
const [windowKey, setWindowKey] = useState<WindowKey>("24h");
|
||||
const [summary, setSummary] = useState<DashboardResponse | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let isCancelled = false;
|
||||
|
||||
async function load() {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const response = await fetch(`/api/dashboard?window=${windowKey}`, {
|
||||
headers: { accept: "application/json" },
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`Dashboard request failed (${response.status})`);
|
||||
}
|
||||
const nextSummary = (await response.json()) as DashboardResponse;
|
||||
if (!isCancelled) setSummary(nextSummary);
|
||||
} catch (nextError) {
|
||||
if (!isCancelled) {
|
||||
setError(nextError instanceof Error ? nextError.message : String(nextError));
|
||||
}
|
||||
} finally {
|
||||
if (!isCancelled) setIsLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
void load();
|
||||
return () => { isCancelled = true; };
|
||||
}, [windowKey]);
|
||||
|
||||
const activePacketTypes = useMemo(
|
||||
() => (summary?.packetTypeTotals ?? []).filter((e) => e.total > 0),
|
||||
[summary],
|
||||
);
|
||||
const activePathModes = useMemo(
|
||||
() => (summary?.pathModeTotals ?? []).filter((e) => e.total > 0),
|
||||
[summary],
|
||||
);
|
||||
const totalPackets = useMemo(
|
||||
() => (summary ? summary.decodedPackets + summary.decodeFailures : 0),
|
||||
[summary],
|
||||
);
|
||||
const decodeRate = totalPackets > 0
|
||||
? ((summary!.decodedPackets / totalPackets) * 100).toFixed(1)
|
||||
: "0";
|
||||
const maxTrend = Math.max(...(summary?.chartPoints ?? []).map((p) => p.totalPackets), 1);
|
||||
const multiHopTotal = (summary?.multiHopRatio.direct ?? 0) + (summary?.multiHopRatio.multiHop ?? 0);
|
||||
const multiHopPct = multiHopTotal > 0
|
||||
? ((summary!.multiHopRatio.multiHop / multiHopTotal) * 100).toFixed(1)
|
||||
: "0";
|
||||
const comp = summary?.trafficComposition;
|
||||
const compTotal = comp ? comp.human + comp.overhead + comp.acks : 0;
|
||||
const humanPct = compTotal > 0 ? ((comp!.human / compTotal) * 100).toFixed(1) : "0";
|
||||
const nodeCount = summary?.uniqueDevices ?? 0;
|
||||
const avgPerNode = nodeCount > 0 ? Math.round(totalPackets / nodeCount) : 0;
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-[1320px] px-5 py-8">
|
||||
<Tabs value={windowKey} onValueChange={(v) => setWindowKey(v as WindowKey)}>
|
||||
{/* Header */}
|
||||
<header className="mb-8 flex flex-wrap items-end justify-between gap-4">
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2.5">
|
||||
<img src="/favicon.png" alt="MeshCore SAR" className="h-8 w-8 rounded-lg" />
|
||||
<h1 className="text-2xl font-semibold tracking-tight">MeshCore SAR</h1>
|
||||
</div>
|
||||
<p className="max-w-xl text-sm text-muted-foreground">
|
||||
Aggregated observations from opt-in mesh nodes. Counts reflect what reporting nodes observed, not unique network packets.
|
||||
Ratios and percentages are statistically valid; absolute numbers scale with reporter count.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<TabsList className="h-9 rounded-full bg-secondary/60 p-1">
|
||||
{WINDOW_OPTIONS.map((o) => (
|
||||
<TabsTrigger key={o.key} value={o.key} className="rounded-full px-4 text-xs">
|
||||
{o.label}
|
||||
</TabsTrigger>
|
||||
))}
|
||||
</TabsList>
|
||||
{summary && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
Updated {formatRelative(summary.generatedAt)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{error && (
|
||||
<div className="mb-6 flex items-center gap-3 rounded-2xl border border-destructive/20 bg-destructive/10 px-5 py-3 text-sm text-destructive">
|
||||
<span className="flex-1">{error}</span>
|
||||
<Button size="sm" variant="outline" onClick={() => setWindowKey((c) => c)}>Retry</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<TabsContent value={windowKey} className="space-y-6">
|
||||
{/* Key metrics */}
|
||||
<section className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6">
|
||||
<MetricCard
|
||||
label="Reporting Nodes"
|
||||
value={nodeCount}
|
||||
note="Opt-in nodes in this window"
|
||||
/>
|
||||
<MetricCard
|
||||
label="Avg / Node"
|
||||
value={avgPerNode}
|
||||
note={`${totalPackets.toLocaleString()} total obs.`}
|
||||
/>
|
||||
<MetricCard
|
||||
label="Decode Rate"
|
||||
value={`${decodeRate}%`}
|
||||
note={`${summary?.decodeFailures ?? 0} failed`}
|
||||
/>
|
||||
<MetricCard
|
||||
label="Multi-Hop"
|
||||
value={`${multiHopPct}%`}
|
||||
note="Relayed through mesh"
|
||||
/>
|
||||
<MetricCard
|
||||
label="Messages"
|
||||
value={`${humanPct}%`}
|
||||
note="Text + group text"
|
||||
/>
|
||||
<MetricCard
|
||||
label="Protocol Types"
|
||||
value={activePacketTypes.length}
|
||||
note="of 16 types observed"
|
||||
/>
|
||||
</section>
|
||||
|
||||
{/* Traffic breakdown */}
|
||||
<section className="space-y-4">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Traffic Breakdown</CardTitle>
|
||||
<CardDescription>Observed traffic composition across all reporting nodes</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-5">
|
||||
{comp && compTotal > 0 ? (
|
||||
<>
|
||||
<div className="flex h-6 overflow-hidden rounded-full">
|
||||
<div className="bg-primary" style={{ width: `${(comp.human / compTotal) * 100}%` }} title={`Messages: ${comp.human}`} />
|
||||
<div className="bg-amber-400" style={{ width: `${(comp.acks / compTotal) * 100}%` }} title={`Acks: ${comp.acks}`} />
|
||||
<div className="bg-secondary" style={{ width: `${(comp.overhead / compTotal) * 100}%` }} title={`Overhead: ${comp.overhead}`} />
|
||||
</div>
|
||||
<div className="grid grid-cols-3 gap-3 text-center">
|
||||
<div>
|
||||
<div className="mx-auto mb-1 h-2.5 w-2.5 rounded-full bg-primary" />
|
||||
<div className="text-lg font-semibold tabular-nums">{comp.human.toLocaleString()}</div>
|
||||
<div className="text-xs text-muted-foreground">Messages</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="mx-auto mb-1 h-2.5 w-2.5 rounded-full bg-amber-400" />
|
||||
<div className="text-lg font-semibold tabular-nums">{comp.acks.toLocaleString()}</div>
|
||||
<div className="text-xs text-muted-foreground">Acks</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="mx-auto mb-1 h-2.5 w-2.5 rounded-full bg-secondary" />
|
||||
<div className="text-lg font-semibold tabular-nums">{comp.overhead.toLocaleString()}</div>
|
||||
<div className="text-xs text-muted-foreground">Overhead</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<EmptyState label="No traffic data yet." />
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Messages vs Protocol Overhead</CardTitle>
|
||||
<CardDescription>
|
||||
Human messages (text + group text) compared to protocol overhead (acks, advertisements, routing, control) over time.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{summary?.compositionOverTime.length ? (
|
||||
<CompositionChart points={summary.compositionOverTime} />
|
||||
) : (
|
||||
<EmptyState label="No composition data yet." />
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</section>
|
||||
|
||||
{/* Protocol breakdown */}
|
||||
<section className="space-y-4">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Protocol Packet Types</CardTitle>
|
||||
<CardDescription>
|
||||
MeshCore protocol uses 16 packet type codes (0x00 - 0x0F).
|
||||
Showing types with traffic in this window.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{activePacketTypes.length ? (
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
{activePacketTypes.map((entry) => {
|
||||
const pct = totalPackets > 0 ? ((entry.total / totalPackets) * 100).toFixed(1) : "0";
|
||||
const info = PACKET_TYPE_INFO[entry.key];
|
||||
return (
|
||||
<div key={entry.key} className="flex gap-3 rounded-xl border border-border/50 bg-secondary/30 p-3">
|
||||
<div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-xs font-mono font-semibold text-primary">
|
||||
{entry.key.replace("pt_", "0x").toUpperCase()}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-baseline justify-between gap-2">
|
||||
<span className="text-sm font-medium">{entry.label}</span>
|
||||
<span className="shrink-0 text-xs text-muted-foreground">{pct}%</span>
|
||||
</div>
|
||||
<div className="mt-0.5 font-mono text-[0.65rem] text-muted-foreground/70">
|
||||
{info?.title ?? entry.key}
|
||||
</div>
|
||||
<p className="mt-0.5 text-xs text-muted-foreground">
|
||||
{info?.summary ?? ""}
|
||||
</p>
|
||||
<div className="mt-1.5 flex items-center gap-2">
|
||||
<div className="h-1.5 flex-1 overflow-hidden rounded-full bg-secondary">
|
||||
<div
|
||||
className="h-full rounded-full bg-primary/70"
|
||||
style={{ width: `${pct}%` }}
|
||||
/>
|
||||
</div>
|
||||
<span className="text-xs font-semibold tabular-nums">{entry.total.toLocaleString()} obs.</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<EmptyState label="No packet data yet." />
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Path Routing Modes</CardTitle>
|
||||
<CardDescription>
|
||||
Path hash byte length determines routing precision.
|
||||
Longer hashes allow more specific multi-hop paths.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{activePathModes.length ? (
|
||||
<div className="grid grid-cols-2 gap-3 sm:grid-cols-5">
|
||||
{activePathModes.map((entry) => {
|
||||
const pct = totalPackets > 0 ? ((entry.total / totalPackets) * 100).toFixed(1) : "0";
|
||||
return (
|
||||
<div key={entry.key} className="rounded-xl border border-border/50 bg-secondary/30 p-4 text-center">
|
||||
<div className="mx-auto mb-2 flex h-10 w-10 items-center justify-center rounded-full bg-primary/10 text-sm font-bold text-primary">
|
||||
{PATH_MODE_ICONS[entry.key] ?? "?"}
|
||||
</div>
|
||||
<div className="text-lg font-semibold tabular-nums">{entry.total.toLocaleString()}</div>
|
||||
<div className="mt-0.5 text-xs text-muted-foreground">{entry.label}</div>
|
||||
<div className="mt-1 text-xs text-muted-foreground">{pct}%</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<EmptyState label="No path mode samples." />
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</section>
|
||||
|
||||
{/* Map + Traffic trend */}
|
||||
<section className="space-y-4">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Reporter Locations</CardTitle>
|
||||
<CardDescription>
|
||||
Approximate locations from Cloudflare edge nodes, not device GPS.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<ReporterMap locations={summary?.locationPoints ?? []} />
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Observations Over Time</CardTitle>
|
||||
<CardDescription>
|
||||
Per-node average observations per {summary?.filter.bucket ?? "time"} bucket.
|
||||
Normalizing by reporter count removes the bias of more nodes = higher numbers.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{isLoading && !summary ? (
|
||||
<EmptyState label="Loading..." />
|
||||
) : summary?.chartPoints.length ? (
|
||||
<TrafficChart points={summary.chartPoints} maxValue={maxTrend} />
|
||||
) : (
|
||||
<EmptyState label="No data for this window." />
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</section>
|
||||
|
||||
{/* App versions */}
|
||||
<section>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>App Versions</CardTitle>
|
||||
<CardDescription>Distribution of reporting app versions by node count and observations</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{summary?.appVersions.length ? (
|
||||
<div className="space-y-3">
|
||||
{summary.appVersions.map((entry) => {
|
||||
const maxPkts = summary.appVersions[0].packets;
|
||||
return (
|
||||
<div key={entry.version} className="space-y-1.5">
|
||||
<div className="flex items-baseline justify-between gap-3 text-sm">
|
||||
<span className="font-mono font-medium">{entry.version}</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{entry.reporters} {entry.reporters === 1 ? "node" : "nodes"} / {entry.packets.toLocaleString()} obs.
|
||||
</span>
|
||||
</div>
|
||||
<div className="h-2 overflow-hidden rounded-full bg-secondary">
|
||||
<div
|
||||
className="h-full rounded-full bg-primary/70"
|
||||
style={{ width: `${(entry.packets / maxPkts) * 100}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<EmptyState label="No version data yet." />
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</section>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// --- Composition stacked area chart ---
|
||||
|
||||
function CompositionChart({ points }: { points: CompositionPoint[] }) {
|
||||
const [hover, setHover] = useState<number | null>(null);
|
||||
const count = points.length;
|
||||
if (count === 0) return null;
|
||||
|
||||
const maxVal = Math.max(...points.map((p) => p.human + p.overhead), 1);
|
||||
const innerW = 100;
|
||||
const innerH = 188;
|
||||
const pad = { top: 16, right: 16, bottom: 32, left: 48 };
|
||||
|
||||
const xs = points.map((_, i) => i / Math.max(count - 1, 1));
|
||||
|
||||
// stacked: overhead on bottom, human on top
|
||||
const overheadYs = points.map((p) => 1 - p.overhead / maxVal);
|
||||
const totalYs = points.map((p) => 1 - (p.overhead + p.human) / maxVal);
|
||||
|
||||
const overheadArea = buildAreaPath(xs, overheadYs, innerW, innerH);
|
||||
const humanArea = buildStackedAreaPath(xs, totalYs, overheadYs, innerW, innerH);
|
||||
|
||||
const labelStep = Math.max(1, Math.floor(count / 6));
|
||||
const gridLines = niceGridLines(maxVal, 3);
|
||||
|
||||
return (
|
||||
<div className="relative select-none">
|
||||
<svg
|
||||
viewBox={`${-pad.left} ${-pad.top} ${innerW + pad.left + pad.right} ${innerH + pad.top + pad.bottom}`}
|
||||
className="h-auto max-h-[280px] w-full"
|
||||
preserveAspectRatio="xMidYMid meet"
|
||||
onMouseLeave={() => setHover(null)}
|
||||
>
|
||||
<defs>
|
||||
<linearGradient id="humanFill" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0%" stopColor="hsl(var(--chart-primary))" stopOpacity={0.5} />
|
||||
<stop offset="100%" stopColor="hsl(var(--chart-primary))" stopOpacity={0.1} />
|
||||
</linearGradient>
|
||||
<linearGradient id="overheadFill" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0%" stopColor="hsl(var(--chart-secondary))" stopOpacity={0.5} />
|
||||
<stop offset="100%" stopColor="hsl(var(--chart-secondary))" stopOpacity={0.1} />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
|
||||
{gridLines.map((val) => {
|
||||
const y = (1 - val / maxVal) * innerH;
|
||||
return (
|
||||
<g key={val}>
|
||||
<line x1={0} y1={y} x2={innerW} y2={y} stroke="hsl(var(--chart-grid))" strokeWidth={0.3} />
|
||||
<text x={-6} y={y} textAnchor="end" dominantBaseline="middle" fill="hsl(var(--chart-label))" fontSize={3.2} fontFamily="var(--font-sans)">
|
||||
{formatCompact(val)}
|
||||
</text>
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
<line x1={0} y1={innerH} x2={innerW} y2={innerH} stroke="hsl(var(--chart-grid))" strokeWidth={0.4} />
|
||||
|
||||
<path d={overheadArea} fill="url(#overheadFill)" />
|
||||
<path d={humanArea} fill="url(#humanFill)" />
|
||||
|
||||
{/* X labels */}
|
||||
{points.map((p, i) => (i % labelStep === 0 || i === count - 1) ? (
|
||||
<text key={i} x={xs[i] * innerW} y={innerH + 10} textAnchor="middle" fill="hsl(var(--chart-label))" fontSize={2.8} fontFamily="var(--font-sans)">
|
||||
{p.label.slice(5)}
|
||||
</text>
|
||||
) : null)}
|
||||
|
||||
{/* hover zones */}
|
||||
{points.map((point, i) => (
|
||||
<rect
|
||||
key={point.label}
|
||||
x={xs[i] * innerW - innerW / count / 2}
|
||||
y={0}
|
||||
width={innerW / count}
|
||||
height={innerH}
|
||||
fill="transparent"
|
||||
onMouseEnter={() => setHover(i)}
|
||||
/>
|
||||
))}
|
||||
|
||||
{hover !== null && (
|
||||
<line x1={xs[hover] * innerW} y1={0} x2={xs[hover] * innerW} y2={innerH} stroke="hsl(var(--chart-primary))" strokeWidth={0.3} strokeDasharray="1.5 1" />
|
||||
)}
|
||||
</svg>
|
||||
|
||||
{hover !== null && (
|
||||
<div
|
||||
className="pointer-events-none absolute -top-2 z-10 -translate-x-1/2 rounded-lg border border-border/50 bg-card px-3 py-1.5 text-xs shadow-lg"
|
||||
style={{ left: `${(pad.left + xs[hover] * innerW) / (innerW + pad.left + pad.right) * 100}%` }}
|
||||
>
|
||||
<div className="font-semibold">{points[hover].label}</div>
|
||||
<div className="flex items-center gap-1.5"><span className="inline-block h-2 w-2 rounded-full bg-primary" /> Messages: {points[hover].human.toLocaleString()}</div>
|
||||
<div className="flex items-center gap-1.5"><span className="inline-block h-2 w-2 rounded-full bg-secondary" /> Overhead: {points[hover].overhead.toLocaleString()}</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="mt-2 flex items-center justify-center gap-4 text-xs text-muted-foreground">
|
||||
<span className="flex items-center gap-1.5"><span className="inline-block h-2.5 w-2.5 rounded-full bg-primary/60" /> Messages</span>
|
||||
<span className="flex items-center gap-1.5"><span className="inline-block h-2.5 w-2.5 rounded-full bg-secondary/70" /> Overhead</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function buildAreaPath(xs: number[], ys: number[], w: number, h: number): string {
|
||||
const line = xs.map((x, i) => `${i === 0 ? "M" : "L"}${x * w},${ys[i] * h}`).join(" ");
|
||||
return `${line} L${xs[xs.length - 1] * w},${h} L0,${h} Z`;
|
||||
}
|
||||
|
||||
function buildStackedAreaPath(xs: number[], topYs: number[], bottomYs: number[], w: number, h: number): string {
|
||||
const top = xs.map((x, i) => `${i === 0 ? "M" : "L"}${x * w},${topYs[i] * h}`).join(" ");
|
||||
const bottom = [...xs].reverse().map((x, i) => `L${x * w},${bottomYs[xs.length - 1 - i] * h}`).join(" ");
|
||||
return `${top} ${bottom} Z`;
|
||||
}
|
||||
|
||||
// --- Traffic trend chart ---
|
||||
|
||||
const CHART_H = 240;
|
||||
const CHART_PAD = { top: 20, right: 16, bottom: 32, left: 48 };
|
||||
|
||||
function TrafficChart({ points, maxValue: _rawMax }: { points: ChartPoint[]; maxValue: number }) {
|
||||
const [hover, setHover] = useState<number | null>(null);
|
||||
const count = points.length;
|
||||
if (count === 0) return null;
|
||||
|
||||
// Normalize: per-node average per bucket
|
||||
const normalized = points.map((p) => ({
|
||||
...p,
|
||||
perNode: p.reports > 0 ? Math.round(p.totalPackets / p.reports) : 0,
|
||||
}));
|
||||
const maxValue = Math.max(...normalized.map((p) => p.perNode), 1);
|
||||
|
||||
const innerW = 100;
|
||||
const innerH = CHART_H - CHART_PAD.top - CHART_PAD.bottom;
|
||||
|
||||
const peakIdx = normalized.reduce((best, p, i) => (p.perNode > normalized[best].perNode ? i : best), 0);
|
||||
|
||||
const gridLines = niceGridLines(maxValue, 4);
|
||||
|
||||
const xs = normalized.map((_, i) => i / Math.max(count - 1, 1));
|
||||
const ys = normalized.map((p) => 1 - p.perNode / maxValue);
|
||||
|
||||
const linePath = xs.map((x, i) => `${i === 0 ? "M" : "L"}${x * innerW},${ys[i] * innerH}`).join(" ");
|
||||
const areaPath = `${linePath} L${xs[xs.length - 1] * innerW},${innerH} L0,${innerH} Z`;
|
||||
|
||||
// X-axis labels: show ~6 evenly spaced
|
||||
const labelStep = Math.max(1, Math.floor(count / 6));
|
||||
const xLabels = points
|
||||
.map((p, i) => ({ i, label: p.label.slice(5) }))
|
||||
.filter((_, i) => i % labelStep === 0 || i === count - 1);
|
||||
|
||||
return (
|
||||
<div className="relative select-none">
|
||||
<svg
|
||||
viewBox={`${-CHART_PAD.left} ${-CHART_PAD.top} ${innerW + CHART_PAD.left + CHART_PAD.right} ${CHART_H}`}
|
||||
className="h-auto max-h-[280px] w-full"
|
||||
preserveAspectRatio="xMidYMid meet"
|
||||
onMouseLeave={() => setHover(null)}
|
||||
>
|
||||
<defs>
|
||||
<linearGradient id="areaFill" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0%" stopColor="hsl(var(--chart-primary))" stopOpacity={0.35} />
|
||||
<stop offset="100%" stopColor="hsl(var(--chart-primary))" stopOpacity={0.03} />
|
||||
</linearGradient>
|
||||
<linearGradient id="lineStroke" x1="0" y1="0" x2="1" y2="0">
|
||||
<stop offset="0%" stopColor="hsl(var(--chart-primary-light))" />
|
||||
<stop offset="100%" stopColor="hsl(var(--chart-primary-dark))" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
|
||||
{/* Y grid lines */}
|
||||
{gridLines.map((val) => {
|
||||
const y = (1 - val / maxValue) * innerH;
|
||||
return (
|
||||
<g key={val}>
|
||||
<line x1={0} y1={y} x2={innerW} y2={y} stroke="hsl(var(--chart-grid))" strokeWidth={0.3} />
|
||||
<text x={-6} y={y} textAnchor="end" dominantBaseline="middle" fill="hsl(var(--chart-label))" fontSize={3.2} fontFamily="var(--font-sans)">
|
||||
{formatCompact(val)}
|
||||
</text>
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* baseline */}
|
||||
<line x1={0} y1={innerH} x2={innerW} y2={innerH} stroke="hsl(var(--chart-grid))" strokeWidth={0.4} />
|
||||
|
||||
{/* area fill */}
|
||||
<path d={areaPath} fill="url(#areaFill)" />
|
||||
|
||||
{/* line */}
|
||||
<path d={linePath} fill="none" stroke="url(#lineStroke)" strokeWidth={0.7} strokeLinecap="round" strokeLinejoin="round" />
|
||||
|
||||
{/* peak dot */}
|
||||
<circle
|
||||
cx={xs[peakIdx] * innerW}
|
||||
cy={ys[peakIdx] * innerH}
|
||||
r={1.5}
|
||||
fill="hsl(var(--chart-primary))"
|
||||
stroke="white"
|
||||
strokeWidth={0.6}
|
||||
/>
|
||||
|
||||
{/* peak label */}
|
||||
<text
|
||||
x={xs[peakIdx] * innerW}
|
||||
y={ys[peakIdx] * innerH - 4}
|
||||
textAnchor="middle"
|
||||
fill="hsl(var(--chart-primary-accent))"
|
||||
fontSize={3}
|
||||
fontWeight={600}
|
||||
fontFamily="var(--font-sans)"
|
||||
>
|
||||
{normalized[peakIdx].perNode.toLocaleString()}
|
||||
</text>
|
||||
|
||||
{/* X-axis labels */}
|
||||
{xLabels.map(({ i, label }) => (
|
||||
<text
|
||||
key={i}
|
||||
x={xs[i] * innerW}
|
||||
y={innerH + 10}
|
||||
textAnchor="middle"
|
||||
fill="hsl(var(--chart-label))"
|
||||
fontSize={2.8}
|
||||
fontFamily="var(--font-sans)"
|
||||
>
|
||||
{label}
|
||||
</text>
|
||||
))}
|
||||
|
||||
{/* invisible hover zones */}
|
||||
{points.map((point, i) => {
|
||||
const sliceW = innerW / count;
|
||||
return (
|
||||
<rect
|
||||
key={point.label}
|
||||
x={xs[i] * innerW - sliceW / 2}
|
||||
y={0}
|
||||
width={sliceW}
|
||||
height={innerH}
|
||||
fill="transparent"
|
||||
onMouseEnter={() => setHover(i)}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* hover indicator */}
|
||||
{hover !== null && (
|
||||
<>
|
||||
<line
|
||||
x1={xs[hover] * innerW}
|
||||
y1={0}
|
||||
x2={xs[hover] * innerW}
|
||||
y2={innerH}
|
||||
stroke="hsl(var(--chart-primary))"
|
||||
strokeWidth={0.3}
|
||||
strokeDasharray="1.5 1"
|
||||
/>
|
||||
<circle
|
||||
cx={xs[hover] * innerW}
|
||||
cy={ys[hover] * innerH}
|
||||
r={1.2}
|
||||
fill="white"
|
||||
stroke="hsl(var(--chart-primary))"
|
||||
strokeWidth={0.6}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</svg>
|
||||
|
||||
{/* hover tooltip */}
|
||||
{hover !== null && (
|
||||
<div
|
||||
className="pointer-events-none absolute -top-2 z-10 -translate-x-1/2 rounded-lg border border-border/50 bg-card px-3 py-1.5 text-xs shadow-lg"
|
||||
style={{
|
||||
left: `${(CHART_PAD.left + xs[hover] * innerW) / (innerW + CHART_PAD.left + CHART_PAD.right) * 100}%`,
|
||||
}}
|
||||
>
|
||||
<div className="font-semibold tabular-nums">{normalized[hover].perNode.toLocaleString()} avg/node</div>
|
||||
<div className="text-muted-foreground">{normalized[hover].totalPackets.toLocaleString()} total from {normalized[hover].reports} {normalized[hover].reports === 1 ? "node" : "nodes"}</div>
|
||||
<div className="text-muted-foreground">{normalized[hover].label}</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function niceGridLines(max: number, count: number): number[] {
|
||||
if (max <= 0) return [0];
|
||||
const rough = max / count;
|
||||
const magnitude = 10 ** Math.floor(Math.log10(rough));
|
||||
const residual = rough / magnitude;
|
||||
const nice = residual <= 1.5 ? 1 : residual <= 3 ? 2 : residual <= 7 ? 5 : 10;
|
||||
const step = nice * magnitude;
|
||||
const lines: number[] = [];
|
||||
for (let v = step; v <= max; v += step) {
|
||||
lines.push(Math.round(v));
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
function formatCompact(n: number): string {
|
||||
if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
|
||||
if (n >= 1_000) return `${(n / 1_000).toFixed(n >= 10_000 ? 0 : 1)}K`;
|
||||
return String(n);
|
||||
}
|
||||
|
||||
function MetricCard({ label, value, note }: { label: string; value: number | string; note: string }) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="gap-1.5">
|
||||
<CardDescription className="text-xs uppercase tracking-wider">{label}</CardDescription>
|
||||
<CardTitle className="text-3xl tabular-nums">{typeof value === "number" ? value.toLocaleString() : value}</CardTitle>
|
||||
<CardDescription>{note}</CardDescription>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function EmptyState({ label }: { label: string }) {
|
||||
return (
|
||||
<div className="rounded-2xl border border-dashed border-border bg-secondary/20 px-4 py-8 text-center text-sm text-muted-foreground">
|
||||
{label}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ReporterMap({ locations }: { locations: LocationPoint[] }) {
|
||||
const [mounted, setMounted] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setMounted(true);
|
||||
}, []);
|
||||
|
||||
if (!mounted || typeof window === "undefined") {
|
||||
return (
|
||||
<div className="flex min-h-[360px] items-center justify-center rounded-xl bg-secondary/30 text-sm text-muted-foreground">
|
||||
Loading map...
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return <LeafletMap locations={locations} />;
|
||||
}
|
||||
|
||||
function LeafletMap({ locations }: { locations: LocationPoint[] }) {
|
||||
const [leaflet, setLeaflet] = useState<{
|
||||
MapContainer: typeof import("react-leaflet").MapContainer;
|
||||
TileLayer: typeof import("react-leaflet").TileLayer;
|
||||
CircleMarker: typeof import("react-leaflet").CircleMarker;
|
||||
Tooltip: typeof import("react-leaflet").Tooltip;
|
||||
L: typeof import("leaflet");
|
||||
} | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
Promise.all([
|
||||
import("react-leaflet"),
|
||||
import("leaflet"),
|
||||
]).then(([rl, L]) => {
|
||||
setLeaflet({
|
||||
MapContainer: rl.MapContainer,
|
||||
TileLayer: rl.TileLayer,
|
||||
CircleMarker: rl.CircleMarker,
|
||||
Tooltip: rl.Tooltip,
|
||||
L: L.default ?? L,
|
||||
});
|
||||
});
|
||||
}, []);
|
||||
|
||||
if (!leaflet) {
|
||||
return (
|
||||
<div className="flex min-h-[360px] items-center justify-center rounded-xl bg-secondary/30 text-sm text-muted-foreground">
|
||||
Loading map...
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const { MapContainer, TileLayer, CircleMarker, Tooltip } = leaflet;
|
||||
|
||||
const center: [number, number] = locations.length
|
||||
? [
|
||||
locations.reduce((s, l) => s + l.latitude, 0) / locations.length,
|
||||
locations.reduce((s, l) => s + l.longitude, 0) / locations.length,
|
||||
]
|
||||
: [46.0, 14.5];
|
||||
|
||||
return (
|
||||
<>
|
||||
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
|
||||
<div className="overflow-hidden rounded-xl">
|
||||
<MapContainer
|
||||
center={center}
|
||||
zoom={locations.length > 1 ? 4 : 8}
|
||||
scrollWheelZoom={true}
|
||||
style={{ height: 360, width: "100%" }}
|
||||
attributionControl={true}
|
||||
>
|
||||
<TileLayer
|
||||
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'
|
||||
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
|
||||
/>
|
||||
{locations.map((loc) => (
|
||||
<CircleMarker
|
||||
key={`${loc.latitude}-${loc.longitude}-${loc.city}`}
|
||||
center={[loc.latitude, loc.longitude]}
|
||||
radius={8}
|
||||
pathOptions={{
|
||||
color: "hsl(217, 91%, 60%)",
|
||||
fillColor: "hsl(217, 91%, 70%)",
|
||||
fillOpacity: 0.6,
|
||||
weight: 2,
|
||||
}}
|
||||
>
|
||||
<Tooltip>
|
||||
{loc.city}, {loc.country}
|
||||
</Tooltip>
|
||||
</CircleMarker>
|
||||
))}
|
||||
</MapContainer>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function formatRelative(value: string) {
|
||||
const diffMs = Date.now() - new Date(value).getTime();
|
||||
const diffMin = Math.floor(diffMs / 60000);
|
||||
if (diffMin < 1) return "just now";
|
||||
if (diffMin < 60) return `${diffMin}m ago`;
|
||||
const diffHr = Math.floor(diffMin / 60);
|
||||
if (diffHr < 24) return `${diffHr}h ago`;
|
||||
return `${Math.floor(diffHr / 24)}d ago`;
|
||||
}
|
||||
31
worker/src/components/ui/badge.tsx
Normal file
31
worker/src/components/ui/badge.tsx
Normal file
@@ -0,0 +1,31 @@
|
||||
import * as React from "react";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const badgeVariants = cva(
|
||||
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "border-transparent bg-primary text-primary-foreground",
|
||||
secondary: "border-transparent bg-secondary text-secondary-foreground",
|
||||
destructive: "border-transparent bg-destructive text-destructive-foreground",
|
||||
outline: "text-foreground bg-card/60",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
export interface BadgeProps
|
||||
extends React.HTMLAttributes<HTMLDivElement>,
|
||||
VariantProps<typeof badgeVariants> {}
|
||||
|
||||
function Badge({ className, variant, ...props }: BadgeProps) {
|
||||
return <div className={cn(badgeVariants({ variant }), className)} {...props} />;
|
||||
}
|
||||
|
||||
export { Badge, badgeVariants };
|
||||
54
worker/src/components/ui/button.tsx
Normal file
54
worker/src/components/ui/button.tsx
Normal file
@@ -0,0 +1,54 @@
|
||||
import * as React from "react";
|
||||
import { Slot } from "@radix-ui/react-slot";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
type ButtonProps = React.ComponentProps<"button"> &
|
||||
VariantProps<typeof buttonVariants> & {
|
||||
asChild?: boolean;
|
||||
};
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all cursor-pointer disabled:pointer-events-none disabled:opacity-50 outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-primary text-primary-foreground hover:bg-primary/90",
|
||||
destructive: "bg-destructive text-destructive-foreground hover:bg-destructive/90",
|
||||
outline: "border bg-card hover:bg-muted",
|
||||
secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/90",
|
||||
ghost: "hover:bg-muted",
|
||||
},
|
||||
size: {
|
||||
default: "h-9 px-4 py-2",
|
||||
sm: "h-8 rounded-md px-3",
|
||||
lg: "h-10 rounded-md px-6",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
function Button({
|
||||
className,
|
||||
variant,
|
||||
size,
|
||||
asChild = false,
|
||||
...props
|
||||
}: ButtonProps) {
|
||||
const Comp = asChild ? Slot : "button";
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="button"
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Button, buttonVariants, type ButtonProps };
|
||||
52
worker/src/components/ui/card.tsx
Normal file
52
worker/src/components/ui/card.tsx
Normal file
@@ -0,0 +1,52 @@
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
function Card({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card"
|
||||
className={cn(
|
||||
"bg-card/88 text-card-foreground flex flex-col gap-6 rounded-[1.5rem] border border-border/50 py-6 shadow-[0_18px_48px_rgba(16,33,47,0.08)] dark:shadow-[0_18px_48px_rgba(0,0,0,0.3)] backdrop-blur-md",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-header"
|
||||
className={cn("grid auto-rows-min items-start gap-2 px-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-title"
|
||||
className={cn("leading-none font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return <div data-slot="card-content" className={cn("px-6", className)} {...props} />;
|
||||
}
|
||||
|
||||
export { Card, CardHeader, CardTitle, CardDescription, CardContent };
|
||||
64
worker/src/components/ui/table.tsx
Normal file
64
worker/src/components/ui/table.tsx
Normal file
@@ -0,0 +1,64 @@
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const Table = React.forwardRef<HTMLTableElement, React.HTMLAttributes<HTMLTableElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<div className="relative w-full overflow-auto">
|
||||
<table ref={ref} className={cn("w-full caption-bottom text-sm", className)} {...props} />
|
||||
</div>
|
||||
),
|
||||
);
|
||||
Table.displayName = "Table";
|
||||
|
||||
const TableHeader = React.forwardRef<
|
||||
HTMLTableSectionElement,
|
||||
React.HTMLAttributes<HTMLTableSectionElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<thead ref={ref} className={cn("[&_tr]:border-b", className)} {...props} />
|
||||
));
|
||||
TableHeader.displayName = "TableHeader";
|
||||
|
||||
const TableBody = React.forwardRef<
|
||||
HTMLTableSectionElement,
|
||||
React.HTMLAttributes<HTMLTableSectionElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<tbody ref={ref} className={cn("[&_tr:last-child]:border-0", className)} {...props} />
|
||||
));
|
||||
TableBody.displayName = "TableBody";
|
||||
|
||||
const TableRow = React.forwardRef<HTMLTableRowElement, React.HTMLAttributes<HTMLTableRowElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<tr
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"border-b transition-colors hover:bg-muted/50",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
),
|
||||
);
|
||||
TableRow.displayName = "TableRow";
|
||||
|
||||
const TableHead = React.forwardRef<
|
||||
HTMLTableCellElement,
|
||||
React.ThHTMLAttributes<HTMLTableCellElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<th
|
||||
ref={ref}
|
||||
className={cn("h-12 px-4 text-left align-middle font-medium text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
TableHead.displayName = "TableHead";
|
||||
|
||||
const TableCell = React.forwardRef<
|
||||
HTMLTableCellElement,
|
||||
React.TdHTMLAttributes<HTMLTableCellElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<td ref={ref} className={cn("p-4 align-middle", className)} {...props} />
|
||||
));
|
||||
TableCell.displayName = "TableCell";
|
||||
|
||||
export { Table, TableHeader, TableBody, TableRow, TableHead, TableCell };
|
||||
50
worker/src/components/ui/tabs.tsx
Normal file
50
worker/src/components/ui/tabs.tsx
Normal file
@@ -0,0 +1,50 @@
|
||||
import * as React from "react";
|
||||
import * as TabsPrimitive from "@radix-ui/react-tabs";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const Tabs = TabsPrimitive.Root;
|
||||
|
||||
const TabsList = React.forwardRef<
|
||||
React.ComponentRef<typeof TabsPrimitive.List>,
|
||||
React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<TabsPrimitive.List
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"inline-flex h-11 items-center justify-center rounded-full border border-white/70 bg-white/60 p-1 text-muted-foreground shadow-sm backdrop-blur",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
TabsList.displayName = TabsPrimitive.List.displayName;
|
||||
|
||||
const TabsTrigger = React.forwardRef<
|
||||
React.ComponentRef<typeof TabsPrimitive.Trigger>,
|
||||
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<TabsPrimitive.Trigger
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"inline-flex items-center justify-center whitespace-nowrap rounded-full px-4 py-2 text-sm font-medium transition-all focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-primary data-[state=active]:text-primary-foreground data-[state=active]:shadow-sm",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName;
|
||||
|
||||
const TabsContent = React.forwardRef<
|
||||
React.ComponentRef<typeof TabsPrimitive.Content>,
|
||||
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<TabsPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn("mt-6 focus-visible:outline-none", className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
TabsContent.displayName = TabsPrimitive.Content.displayName;
|
||||
|
||||
export { Tabs, TabsList, TabsTrigger, TabsContent };
|
||||
99
worker/src/index.css
Normal file
99
worker/src/index.css
Normal file
@@ -0,0 +1,99 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
@theme {
|
||||
--font-sans: "IBM Plex Sans", "Avenir Next", "Segoe UI", sans-serif;
|
||||
--font-mono: "IBM Plex Mono", "SFMono-Regular", monospace;
|
||||
|
||||
--color-border: hsl(var(--border));
|
||||
--color-input: hsl(var(--input));
|
||||
--color-ring: hsl(var(--ring));
|
||||
--color-background: hsl(var(--background));
|
||||
--color-foreground: hsl(var(--foreground));
|
||||
--color-primary: hsl(var(--primary));
|
||||
--color-primary-foreground: hsl(var(--primary-foreground));
|
||||
--color-secondary: hsl(var(--secondary));
|
||||
--color-secondary-foreground: hsl(var(--secondary-foreground));
|
||||
--color-muted: hsl(var(--muted));
|
||||
--color-muted-foreground: hsl(var(--muted-foreground));
|
||||
--color-accent: hsl(var(--accent));
|
||||
--color-accent-foreground: hsl(var(--accent-foreground));
|
||||
--color-destructive: hsl(var(--destructive));
|
||||
--color-destructive-foreground: hsl(var(--destructive-foreground));
|
||||
--color-card: hsl(var(--card));
|
||||
--color-card-foreground: hsl(var(--card-foreground));
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
}
|
||||
|
||||
@layer base {
|
||||
:root {
|
||||
--background: 220 33% 97%;
|
||||
--foreground: 222 47% 11%;
|
||||
--card: 0 0% 100%;
|
||||
--card-foreground: 222 47% 11%;
|
||||
--primary: 217 91% 60%;
|
||||
--primary-foreground: 0 0% 100%;
|
||||
--secondary: 220 50% 93%;
|
||||
--secondary-foreground: 222 47% 11%;
|
||||
--muted: 220 26% 93%;
|
||||
--muted-foreground: 220 13% 46%;
|
||||
--accent: 217 91% 60%;
|
||||
--accent-foreground: 0 0% 100%;
|
||||
--destructive: 0 72% 51%;
|
||||
--destructive-foreground: 0 0% 100%;
|
||||
--border: 220 20% 88%;
|
||||
--input: 220 20% 88%;
|
||||
--ring: 217 91% 60%;
|
||||
--radius: 1rem;
|
||||
--chart-grid: 220 20% 88%;
|
||||
--chart-label: 220 13% 46%;
|
||||
--chart-primary: 217 91% 60%;
|
||||
--chart-primary-light: 217 91% 65%;
|
||||
--chart-primary-dark: 217 70% 50%;
|
||||
--chart-primary-accent: 217 91% 45%;
|
||||
--chart-secondary: 206 22% 75%;
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: 222 47% 8%;
|
||||
--foreground: 220 20% 90%;
|
||||
--card: 222 40% 12%;
|
||||
--card-foreground: 220 20% 90%;
|
||||
--primary: 217 91% 60%;
|
||||
--primary-foreground: 0 0% 100%;
|
||||
--secondary: 220 30% 18%;
|
||||
--secondary-foreground: 220 20% 90%;
|
||||
--muted: 220 20% 16%;
|
||||
--muted-foreground: 220 13% 55%;
|
||||
--accent: 217 91% 60%;
|
||||
--accent-foreground: 0 0% 100%;
|
||||
--destructive: 0 72% 51%;
|
||||
--destructive-foreground: 0 0% 100%;
|
||||
--border: 220 20% 20%;
|
||||
--input: 220 20% 20%;
|
||||
--ring: 217 91% 60%;
|
||||
--chart-grid: 220 20% 22%;
|
||||
--chart-label: 220 13% 50%;
|
||||
--chart-primary: 217 91% 65%;
|
||||
--chart-primary-light: 217 91% 70%;
|
||||
--chart-primary-dark: 217 70% 55%;
|
||||
--chart-primary-accent: 217 91% 55%;
|
||||
--chart-secondary: 220 20% 35%;
|
||||
}
|
||||
|
||||
* {
|
||||
border-color: hsl(var(--border));
|
||||
}
|
||||
|
||||
html {
|
||||
font-family: var(--font-sans);
|
||||
color-scheme: light dark;
|
||||
}
|
||||
|
||||
body {
|
||||
min-height: 100vh;
|
||||
background: hsl(var(--background));
|
||||
color: hsl(var(--foreground));
|
||||
}
|
||||
}
|
||||
28
worker/src/layouts/BaseLayout.astro
Normal file
28
worker/src/layouts/BaseLayout.astro
Normal file
@@ -0,0 +1,28 @@
|
||||
---
|
||||
interface Props {
|
||||
title?: string;
|
||||
}
|
||||
|
||||
const { title = "MeshCore SAR RX Stats" } = Astro.props;
|
||||
|
||||
import "../index.css";
|
||||
---
|
||||
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="icon" type="image/png" href="/favicon.png" />
|
||||
<title>{title}</title>
|
||||
</head>
|
||||
<body>
|
||||
<slot />
|
||||
<script>
|
||||
const mq = window.matchMedia("(prefers-color-scheme: dark)");
|
||||
function apply(e) { document.documentElement.classList.toggle("dark", e.matches); }
|
||||
apply(mq);
|
||||
mq.addEventListener("change", apply);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
6
worker/src/lib/utils.ts
Normal file
6
worker/src/lib/utils.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
import { clsx, type ClassValue } from "clsx";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
8
worker/src/pages/index.astro
Normal file
8
worker/src/pages/index.astro
Normal file
@@ -0,0 +1,8 @@
|
||||
---
|
||||
import BaseLayout from "../layouts/BaseLayout.astro";
|
||||
import { DashboardShell } from "@/components/dashboard/dashboard-shell";
|
||||
---
|
||||
|
||||
<BaseLayout title="MeshCore SAR RX Stats">
|
||||
<DashboardShell client:load />
|
||||
</BaseLayout>
|
||||
169
worker/test/index.test.ts
Normal file
169
worker/test/index.test.ts
Normal file
@@ -0,0 +1,169 @@
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
|
||||
import {
|
||||
REPORT_INSERT_SQL,
|
||||
buildWindowFilter,
|
||||
createEmptyCounts,
|
||||
extractCfGeo,
|
||||
loadDashboardSummary,
|
||||
summarizeRows,
|
||||
validateIngestPayload,
|
||||
} from '../worker/stats';
|
||||
|
||||
describe('validateIngestPayload', () => {
|
||||
test('accepts a complete payload with fixed columns', () => {
|
||||
const counts = createEmptyCounts();
|
||||
counts.pt_04 = 12;
|
||||
counts.path_mode_2b = 4;
|
||||
|
||||
const payload = validateIngestPayload({
|
||||
reportId: 'a1b2c3d4e5f6:2026-04-03T10:00:00.000Z',
|
||||
deviceKey6: 'a1b2c3d4e5f6',
|
||||
windowStart: '2026-04-03T10:00:00.000Z',
|
||||
windowEnd: '2026-04-03T10:05:00.000Z',
|
||||
appVersion: '2026.0402.1+44',
|
||||
counts,
|
||||
});
|
||||
|
||||
expect(payload.counts.pt_04).toBe(12);
|
||||
expect(payload.counts.path_mode_2b).toBe(4);
|
||||
});
|
||||
|
||||
test('rejects missing fixed count keys', () => {
|
||||
expect(() =>
|
||||
validateIngestPayload({
|
||||
reportId: 'a1b2c3d4e5f6:2026-04-03T10:00:00.000Z',
|
||||
deviceKey6: 'a1b2c3d4e5f6',
|
||||
windowStart: '2026-04-03T10:00:00.000Z',
|
||||
windowEnd: '2026-04-03T10:05:00.000Z',
|
||||
appVersion: '2026.0402.1+44',
|
||||
counts: {},
|
||||
}),
|
||||
).toThrow('counts.pt_00 must be a number.');
|
||||
});
|
||||
});
|
||||
|
||||
describe('worker helpers', () => {
|
||||
test('uses insert-or-ignore semantics for idempotent reports', () => {
|
||||
expect(REPORT_INSERT_SQL).toContain('INSERT OR IGNORE INTO reports');
|
||||
});
|
||||
|
||||
test('extractCfGeo reads Cloudflare request metadata', () => {
|
||||
const request = new Request('https://example.com/') as Request & {
|
||||
cf?: Record<string, unknown>;
|
||||
};
|
||||
request.cf = {
|
||||
country: 'SI',
|
||||
region: 'Ljubljana',
|
||||
city: 'Ljubljana',
|
||||
latitude: '46.0569',
|
||||
longitude: '14.5058',
|
||||
colo: 'LJU',
|
||||
};
|
||||
|
||||
const geo = extractCfGeo(request);
|
||||
|
||||
expect(geo.country).toBe('SI');
|
||||
expect(geo.latitude).toBe(46.0569);
|
||||
expect(geo.longitude).toBe(14.5058);
|
||||
expect(geo.colo).toBe('LJU');
|
||||
});
|
||||
|
||||
test('summarizeRows aggregates packet and path mode totals', () => {
|
||||
const filter = buildWindowFilter('24h', new Date('2026-04-03T12:00:00.000Z'));
|
||||
const rows = [
|
||||
{
|
||||
...createEmptyCounts(),
|
||||
report_id: 'a1',
|
||||
device_key6: 'a1b2c3d4e5f6',
|
||||
window_start: '2026-04-03T10:00:00.000Z',
|
||||
window_end: '2026-04-03T10:05:00.000Z',
|
||||
received_at: '2026-04-03T10:05:03.000Z',
|
||||
app_version: '2026.0402.1+44',
|
||||
cf_country: 'SI',
|
||||
cf_region: 'Ljubljana',
|
||||
cf_city: 'Ljubljana',
|
||||
cf_latitude: 46.0569,
|
||||
cf_longitude: 14.5058,
|
||||
cf_colo: 'LJU',
|
||||
pt_04: 12,
|
||||
path_mode_2b: 12,
|
||||
},
|
||||
{
|
||||
...createEmptyCounts(),
|
||||
report_id: 'a2',
|
||||
device_key6: '001122334455',
|
||||
window_start: '2026-04-03T11:00:00.000Z',
|
||||
window_end: '2026-04-03T11:05:00.000Z',
|
||||
received_at: '2026-04-03T11:05:02.000Z',
|
||||
app_version: '2026.0402.1+44',
|
||||
cf_country: 'DE',
|
||||
cf_region: 'Berlin',
|
||||
cf_city: 'Berlin',
|
||||
cf_latitude: 52.52,
|
||||
cf_longitude: 13.405,
|
||||
cf_colo: 'FRA',
|
||||
pt_05: 3,
|
||||
decode_fail: 1,
|
||||
path_mode_none: 1,
|
||||
path_mode_3b: 2,
|
||||
},
|
||||
];
|
||||
|
||||
const summary = summarizeRows(rows, filter);
|
||||
|
||||
expect(summary.reportCount).toBe(2);
|
||||
expect(summary.uniqueDevices).toBe(2);
|
||||
expect(summary.decodedPackets).toBe(15);
|
||||
expect(summary.decodeFailures).toBe(1);
|
||||
expect(summary.pathModeTotals[0]?.total).toBe(12);
|
||||
expect(summary.locationPoints).toHaveLength(2);
|
||||
});
|
||||
|
||||
test('loadDashboardSummary reads D1 rows for the selected window', async () => {
|
||||
const rows = [
|
||||
{
|
||||
...createEmptyCounts(),
|
||||
report_id: 'a1',
|
||||
device_key6: 'a1b2c3d4e5f6',
|
||||
window_start: '2026-04-03T10:00:00.000Z',
|
||||
window_end: '2026-04-03T10:05:00.000Z',
|
||||
received_at: '2026-04-03T10:05:03.000Z',
|
||||
app_version: '2026.0402.1+44',
|
||||
cf_country: 'SI',
|
||||
cf_region: 'Ljubljana',
|
||||
cf_city: 'Ljubljana',
|
||||
cf_latitude: 46.0569,
|
||||
cf_longitude: 14.5058,
|
||||
cf_colo: 'LJU',
|
||||
pt_04: 5,
|
||||
},
|
||||
];
|
||||
|
||||
const env = {
|
||||
DB: {
|
||||
prepare() {
|
||||
return {
|
||||
bind() {
|
||||
return {
|
||||
async all() {
|
||||
return { results: rows };
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
},
|
||||
},
|
||||
} as any;
|
||||
|
||||
const summary = await loadDashboardSummary(
|
||||
env,
|
||||
'24h',
|
||||
new Date('2026-04-03T12:00:00.000Z'),
|
||||
);
|
||||
|
||||
expect(summary.reportCount).toBe(1);
|
||||
expect(summary.packetTypeTotals[0]?.key).toBe('pt_04');
|
||||
expect(summary.packetTypeTotals[0]?.total).toBe(5);
|
||||
});
|
||||
});
|
||||
20
worker/tsconfig.json
Normal file
20
worker/tsconfig.json
Normal file
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"extends": "astro/tsconfigs/strict",
|
||||
"include": [
|
||||
".astro/types.d.ts",
|
||||
"**/*"
|
||||
],
|
||||
"exclude": [
|
||||
"dist",
|
||||
"node_modules"
|
||||
],
|
||||
"compilerOptions": {
|
||||
"baseUrl": ".",
|
||||
"jsx": "react-jsx",
|
||||
"jsxImportSource": "react",
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
},
|
||||
"types": ["@cloudflare/workers-types", "bun-types"]
|
||||
}
|
||||
}
|
||||
124
worker/worker/index.ts
Normal file
124
worker/worker/index.ts
Normal file
@@ -0,0 +1,124 @@
|
||||
import {
|
||||
COUNT_KEYS,
|
||||
REPORT_INSERT_SQL,
|
||||
extractCfGeo,
|
||||
jsonHeaders,
|
||||
loadDashboardSummary,
|
||||
validateIngestPayload,
|
||||
type Env,
|
||||
type IngestPayload,
|
||||
} from "./stats";
|
||||
|
||||
const ROUTES = {
|
||||
"/api/ingest": handleIngest,
|
||||
"/api/dashboard": handleDashboard,
|
||||
} as const;
|
||||
|
||||
export default {
|
||||
async fetch(request: Request, env: Env): Promise<Response> {
|
||||
const pathname = new URL(request.url).pathname;
|
||||
const route = Object.entries(ROUTES).find(([prefix]) =>
|
||||
pathname.startsWith(prefix),
|
||||
);
|
||||
if (!route) {
|
||||
return new Response("Not Found", { status: 404 });
|
||||
}
|
||||
try {
|
||||
return await route[1](request, env);
|
||||
} catch (error) {
|
||||
console.error(`Worker route failed for ${pathname}:`, error);
|
||||
return Response.json(
|
||||
{ error: "Internal Server Error" },
|
||||
{
|
||||
headers: jsonHeaders,
|
||||
status: 500,
|
||||
},
|
||||
);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
async function handleIngest(request: Request, env: Env): Promise<Response> {
|
||||
if (request.method !== "POST") {
|
||||
return Response.json(
|
||||
{ error: "Method not allowed" },
|
||||
{
|
||||
headers: jsonHeaders,
|
||||
status: 405,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
let payload: IngestPayload;
|
||||
try {
|
||||
payload = validateIngestPayload(await request.json());
|
||||
} catch (error) {
|
||||
return Response.json(
|
||||
{ error: error instanceof Error ? error.message : "Invalid payload" },
|
||||
{
|
||||
headers: jsonHeaders,
|
||||
status: 400,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const geo = extractCfGeo(request);
|
||||
const values = [
|
||||
payload.reportId,
|
||||
payload.deviceKey6,
|
||||
payload.windowStart,
|
||||
payload.windowEnd,
|
||||
new Date().toISOString(),
|
||||
payload.appVersion,
|
||||
geo.country,
|
||||
geo.region,
|
||||
geo.city,
|
||||
geo.latitude,
|
||||
geo.longitude,
|
||||
geo.colo,
|
||||
...COUNT_KEYS.map((key) => payload.counts[key]),
|
||||
];
|
||||
|
||||
const result = await env.DB.prepare(REPORT_INSERT_SQL).bind(...values).run();
|
||||
const changes = Number((result.meta as { changes?: number }).changes ?? 0);
|
||||
|
||||
return Response.json(
|
||||
{
|
||||
ok: true,
|
||||
duplicate: changes === 0,
|
||||
},
|
||||
{
|
||||
headers: jsonHeaders,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async function handleDashboard(request: Request, env: Env): Promise<Response> {
|
||||
if (request.method !== "GET") {
|
||||
return Response.json(
|
||||
{ error: "Method not allowed" },
|
||||
{
|
||||
headers: jsonHeaders,
|
||||
status: 405,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const url = new URL(request.url);
|
||||
const windowParam = url.searchParams.get("window");
|
||||
const summary = await loadDashboardSummary(env, windowParam);
|
||||
const cacheTtl = windowParam === "7d" || windowParam === "30d" ? 86400 : 60;
|
||||
return Response.json(
|
||||
{
|
||||
generatedAt: new Date().toISOString(),
|
||||
...summary,
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
...jsonHeaders,
|
||||
"cache-control": `public, max-age=${cacheTtl}, s-maxage=${cacheTtl}`,
|
||||
"cdn-cache-control": `max-age=${cacheTtl}`,
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
507
worker/worker/stats.ts
Normal file
507
worker/worker/stats.ts
Normal file
@@ -0,0 +1,507 @@
|
||||
export const PACKET_TYPE_KEYS = [
|
||||
"pt_00",
|
||||
"pt_01",
|
||||
"pt_02",
|
||||
"pt_03",
|
||||
"pt_04",
|
||||
"pt_05",
|
||||
"pt_06",
|
||||
"pt_07",
|
||||
"pt_08",
|
||||
"pt_09",
|
||||
"pt_0a",
|
||||
"pt_0b",
|
||||
"pt_0c",
|
||||
"pt_0d",
|
||||
"pt_0e",
|
||||
"pt_0f",
|
||||
] as const;
|
||||
|
||||
export const PATH_MODE_KEYS = [
|
||||
"path_mode_1b",
|
||||
"path_mode_2b",
|
||||
"path_mode_3b",
|
||||
"path_mode_none",
|
||||
"path_mode_unknown",
|
||||
] as const;
|
||||
|
||||
export const COUNT_KEYS = [
|
||||
...PACKET_TYPE_KEYS,
|
||||
"decode_fail",
|
||||
...PATH_MODE_KEYS,
|
||||
] as const;
|
||||
|
||||
const REPORT_COLUMNS = [
|
||||
"report_id",
|
||||
"device_key6",
|
||||
"window_start",
|
||||
"window_end",
|
||||
"received_at",
|
||||
"app_version",
|
||||
"cf_country",
|
||||
"cf_region",
|
||||
"cf_city",
|
||||
"cf_latitude",
|
||||
"cf_longitude",
|
||||
"cf_colo",
|
||||
...COUNT_KEYS,
|
||||
] as const;
|
||||
|
||||
const PACKET_TYPE_LABELS: Record<(typeof PACKET_TYPE_KEYS)[number], string> = {
|
||||
pt_00: "Request",
|
||||
pt_01: "Response",
|
||||
pt_02: "Text message",
|
||||
pt_03: "Ack",
|
||||
pt_04: "Advertisement",
|
||||
pt_05: "Group text",
|
||||
pt_06: "Group datagram",
|
||||
pt_07: "Anonymous request",
|
||||
pt_08: "Returned path",
|
||||
pt_09: "Trace path",
|
||||
pt_0a: "Multipart packet",
|
||||
pt_0b: "Control packet",
|
||||
pt_0c: "Reserved 0x0C",
|
||||
pt_0d: "Reserved 0x0D",
|
||||
pt_0e: "Reserved 0x0E",
|
||||
pt_0f: "Custom packet",
|
||||
};
|
||||
|
||||
const PATH_MODE_LABELS: Record<(typeof PATH_MODE_KEYS)[number], string> = {
|
||||
path_mode_1b: "1-byte path hash",
|
||||
path_mode_2b: "2-byte path hash",
|
||||
path_mode_3b: "3-byte path hash",
|
||||
path_mode_none: "No path bytes",
|
||||
path_mode_unknown: "Unknown path mode",
|
||||
};
|
||||
|
||||
const WINDOW_OPTIONS = {
|
||||
"24h": {
|
||||
label: "Last 24 hours",
|
||||
durationMs: 24 * 60 * 60 * 1000,
|
||||
bucket: "hour",
|
||||
},
|
||||
"7d": {
|
||||
label: "Last 7 days",
|
||||
durationMs: 7 * 24 * 60 * 60 * 1000,
|
||||
bucket: "day",
|
||||
},
|
||||
"30d": {
|
||||
label: "Last 30 days",
|
||||
durationMs: 30 * 24 * 60 * 60 * 1000,
|
||||
bucket: "day",
|
||||
},
|
||||
} as const;
|
||||
|
||||
export const jsonHeaders = {
|
||||
"content-type": "application/json; charset=utf-8",
|
||||
} as const;
|
||||
|
||||
type CountKey = (typeof COUNT_KEYS)[number];
|
||||
type PacketTypeKey = (typeof PACKET_TYPE_KEYS)[number];
|
||||
type PathModeKey = (typeof PATH_MODE_KEYS)[number];
|
||||
type WindowKey = keyof typeof WINDOW_OPTIONS;
|
||||
|
||||
export type Counts = Record<CountKey, number>;
|
||||
|
||||
export interface Env {
|
||||
DB: D1Database;
|
||||
}
|
||||
|
||||
export interface IngestPayload {
|
||||
reportId: string;
|
||||
deviceKey6: string;
|
||||
windowStart: string;
|
||||
windowEnd: string;
|
||||
appVersion: string;
|
||||
counts: Counts;
|
||||
}
|
||||
|
||||
export interface CfGeo {
|
||||
country: string | null;
|
||||
region: string | null;
|
||||
city: string | null;
|
||||
latitude: number | null;
|
||||
longitude: number | null;
|
||||
colo: string | null;
|
||||
}
|
||||
|
||||
export interface ReportRow extends Counts {
|
||||
report_id: string;
|
||||
device_key6: string;
|
||||
window_start: string;
|
||||
window_end: string;
|
||||
received_at: string;
|
||||
app_version: string | null;
|
||||
cf_country: string | null;
|
||||
cf_region: string | null;
|
||||
cf_city: string | null;
|
||||
cf_latitude: number | null;
|
||||
cf_longitude: number | null;
|
||||
cf_colo: string | null;
|
||||
}
|
||||
|
||||
export interface WindowFilter {
|
||||
windowKey: WindowKey;
|
||||
label: string;
|
||||
sinceIso: string;
|
||||
bucket: "hour" | "day";
|
||||
}
|
||||
|
||||
export interface ChartPoint {
|
||||
label: string;
|
||||
totalPackets: number;
|
||||
reports: number;
|
||||
}
|
||||
|
||||
export interface LocationPoint {
|
||||
key6: string;
|
||||
city: string;
|
||||
country: string;
|
||||
latitude: number;
|
||||
longitude: number;
|
||||
}
|
||||
|
||||
export interface ReporterSummary {
|
||||
key6: string;
|
||||
lastSeen: string;
|
||||
packetTotal: number;
|
||||
country: string;
|
||||
city: string;
|
||||
latitude: number | null;
|
||||
longitude: number | null;
|
||||
}
|
||||
|
||||
export interface AppVersionEntry {
|
||||
version: string;
|
||||
reporters: number;
|
||||
packets: number;
|
||||
}
|
||||
|
||||
export interface TrafficComposition {
|
||||
human: number;
|
||||
overhead: number;
|
||||
acks: number;
|
||||
}
|
||||
|
||||
export interface MultiHopRatio {
|
||||
direct: number;
|
||||
multiHop: number;
|
||||
}
|
||||
|
||||
export interface CompositionPoint {
|
||||
label: string;
|
||||
human: number;
|
||||
overhead: number;
|
||||
}
|
||||
|
||||
export interface DashboardSummary {
|
||||
filter: WindowFilter;
|
||||
reportCount: number;
|
||||
uniqueDevices: number;
|
||||
decodedPackets: number;
|
||||
decodeFailures: number;
|
||||
packetTypeTotals: Array<{ key: PacketTypeKey; label: string; total: number }>;
|
||||
pathModeTotals: Array<{ key: PathModeKey; label: string; total: number }>;
|
||||
recentReporters: ReporterSummary[];
|
||||
chartPoints: ChartPoint[];
|
||||
locationPoints: LocationPoint[];
|
||||
appVersions: AppVersionEntry[];
|
||||
trafficComposition: TrafficComposition;
|
||||
multiHopRatio: MultiHopRatio;
|
||||
compositionOverTime: CompositionPoint[];
|
||||
}
|
||||
|
||||
export const REPORT_INSERT_SQL = `
|
||||
INSERT OR IGNORE INTO reports (
|
||||
${REPORT_COLUMNS.join(", ")}
|
||||
) VALUES (
|
||||
${REPORT_COLUMNS.map(() => "?").join(", ")}
|
||||
)`.trim();
|
||||
|
||||
export function createEmptyCounts(): Counts {
|
||||
return Object.fromEntries(
|
||||
COUNT_KEYS.map((key) => [key, 0]),
|
||||
) as Counts;
|
||||
}
|
||||
|
||||
export function validateIngestPayload(payload: unknown): IngestPayload {
|
||||
if (typeof payload !== "object" || payload === null) {
|
||||
throw new Error("Body must be a JSON object.");
|
||||
}
|
||||
const record = payload as Record<string, unknown>;
|
||||
const reportId = asTrimmedString(record.reportId, "reportId");
|
||||
const deviceKey6 = asTrimmedString(record.deviceKey6, "deviceKey6");
|
||||
if (!/^[0-9a-f]{12}$/.test(deviceKey6)) {
|
||||
throw new Error("deviceKey6 must be 12 lowercase hex characters.");
|
||||
}
|
||||
const windowStart = asIsoString(record.windowStart, "windowStart");
|
||||
const windowEnd = asIsoString(record.windowEnd, "windowEnd");
|
||||
if (Date.parse(windowEnd) < Date.parse(windowStart)) {
|
||||
throw new Error("windowEnd must not be earlier than windowStart.");
|
||||
}
|
||||
const appVersion = asTrimmedString(record.appVersion, "appVersion");
|
||||
const counts = validateCounts(record.counts);
|
||||
return {
|
||||
reportId,
|
||||
deviceKey6,
|
||||
windowStart,
|
||||
windowEnd,
|
||||
appVersion,
|
||||
counts,
|
||||
};
|
||||
}
|
||||
|
||||
export function extractCfGeo(request: Request): CfGeo {
|
||||
const cf = (request as Request & { cf?: Record<string, unknown> }).cf;
|
||||
return {
|
||||
country: asNullableString(cf?.country),
|
||||
region: asNullableString(cf?.region),
|
||||
city: asNullableString(cf?.city),
|
||||
latitude: asNullableNumber(cf?.latitude),
|
||||
longitude: asNullableNumber(cf?.longitude),
|
||||
colo: asNullableString(cf?.colo),
|
||||
};
|
||||
}
|
||||
|
||||
export function buildWindowFilter(
|
||||
requestedWindow: string | null,
|
||||
now: Date = new Date(),
|
||||
): WindowFilter {
|
||||
const windowKey =
|
||||
requestedWindow === "24h" ||
|
||||
requestedWindow === "7d" ||
|
||||
requestedWindow === "30d"
|
||||
? requestedWindow
|
||||
: "24h";
|
||||
const option = WINDOW_OPTIONS[windowKey];
|
||||
return {
|
||||
windowKey,
|
||||
label: option.label,
|
||||
sinceIso: new Date(now.getTime() - option.durationMs).toISOString(),
|
||||
bucket: option.bucket,
|
||||
};
|
||||
}
|
||||
|
||||
export async function loadDashboardSummary(
|
||||
env: Env,
|
||||
requestedWindow: string | null,
|
||||
now: Date = new Date(),
|
||||
): Promise<DashboardSummary> {
|
||||
const filter = buildWindowFilter(requestedWindow, now);
|
||||
const query = await env.DB.prepare(
|
||||
"SELECT * FROM reports WHERE window_end >= ? ORDER BY window_end DESC",
|
||||
)
|
||||
.bind(filter.sinceIso)
|
||||
.all<ReportRow>();
|
||||
const rows = (query.results ?? []) as ReportRow[];
|
||||
return summarizeRows(rows, filter);
|
||||
}
|
||||
|
||||
export function summarizeRows(
|
||||
rows: ReportRow[],
|
||||
filter: WindowFilter,
|
||||
): DashboardSummary {
|
||||
const packetTypeTotals = PACKET_TYPE_KEYS.map((key) => ({
|
||||
key,
|
||||
label: PACKET_TYPE_LABELS[key],
|
||||
total: sumRows(rows, key),
|
||||
})).sort((left, right) => right.total - left.total);
|
||||
const pathModeTotals = PATH_MODE_KEYS.map((key) => ({
|
||||
key,
|
||||
label: PATH_MODE_LABELS[key],
|
||||
total: sumRows(rows, key),
|
||||
})).sort((left, right) => right.total - left.total);
|
||||
const decodedPackets = PACKET_TYPE_KEYS.reduce(
|
||||
(total, key) => total + sumRows(rows, key),
|
||||
0,
|
||||
);
|
||||
const decodeFailures = sumRows(rows, "decode_fail");
|
||||
const reporterMap = new Map<string, ReporterSummary>();
|
||||
const chartBuckets = new Map<string, ChartPoint>();
|
||||
|
||||
// per-version and per-colo accumulators
|
||||
const versionMap = new Map<string, { reporters: Set<string>; packets: number }>();
|
||||
const compositionBuckets = new Map<string, { human: number; overhead: number }>();
|
||||
|
||||
for (const row of rows) {
|
||||
const packetTotal =
|
||||
decodeFailuresForRow(row) +
|
||||
PACKET_TYPE_KEYS.reduce((total, key) => total + row[key], 0);
|
||||
const existingReporter = reporterMap.get(row.device_key6);
|
||||
if (!existingReporter) {
|
||||
reporterMap.set(row.device_key6, {
|
||||
key6: row.device_key6,
|
||||
lastSeen: row.window_end,
|
||||
packetTotal,
|
||||
country: row.cf_country ?? "Unknown",
|
||||
city: row.cf_city ?? row.cf_region ?? "Unknown",
|
||||
latitude: row.cf_latitude,
|
||||
longitude: row.cf_longitude,
|
||||
});
|
||||
} else {
|
||||
existingReporter.packetTotal += packetTotal;
|
||||
if (row.window_end > existingReporter.lastSeen) {
|
||||
existingReporter.lastSeen = row.window_end;
|
||||
existingReporter.country = row.cf_country ?? existingReporter.country;
|
||||
existingReporter.city =
|
||||
row.cf_city ?? row.cf_region ?? existingReporter.city;
|
||||
existingReporter.latitude = row.cf_latitude;
|
||||
existingReporter.longitude = row.cf_longitude;
|
||||
}
|
||||
}
|
||||
|
||||
const bucketKey = formatBucket(row.window_end, filter.bucket);
|
||||
const existingBucket = chartBuckets.get(bucketKey);
|
||||
if (existingBucket) {
|
||||
existingBucket.totalPackets += packetTotal;
|
||||
existingBucket.reports += 1;
|
||||
} else {
|
||||
chartBuckets.set(bucketKey, {
|
||||
label: bucketKey,
|
||||
totalPackets: packetTotal,
|
||||
reports: 1,
|
||||
});
|
||||
}
|
||||
|
||||
// app version
|
||||
const ver = row.app_version ?? "unknown";
|
||||
const verEntry = versionMap.get(ver);
|
||||
if (verEntry) {
|
||||
verEntry.reporters.add(row.device_key6);
|
||||
verEntry.packets += packetTotal;
|
||||
} else {
|
||||
versionMap.set(ver, { reporters: new Set([row.device_key6]), packets: packetTotal });
|
||||
}
|
||||
|
||||
// composition over time (human = text + group_text, overhead = rest)
|
||||
const humanPackets = row.pt_02 + row.pt_05;
|
||||
const overheadPackets = packetTotal - humanPackets;
|
||||
const compBucket = compositionBuckets.get(bucketKey);
|
||||
if (compBucket) {
|
||||
compBucket.human += humanPackets;
|
||||
compBucket.overhead += overheadPackets;
|
||||
} else {
|
||||
compositionBuckets.set(bucketKey, { human: humanPackets, overhead: overheadPackets });
|
||||
}
|
||||
}
|
||||
|
||||
const recentReporters = [...reporterMap.values()]
|
||||
.sort((left, right) => right.lastSeen.localeCompare(left.lastSeen))
|
||||
.slice(0, 12);
|
||||
const locationPoints = recentReporters
|
||||
.filter(
|
||||
(
|
||||
reporter,
|
||||
): reporter is ReporterSummary & { latitude: number; longitude: number } =>
|
||||
reporter.latitude !== null && reporter.longitude !== null,
|
||||
)
|
||||
.map((reporter) => ({
|
||||
key6: reporter.key6,
|
||||
city: reporter.city,
|
||||
country: reporter.country,
|
||||
latitude: reporter.latitude,
|
||||
longitude: reporter.longitude,
|
||||
}));
|
||||
|
||||
// human = text messages (pt_02 + pt_05), acks = pt_03, overhead = everything else
|
||||
const humanTotal = sumRows(rows, "pt_02") + sumRows(rows, "pt_05");
|
||||
const acksTotal = sumRows(rows, "pt_03");
|
||||
const overheadTotal = decodedPackets - humanTotal - acksTotal;
|
||||
|
||||
// multi-hop: direct = path_mode_none, multiHop = 1b+2b+3b
|
||||
const directTotal = sumRows(rows, "path_mode_none");
|
||||
const multiHopTotal = sumRows(rows, "path_mode_1b") + sumRows(rows, "path_mode_2b") + sumRows(rows, "path_mode_3b");
|
||||
|
||||
return {
|
||||
filter,
|
||||
reportCount: rows.length,
|
||||
uniqueDevices: reporterMap.size,
|
||||
decodedPackets,
|
||||
decodeFailures,
|
||||
packetTypeTotals,
|
||||
pathModeTotals,
|
||||
recentReporters,
|
||||
chartPoints: [...chartBuckets.values()].sort((left, right) =>
|
||||
left.label.localeCompare(right.label),
|
||||
),
|
||||
locationPoints,
|
||||
appVersions: [...versionMap.entries()]
|
||||
.map(([version, entry]) => ({ version, reporters: entry.reporters.size, packets: entry.packets }))
|
||||
.sort((left, right) => right.packets - left.packets),
|
||||
trafficComposition: { human: humanTotal, overhead: overheadTotal, acks: acksTotal },
|
||||
multiHopRatio: { direct: directTotal, multiHop: multiHopTotal },
|
||||
compositionOverTime: [...compositionBuckets.entries()]
|
||||
.map(([label, entry]) => ({ label, ...entry }))
|
||||
.sort((left, right) => left.label.localeCompare(right.label)),
|
||||
};
|
||||
}
|
||||
|
||||
function validateCounts(value: unknown): Counts {
|
||||
if (typeof value !== "object" || value === null) {
|
||||
throw new Error("counts must be an object.");
|
||||
}
|
||||
const record = value as Record<string, unknown>;
|
||||
const counts = createEmptyCounts();
|
||||
for (const key of COUNT_KEYS) {
|
||||
const rawValue = record[key];
|
||||
if (typeof rawValue !== "number" || !Number.isFinite(rawValue)) {
|
||||
throw new Error(`counts.${key} must be a number.`);
|
||||
}
|
||||
if (rawValue < 0) {
|
||||
throw new Error(`counts.${key} must be zero or greater.`);
|
||||
}
|
||||
counts[key] = Math.trunc(rawValue);
|
||||
}
|
||||
return counts;
|
||||
}
|
||||
|
||||
function sumRows(rows: ReportRow[], key: CountKey): number {
|
||||
return rows.reduce((total, row) => total + (row[key] ?? 0), 0);
|
||||
}
|
||||
|
||||
function decodeFailuresForRow(row: ReportRow): number {
|
||||
return row.decode_fail ?? 0;
|
||||
}
|
||||
|
||||
function formatBucket(value: string, bucket: "hour" | "day"): string {
|
||||
const date = new Date(value);
|
||||
const month = `${date.getUTCMonth() + 1}`.padStart(2, "0");
|
||||
const day = `${date.getUTCDate()}`.padStart(2, "0");
|
||||
if (bucket === "day") {
|
||||
return `${date.getUTCFullYear()}-${month}-${day}`;
|
||||
}
|
||||
const hour = `${date.getUTCHours()}`.padStart(2, "0");
|
||||
return `${date.getUTCFullYear()}-${month}-${day} ${hour}:00`;
|
||||
}
|
||||
|
||||
function asTrimmedString(value: unknown, fieldName: string): string {
|
||||
if (typeof value !== "string" || value.trim().length === 0) {
|
||||
throw new Error(`${fieldName} must be a non-empty string.`);
|
||||
}
|
||||
return value.trim();
|
||||
}
|
||||
|
||||
function asIsoString(value: unknown, fieldName: string): string {
|
||||
const stringValue = asTrimmedString(value, fieldName);
|
||||
if (Number.isNaN(Date.parse(stringValue))) {
|
||||
throw new Error(`${fieldName} must be a valid ISO-8601 timestamp.`);
|
||||
}
|
||||
return new Date(stringValue).toISOString();
|
||||
}
|
||||
|
||||
function asNullableString(value: unknown): string | null {
|
||||
return typeof value === "string" && value.trim().length > 0
|
||||
? value.trim()
|
||||
: null;
|
||||
}
|
||||
|
||||
function asNullableNumber(value: unknown): number | null {
|
||||
if (typeof value === "number" && Number.isFinite(value)) {
|
||||
return value;
|
||||
}
|
||||
if (typeof value === "string" && value.trim().length > 0) {
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
20
worker/wrangler.toml
Normal file
20
worker/wrangler.toml
Normal file
@@ -0,0 +1,20 @@
|
||||
name = "meshcore-sar-stats"
|
||||
main = "worker/index.ts"
|
||||
compatibility_date = "2026-04-03"
|
||||
compatibility_flags = ["nodejs_compat"]
|
||||
|
||||
[observability.logs]
|
||||
enabled = false
|
||||
|
||||
[placement]
|
||||
mode = "smart"
|
||||
|
||||
[assets]
|
||||
directory = "./dist"
|
||||
not_found_handling = "404-page"
|
||||
run_worker_first = ["/api/*"]
|
||||
|
||||
[[d1_databases]]
|
||||
binding = "DB"
|
||||
database_name = "meshcore_sar_rx_stats"
|
||||
database_id = "94a3978f-13d9-4dc8-9a3c-2beb102699e5"
|
||||
Reference in New Issue
Block a user