first version worth putting in git - compiles and runs - missing a lot still.

This commit is contained in:
stopflock
2025-07-18 14:25:22 -05:00
parent bd0898c5e4
commit eee92f4f21
71 changed files with 2728 additions and 2 deletions
+87
View File
@@ -0,0 +1,87 @@
import 'package:flutter/material.dart';
import 'package:latlong2/latlong.dart';
import 'models/camera_profile.dart';
import 'models/pending_upload.dart';
class AddCameraSession {
AddCameraSession({required this.profile, this.directionDegrees = 0});
CameraProfile profile;
double directionDegrees;
LatLng? target;
}
class AppState extends ChangeNotifier {
AppState() {
_profiles = [CameraProfile.alpr()];
_enabled = {..._profiles}; // all enabled by default
}
// ---------- Auth ----------
bool _loggedIn = false;
bool get isLoggedIn => _loggedIn;
void setLoggedIn(bool v) {
_loggedIn = v;
notifyListeners();
}
// ---------- Profiles & toggles ----------
late final List<CameraProfile> _profiles;
late final Set<CameraProfile> _enabled;
List<CameraProfile> get profiles => List.unmodifiable(_profiles);
bool isEnabled(CameraProfile p) => _enabled.contains(p);
void toggleProfile(CameraProfile p, bool enable) {
enable ? _enabled.add(p) : _enabled.remove(p);
notifyListeners();
}
List<CameraProfile> get enabledProfiles => _profiles
.where((p) => _enabled.contains(p))
.toList(growable: false);
// ---------- Add-camera session ----------
AddCameraSession? _session;
AddCameraSession? get session => _session;
void startAddSession() {
_session = AddCameraSession(profile: enabledProfiles.first);
notifyListeners();
}
void updateSession({
double? directionDeg,
CameraProfile? profile,
LatLng? target,
}) {
if (_session == null) return;
if (directionDeg != null) _session!.directionDegrees = directionDeg;
if (profile != null) _session!.profile = profile;
if (target != null) _session!.target = target;
notifyListeners();
}
void cancelSession() {
_session = null;
notifyListeners();
}
// ---------- Pending uploads ----------
final List<PendingUpload> _queue = [];
List<PendingUpload> get queue => List.unmodifiable(_queue);
void commitSession() {
if (_session?.target == null) return;
_queue.add(
PendingUpload(
coord: _session!.target!,
direction: _session!.directionDegrees,
profile: _session!.profile,
),
);
_session = null;
notifyListeners();
}
}
+38
View File
@@ -0,0 +1,38 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'app_state.dart';
import 'screens/home_screen.dart';
import 'screens/add_camera_screen.dart';
import 'screens/settings_screen.dart';
void main() {
runApp(
ChangeNotifierProvider(
create: (_) => AppState(),
child: const FlockMapApp(),
),
);
}
class FlockMapApp extends StatelessWidget {
const FlockMapApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flock Map',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.green),
useMaterial3: true,
),
routes: {
'/': (context) => const HomeScreen(),
'/add': (context) => const AddCameraScreen(),
'/settings': (context) => const SettingsScreen(),
},
initialRoute: '/',
);
}
}
+33
View File
@@ -0,0 +1,33 @@
/// A bundle of preset OSM tags that describe a particular camera model/type.
class CameraProfile {
final String name;
final Map<String, String> tags;
const CameraProfile({
required this.name,
required this.tags,
});
// Builtin ALPR profile (Flock Falconstyle).
factory CameraProfile.alpr() => const CameraProfile(
name: 'ALPR Camera',
tags: {
'man_made': 'surveillance',
'surveillance:type': 'ALPR',
'surveillance': 'public',
'surveillance:zone': 'traffic',
'camera:type': 'fixed',
'camera:mount': 'pole',
},
);
CameraProfile copyWith({
String? name,
Map<String, String>? tags,
}) =>
CameraProfile(
name: name ?? this.name,
tags: tags ?? this.tags,
);
}
+18
View File
@@ -0,0 +1,18 @@
import 'package:latlong2/latlong.dart';
class OsmCameraNode {
final int id;
final LatLng coord;
final Map<String, String> tags;
OsmCameraNode({
required this.id,
required this.coord,
required this.tags,
});
bool get hasDirection => tags.containsKey('direction');
double? get directionDeg =>
hasDirection ? double.tryParse(tags['direction']!) : null;
}
+16
View File
@@ -0,0 +1,16 @@
import 'package:latlong2/latlong.dart';
import 'camera_profile.dart';
class PendingUpload {
final LatLng coord;
final double direction;
final CameraProfile profile;
final DateTime queuedAt;
PendingUpload({
required this.coord,
required this.direction,
required this.profile,
}) : queuedAt = DateTime.now();
}
+21
View File
@@ -0,0 +1,21 @@
import 'package:flutter/material.dart';
class AddCameraScreen extends StatelessWidget {
const AddCameraScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Add Camera'),
),
body: const Center(
child: Text(
'AddCamera UI coming in Stage 3',
style: TextStyle(fontSize: 18),
),
),
);
}
}
+73
View File
@@ -0,0 +1,73 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../app_state.dart';
import '../widgets/map_view.dart';
import '../widgets/add_camera_sheet.dart';
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
bool _followMe = true;
Future<void> _startAddCamera(BuildContext context) async {
final appState = context.read<AppState>();
appState.startAddSession();
final submitted = await showModalBottomSheet<bool>(
context: context,
isScrollControlled: true,
enableDrag: false,
isDismissible: false,
builder: (_) => const AddCameraSheet(),
);
// null == closed via system back (treat as cancel)
if (submitted == true) {
appState.commitSession();
if (mounted) {
ScaffoldMessenger.of(context)
.showSnackBar(const SnackBar(content: Text('Camera queued')));
}
} else {
appState.cancelSession();
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flock Map'),
actions: [
IconButton(
tooltip: _followMe ? 'Disable followme' : 'Enable followme',
icon: Icon(_followMe ? Icons.gps_fixed : Icons.gps_off),
onPressed: () => setState(() => _followMe = !_followMe),
),
IconButton(
icon: const Icon(Icons.settings),
onPressed: () => Navigator.pushNamed(context, '/settings'),
),
],
),
body: MapView(
followMe: _followMe,
onUserGesture: () {
if (_followMe) setState(() => _followMe = false);
},
),
floatingActionButton: FloatingActionButton.extended(
onPressed: () => _startAddCamera(context),
icon: const Icon(Icons.add_location_alt),
label: const Text('Tag Camera'),
),
);
}
}
+38
View File
@@ -0,0 +1,38 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../app_state.dart';
class SettingsScreen extends StatelessWidget {
const SettingsScreen({super.key});
@override
Widget build(BuildContext context) {
final appState = context.watch<AppState>();
return Scaffold(
appBar: AppBar(title: const Text('Settings')),
body: ListView(
padding: const EdgeInsets.all(16),
children: [
SwitchListTile(
title: const Text('Logged in to OSM (OAuth coming soon)'),
value: appState.isLoggedIn,
onChanged: null, // disabled for now
),
const Divider(),
const Text('Camera Profiles',
style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
...appState.profiles.map(
(p) => SwitchListTile(
title: Text(p.name),
value: appState.isEnabled(p),
onChanged: (v) => appState.toggleProfile(p, v),
),
),
],
),
);
}
}
+54
View File
@@ -0,0 +1,54 @@
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter_map/flutter_map.dart'; // LatLngBounds
import 'package:latlong2/latlong.dart'; // LatLng
import '../models/camera_profile.dart';
import '../models/osm_camera_node.dart';
class OverpassService {
static const _endpoint = 'https://overpass-api.de/api/interpreter';
Future<List<OsmCameraNode>> fetchCameras(
LatLngBounds bbox,
List<CameraProfile> profiles,
) async {
if (profiles.isEmpty) return [];
// Combine enabled profile types into a regex
final types = profiles
.map((p) => p.tags['surveillance:type'])
.whereType<String>()
.toSet();
final regex = types.join('|');
final query = '''
[out:json][timeout:25];
(
node
["man_made"="surveillance"]
["surveillance:type"~"^(${regex})\$"]
(${bbox.southWest.latitude},${bbox.southWest.longitude},
${bbox.northEast.latitude},${bbox.northEast.longitude});
);
out body 100;
''';
final resp =
await http.post(Uri.parse(_endpoint), body: {'data': query.trim()});
if (resp.statusCode != 200) return [];
final data = jsonDecode(resp.body) as Map<String, dynamic>;
final elements = data['elements'] as List<dynamic>;
return elements.whereType<Map<String, dynamic>>().map((e) {
return OsmCameraNode(
id: e['id'],
coord: LatLng(e['lat'], e['lon']),
tags: Map<String, String>.from(e['tags'] ?? {}),
);
}).toList();
}
}
+87
View File
@@ -0,0 +1,87 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../app_state.dart';
import '../models/camera_profile.dart';
class AddCameraSheet extends StatelessWidget {
const AddCameraSheet({super.key});
@override
Widget build(BuildContext context) {
final appState = context.watch<AppState>();
final session = appState.session;
// If the session was cleared before this frame, bail safely.
if (session == null) {
return const SizedBox.shrink();
}
final profiles = appState.profiles;
return Padding(
padding:
EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const SizedBox(height: 12),
Container(
width: 40,
height: 4,
decoration: BoxDecoration(
color: Colors.grey.shade400,
borderRadius: BorderRadius.circular(2),
),
),
const SizedBox(height: 16),
ListTile(
title: const Text('Profile'),
trailing: DropdownButton<CameraProfile>(
value: session.profile,
items: profiles
.map((p) => DropdownMenuItem(value: p, child: Text(p.name)))
.toList(),
onChanged: (p) =>
appState.updateSession(profile: p ?? session.profile),
),
),
ListTile(
title: Text('Direction ${session.directionDegrees.round()}°'),
subtitle: Slider(
min: 0,
max: 359,
divisions: 359,
value: session.directionDegrees,
label: session.directionDegrees.round().toString(),
onChanged: (v) => appState.updateSession(directionDeg: v),
),
),
const SizedBox(height: 8),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0),
child: Row(
children: [
Expanded(
child: OutlinedButton(
onPressed: () => Navigator.pop(context, false),
child: const Text('Cancel'),
),
),
const SizedBox(width: 12),
Expanded(
child: ElevatedButton(
onPressed: () => Navigator.pop(context, true),
child: const Text('Submit'),
),
),
],
),
),
const SizedBox(height: 20),
],
),
);
}
}
+15
View File
@@ -0,0 +1,15 @@
import 'dart:async';
class Debouncer {
Debouncer(this.duration);
final Duration duration;
Timer? _timer;
void call(void Function() action) {
_timer?.cancel();
_timer = Timer(duration, action);
}
void dispose() => _timer?.cancel();
}
+171
View File
@@ -0,0 +1,171 @@
import 'dart:async';
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:latlong2/latlong.dart';
import 'package:geolocator/geolocator.dart';
import 'package:provider/provider.dart';
import '../app_state.dart';
import '../services/overpass_service.dart';
import '../models/osm_camera_node.dart';
import 'debouncer.dart';
class MapView extends StatefulWidget {
const MapView({
super.key,
required this.followMe,
required this.onUserGesture,
});
final bool followMe;
final VoidCallback onUserGesture;
@override
State<MapView> createState() => _MapViewState();
}
class _MapViewState extends State<MapView> {
final MapController _controller = MapController();
final OverpassService _overpass = OverpassService();
final Debouncer _debounce = Debouncer(const Duration(milliseconds: 500));
StreamSubscription<Position>? _positionSub;
LatLng? _currentLatLng;
List<OsmCameraNode> _cameras = [];
@override
void initState() {
super.initState();
_initLocation();
}
@override
void dispose() {
_positionSub?.cancel();
_debounce.dispose();
super.dispose();
}
@override
void didUpdateWidget(covariant MapView oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.followMe && !oldWidget.followMe && _currentLatLng != null) {
_controller.move(_currentLatLng!, _controller.camera.zoom);
}
}
Future<void> _initLocation() async {
final perm = await Geolocator.requestPermission();
if (perm == LocationPermission.denied ||
perm == LocationPermission.deniedForever) return;
_positionSub =
Geolocator.getPositionStream().listen((Position position) {
final latLng = LatLng(position.latitude, position.longitude);
setState(() => _currentLatLng = latLng);
if (widget.followMe) {
_controller.move(latLng, _controller.camera.zoom);
}
});
}
Future<void> _refreshCameras(AppState appState) async {
final bounds = _controller.camera.visibleBounds;
final cams = await _overpass.fetchCameras(bounds, appState.enabledProfiles);
if (mounted) setState(() => _cameras = cams);
}
@override
Widget build(BuildContext context) {
final appState = context.watch<AppState>();
final session = appState.session;
final markers = <Marker>[
if (_currentLatLng != null)
Marker(
point: _currentLatLng!,
width: 16,
height: 16,
child: const Icon(Icons.my_location, color: Colors.blue),
),
..._cameras.map(
(n) => Marker(
point: n.coord,
width: 24,
height: 24,
child: const Icon(Icons.videocam, color: Colors.orange),
),
),
];
final overlays = <Polygon>[
if (session != null && session.target != null)
_buildCone(session.target!, session.directionDegrees),
..._cameras
.where((n) => n.hasDirection)
.map(
(n) => _buildCone(n.coord, n.directionDeg!),
),
];
return Stack(
children: [
FlutterMap(
mapController: _controller,
options: MapOptions(
center: _currentLatLng ?? LatLng(37.7749, -122.4194),
zoom: 15,
maxZoom: 19,
onPositionChanged: (pos, gesture) {
if (gesture) widget.onUserGesture();
if (session != null) {
appState.updateSession(target: pos.center);
}
_debounce(() => _refreshCameras(appState));
},
),
children: [
TileLayer(
urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
userAgentPackageName: 'com.example.flock_map_app',
),
PolygonLayer(polygons: overlays),
MarkerLayer(markers: markers),
],
),
if (session != null)
const IgnorePointer(
child: Center(
child: Icon(Icons.place, size: 40, color: Colors.redAccent),
),
),
],
);
}
Polygon _buildCone(LatLng origin, double bearingDeg) {
const halfAngle = 15.0;
const length = 0.08; // ~80 m
LatLng _project(double deg) {
final rad = deg * math.pi / 180;
final dLat = length * math.cos(rad);
final dLon =
length * math.sin(rad) / math.cos(origin.latitude * math.pi / 180);
return LatLng(origin.latitude + dLat, origin.longitude + dLon);
}
final left = _project(bearingDeg - halfAngle);
final right = _project(bearingDeg + halfAngle);
return Polygon(
points: [origin, left, right],
color: Colors.redAccent.withOpacity(0.25),
borderStrokeWidth: 0,
);
}
}