feat: Implement self advertisement functionality and enhance location broadcasting settings

This commit is contained in:
Janez T
2025-10-14 21:36:50 +02:00
parent 2cb6c34167
commit fd54392d3c
7 changed files with 808 additions and 164 deletions

View File

@@ -12,9 +12,12 @@ import 'meshcore_ble_service.dart';
class BackgroundLocationService {
static const String _prefKeyEnabled = 'background_tracking_enabled';
static const String _prefKeyDistance = 'background_tracking_distance';
static const String _prefKeyLastLat = 'background_last_lat';
static const String _prefKeyLastLon = 'background_last_lon';
MeshCoreBleService? _bleService;
bool _isInitialized = false;
StreamSubscription<Position>? _positionSubscription;
/// Initialize the service with BLE service reference
void initialize(MeshCoreBleService bleService) {
@@ -22,10 +25,19 @@ class BackgroundLocationService {
_isInitialized = true;
}
/// Start background location tracking
/// Start location tracking and automatic advertisement
/// Returns true if successful, false otherwise
///
/// Note: This is foreground tracking. For true background operation,
/// additional platform-specific configuration is required.
Future<bool> startTracking({double distanceThreshold = 10.0}) async {
if (!_isInitialized || _bleService == null) {
print('⚠️ [BackgroundLocation] Service not initialized or BLE service null');
return false;
}
if (!_bleService!.isConnected) {
print('⚠️ [BackgroundLocation] BLE not connected');
return false;
}
@@ -34,11 +46,13 @@ class BackgroundLocationService {
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
print('⚠️ [BackgroundLocation] Location permission denied');
return false;
}
}
if (permission == LocationPermission.deniedForever) {
print('⚠️ [BackgroundLocation] Location permission permanently denied');
return false;
}
@@ -47,93 +61,17 @@ class BackgroundLocationService {
await prefs.setBool(_prefKeyEnabled, true);
await prefs.setDouble(_prefKeyDistance, distanceThreshold);
// Initialize background service if not already running
final service = FlutterBackgroundService();
final isRunning = await service.isRunning();
if (!isRunning) {
await _initializeBackgroundService();
}
// Start the service
await service.startService();
return true;
}
/// Stop background location tracking
Future<void> stopTracking() async {
final prefs = await SharedPreferences.getInstance();
await prefs.setBool(_prefKeyEnabled, false);
final service = FlutterBackgroundService();
service.invoke('stop');
}
/// Update the distance threshold for location updates
void updateDistanceThreshold(double distance) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setDouble(_prefKeyDistance, distance);
final service = FlutterBackgroundService();
service.invoke('updateDistance', {'distance': distance});
}
/// Initialize the background service
Future<void> _initializeBackgroundService() async {
final service = FlutterBackgroundService();
await service.configure(
iosConfiguration: IosConfiguration(
autoStart: false,
onForeground: _onStart,
onBackground: _onIosBackground,
),
androidConfiguration: AndroidConfiguration(
autoStart: false,
onStart: _onStart,
isForegroundMode: true,
autoStartOnBoot: false,
),
);
}
/// iOS background entry point
@pragma('vm:entry-point')
static bool _onIosBackground(ServiceInstance service) {
WidgetsFlutterBinding.ensureInitialized();
DartPluginRegistrant.ensureInitialized();
return true;
}
/// Background service entry point
@pragma('vm:entry-point')
static void _onStart(ServiceInstance service) async {
// Ensure Flutter binding is initialized
DartPluginRegistrant.ensureInitialized();
// Start listening to position updates
Position? lastPosition;
StreamSubscription<Position>? positionSubscription;
double distanceThreshold = 10.0;
// Load settings
final prefs = await SharedPreferences.getInstance();
final enabled = prefs.getBool(_prefKeyEnabled) ?? false;
distanceThreshold = prefs.getDouble(_prefKeyDistance) ?? 10.0;
if (!enabled) {
service.stopSelf();
return;
}
// Start location tracking
try {
positionSubscription = Geolocator.getPositionStream(
_positionSubscription = Geolocator.getPositionStream(
locationSettings: LocationSettings(
accuracy: LocationAccuracy.best,
distanceFilter: distanceThreshold.toInt(),
),
).listen((Position position) async {
print('📍 [BackgroundLocation] New position: ${position.latitude}, ${position.longitude}');
// Calculate distance from last position
if (lastPosition != null) {
final distance = Geolocator.distanceBetween(
@@ -143,41 +81,73 @@ class BackgroundLocationService {
position.longitude,
);
// Only update if moved enough distance
print(' Distance moved: ${distance.toStringAsFixed(1)}m (threshold: ${distanceThreshold}m)');
// Skip if haven't moved enough
if (distance < distanceThreshold) {
return;
}
}
// Store last position
// Update last position
lastPosition = position;
// Note: In a real implementation, we would need to communicate with
// the BLE service via isolate communication or shared storage.
// For now, this is a placeholder for the background tracking logic.
// Save to preferences
await prefs.setDouble(_prefKeyLastLat, position.latitude);
await prefs.setDouble(_prefKeyLastLon, position.longitude);
// Send location update via notification or data channel
service.invoke('location', {
'latitude': position.latitude,
'longitude': position.longitude,
'timestamp': position.timestamp.millisecondsSinceEpoch,
});
// Update device's advertised location
if (_bleService != null && _bleService!.isConnected) {
try {
print('📤 [BackgroundLocation] Updating device location...');
await _bleService!.setAdvertLatLon(
latitude: position.latitude,
longitude: position.longitude,
);
// Send advertisement to mesh network
print('📡 [BackgroundLocation] Broadcasting self advertisement...');
await _bleService!.sendSelfAdvert(floodMode: true);
print('✅ [BackgroundLocation] Location update sent successfully');
} catch (e) {
print('❌ [BackgroundLocation] Failed to send location update: $e');
}
} else {
print('⚠️ [BackgroundLocation] BLE disconnected, cannot send update');
}
});
print('✅ [BackgroundLocation] Tracking started with ${distanceThreshold}m threshold');
return true;
} catch (e) {
service.stopSelf();
return;
print('❌ [BackgroundLocation] Failed to start tracking: $e');
return false;
}
}
// Listen for service commands
service.on('stop').listen((event) async {
await positionSubscription?.cancel();
service.stopSelf();
});
/// Stop location tracking
Future<void> stopTracking() async {
print('🛑 [BackgroundLocation] Stopping tracking');
await _positionSubscription?.cancel();
_positionSubscription = null;
service.on('updateDistance').listen((event) {
if (event != null && event['distance'] != null) {
distanceThreshold = event['distance'] as double;
}
});
final prefs = await SharedPreferences.getInstance();
await prefs.setBool(_prefKeyEnabled, false);
print('✅ [BackgroundLocation] Tracking stopped');
}
/// Update the distance threshold for location updates
/// Note: This will restart tracking with the new threshold
Future<void> updateDistanceThreshold(double distance) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setDouble(_prefKeyDistance, distance);
print('📏 [BackgroundLocation] Distance threshold updated to ${distance}m');
// Restart tracking if currently enabled
final isEnabled = prefs.getBool(_prefKeyEnabled) ?? false;
if (isEnabled && _bleService != null) {
await stopTracking();
await startTracking(distanceThreshold: distance);
}
}
}

View File

@@ -520,7 +520,35 @@ class MeshCoreBleService {
final senderTimestamp = reader.readUInt32LE();
print(' Sender timestamp: $senderTimestamp (${DateTime.fromMillisecondsSinceEpoch(senderTimestamp * 1000)})');
final text = reader.readString();
// Handle different message types
String text;
Uint8List? signature;
if (txtType == MessageTextType.signedPlain) {
// Signed message format: [64-byte signature][UTF-8 text]
print(' Signed message detected - extracting signature');
if (reader.remainingBytesCount < 64) {
print(' ⚠️ Insufficient bytes for signature (${reader.remainingBytesCount} < 64)');
// Try to read as plain text anyway
text = reader.readString();
} else {
signature = reader.readBytes(64);
print(' Signature (first 16 bytes): ${signature.sublist(0, 16).map((b) => b.toRadixString(16).padLeft(2, '0')).join(' ')}...');
// Remaining bytes are the actual text
if (reader.hasRemaining) {
text = reader.readString();
} else {
text = '';
print(' ⚠️ No text content after signature');
}
}
} else {
// Plain text message
text = reader.readString();
}
print(' Text: "$text"');
final message = Message(
@@ -561,7 +589,35 @@ class MeshCoreBleService {
final senderTimestamp = reader.readUInt32LE();
print(' Sender timestamp: $senderTimestamp (${DateTime.fromMillisecondsSinceEpoch(senderTimestamp * 1000)})');
final text = reader.readString();
// Handle different message types
String text;
Uint8List? signature;
if (txtType == MessageTextType.signedPlain) {
// Signed message format: [64-byte signature][UTF-8 text]
print(' Signed message detected - extracting signature');
if (reader.remainingBytesCount < 64) {
print(' ⚠️ Insufficient bytes for signature (${reader.remainingBytesCount} < 64)');
// Try to read as plain text anyway
text = reader.readString();
} else {
signature = reader.readBytes(64);
print(' Signature (first 16 bytes): ${signature.sublist(0, 16).map((b) => b.toRadixString(16).padLeft(2, '0')).join(' ')}...');
// Remaining bytes are the actual text
if (reader.hasRemaining) {
text = reader.readString();
} else {
text = '';
print(' ⚠️ No text content after signature');
}
}
} else {
// Plain text message
text = reader.readString();
}
print(' Text: "$text"');
final message = Message(
@@ -1207,16 +1263,22 @@ class MeshCoreBleService {
await _writeData(writer.toBytes());
}
/// Send flood advertisement with current location
Future<void> sendFloodAdvertisement({
required double latitude,
required double longitude,
}) async {
/// Send self advertisement packet to mesh network
///
/// This broadcasts the device's current advertisement data (name, location, etc.)
/// to the mesh network. The device uses its internally stored values from
/// setAdvertName() and setAdvertLatLon().
///
/// Protocol format (CMD_SEND_SELF_ADVERT):
/// - 1 byte: command code (7)
/// - 1 byte: type (0=zero-hop/local, 1=flood/mesh-wide)
///
/// [floodMode] - if true, broadcast to entire mesh network (default)
/// if false, only send to direct neighbors (zero-hop)
Future<void> sendSelfAdvert({bool floodMode = true}) async {
final writer = BufferWriter();
writer.writeByte(MeshCoreConstants.cmdSendSelfAdvert);
writer.writeByte(MeshCoreConstants.selfAdvertFlood);
writer.writeInt32LE((latitude * 1000000).round());
writer.writeInt32LE((longitude * 1000000).round());
writer.writeByte(floodMode ? MeshCoreConstants.selfAdvertFlood : MeshCoreConstants.selfAdvertZeroHop);
await _writeData(writer.toBytes());
}