MotorSignal-App/docs/POLICE_AND_SPEED_TRAP_ALERT...

21 KiB
Raw Blame History

MotorSignal — Police & Speed Trap Alerts Architectural Research

Document Version: 1.0.0
Author: Antigravity / MotorSignal Architecture Group
Status: Approved Architectural Research & Options Analysis
Target Systems: MotorSignal Flutter Client (lib/services/alerts/), MotorSignal Backend (backend/motorsignal_api/), Cloudflare R2 / Firestore Swarm Layer


Executive Summary

Real-time speed camera and mobile police enforcement alerts represent one of the highest-value situational awareness features for motorcyclists. Unlike automotive drivers who can glance at large infotainment dashboards, motorcycle riders operate under extreme cognitive and physical constraints: hands are engaged with handlebar controls, visual focus must remain on road surfaces and vanishing points, and high cornering lean angles render sudden auditory distractions hazardous. Furthermore, motorcycle twisties and mountain passes frequently traverse cellular dead zones where conventional cloud-only navigation apps fail.

This research document evaluates the end-to-end options for implementing a production-grade, legally compliant, offline-resilient, and motorcycle-ergonomic police and speed trap alert system in MotorSignal.

Key Strategic Recommendations

  1. Hybrid Tri-Layer Architecture:
    • Layer 1 (Offline Static Base): Pre-cached fixed speed cameras and red-light cameras extracted from OpenStreetMap (OSM) under Open Database License (ODbL), stored locally in SQLite/Drift for 100% offline canyon coverage.
    • Layer 2 (Commercial Cloud Feed): Integration of HERE Technologies Safety Cameras API for verified commercial fixed cameras, average-speed zones, and historical mobile enforcement hotspots with predictable RESTful pricing and legal indemnity.
    • Layer 3 (MotorSignal Rider Swarm): Real-time peer-to-peer and cloud crowdsourcing over Firestore and group ride mesh networking, allowing pack leads and club members to report mobile speed traps and road hazards with 1-tap glove gestures and automated time-to-live (TTL) pruning.
  2. Motorcycle-Specific Safety Interlock (Lean-Angle Mute):
    • Gate audio notifications behind SensorFusionService telemetry. If the motorcycle's lean angle exceeds 15°, audio warnings are deferred or suppressed until the motorcycle returns to upright orientation (< 10° for 1.5 seconds) to prevent startling riders mid-corner.
  3. Legal & Geofence Compliance:
    • Implement automated jurisdictional compliance: exact camera warnings in the United States and UK, "Safety Zone" (Zone de Danger) compliance in France, and automatic feature deactivation in Germany (§ 23 Abs. 1c StVO) and Switzerland (Art. 57b SVG).

1. Existing MotorSignal Alert Pipeline Architecture

MotorSignal already possesses an alert architecture cleanly separated from the 20 Hz telemetry acquisition pipeline, fully respecting the repository's Telemetry Freeze Boundary.

Current Components & Data Flow

flowchart TD
    subgraph UI ["User Interface Layer"]
        DAR["DashboardAlertRegion<br/>(Visual Banner & Dismiss)"]
        UMV["UnifiedMapView<br/>(Tactical Map Overlay)"]
        SET["SettingsScreen<br/>(Provider API Keys & Category Filters)"]
    end

    subgraph Service ["Alerts Application Layer"]
        RAS["RoadAlertService<br/>• Position listener (LocationService)<br/>• Request serialization (45s / 500m)<br/>• 400m approach gate<br/>• Heading bearing filter (<= 100°)<br/>• 4-sec TTS speech cooldown"]
        TTS["FlutterTts<br/>(Voice Alerts)"]
        FTL["FieldTestLogger<br/>(Forensic Event Logging)"]
    end

    subgraph Providers ["Alert Providers (lib/services/alerts/)"]
        TT["TomTomRoadAlertProvider<br/>(Incident Details API)"]
        CT["CommunityTrafficRoadAlertProvider<br/>(Waze / RapidAPI parser)"]
        MO["MockRoadAlertProvider<br/>(Debug & Diagnostic)"]
    end

    UMV --> RAS
    DAR --> RAS
    SET --> RAS
    RAS --> TTS
    RAS --> FTL
    RAS --> TT
    RAS --> CT
    RAS --> MO

Existing Code Assets

  1. lib/services/alerts/road_alert_models.dart:
    • Pre-defines RoadAlertCategory.police and RoadAlertCategory.speedCamera with corresponding iconography (Icons.local_police, Icons.camera_alt) and distinct color tokens (velocity blue, purple accent).
    • Models RoadAlert containing latitude, longitude, heading, roadName, reportedAt, expiresAt, confidence (0.0 to 1.0), severity, and distanceFromUser.
  2. lib/services/alerts/road_alert_service.dart:
    • Subscribes to locationServiceProvider.getFilteredPositionStream().
    • Implements request serialization: fetches from providers only when stationary timer exceeds 45 seconds or displacement exceeds 500 meters.
    • Implements approach detection: alerts within 400 meters that pass the directional bearing filter (_isAlertAheadOfRider checks delta <= 100.0°) trigger voice synthesis via FlutterTts with a 4-second audio cooldown.
  3. lib/services/alerts/community_traffic_parser.dart:
    • Parses Waze-compatible JSON payloads, identifying POLICE, POLICE_VISIBLE, POLICE_HIDDEN, SPEED_CAM, and RED_LIGHT_CAMERA.
  4. Current Architectural Deficiencies:
    • TomTom Provider: Only queries traffic/services/5/incidentDetails, which is designed for traffic jams, construction, and road closures; it does not receive speed camera or police enforcement data without enterprise Speed Camera Services.
    • Community Provider: Uses an unofficial endpoint/API key against scraped Waze data (wz_live_... or RapidAPI proxies). This presents severe commercial licensing, rate-limiting, and TOS liabilities if packaged in an official production app store release.
    • Zero Local Caching: If cellular connection drops (common on canyon rides), no alerts can be queried or displayed.
    • No Lean-Angle Safety Check: Audio alerts currently fire regardless of bike lean angle or cornering state.

2. Comparative Analysis of Data Sources

Criteria HERE Technologies Safety Cameras TomTom Speed Camera Services OpenStreetMap (OSM / Overpass) SCDB.info B2B Partner API Unofficial Waze / RapidAPI Proxies MotorSignal Rider Swarm (In-House)
Fixed Speed Cameras Excellent (Global) Excellent (Global) Very Good (Crowdsourced) Excellent (100k+ in 100+ countries) Variable User-submitted only
Mobile Police / Speed Traps Good (Verified zones & mobile spots) Good (Historical mobile spots) None (Static only) Frequent mobile zones Excellent (Real-time driver reports) Excellent (High relevance for bike routes)
Red Light Cameras Yes Yes Yes (OSM tagged) Yes Yes User-submitted only
Average Speed (Section Control) Yes (Start, end, corridor) Yes (Corridor) Partial (Relations) Yes Partial Planned
Data Freshness Real-time / Daily Real-time / Hourly Monthly / Batch Daily / Weekly Sub-5 minute Sub-second (< 500 ms mesh / Firestore)
Offline Capability Low (REST query required) Low (REST / Protobuf) Exceptional (100% pre-cacheable in Drift SQLite) Very Good (Can download region DB) Low (Online only) Exceptional (Local P2P BLE mesh in packs)
Commercial Terms & Legality 100% Legal & Enterprise SLA 100% Legal & Enterprise SLA 100% Legal (ODbL with attribution) 100% Legal (B2B commercial contract) High TOS & Trademark Risk 100% Proprietary & Owned
Pricing / Cost Structure Freemium tier; Pay-as-you-go per 1k transactions Enterprise contract / B2B sales quota Free ($0) Monthly base fee + per-asset usage fee $10–$100/mo on RapidAPI; breaks without warning Free (utilizes existing Firebase/Firestore)

3. Deep-Dive Provider Evaluations

3.1. OpenStreetMap (OSM) — Zero-Cost Offline Base Layer

  • Primary Source / Specification: OpenStreetMap Wiki: Tag:highway=speed_camera and Relation enforcement=maxspeed.
  • How It Works: OSM contributors tag physical stationary speed enforcement hardware globally using:
    [out:json][timeout:25];
    (
      node["highway"="speed_camera"](bbox);
      node["enforcement"="maxspeed"](bbox);
    );
    out body;
    
  • Strengths:
    • Zero ongoing API fees: Completely open under the Open Database License (ODbL).
    • 100% Offline Resilience: Coordinates, enforced speed limits, and road names can be bundled or pre-downloaded per state/region into a local SQLite table. When a rider is carving through a canyon with no cellular bars, fixed camera alerts still fire accurately.
    • High European & North American Density: Fixed speed cameras in the UK, France, Germany, Italy, and US metro corridors have virtually 100% OSM coverage.
  • Limitations:
    • Zero mobile police presence or temporary radar gun traps.
    • Relies on volunteer community upkeep for speed limit updates.

3.2. HERE Technologies Safety Cameras API

  • Primary Source / Specification: HERE Developer Portal — Safety Cameras Documentation.
  • Endpoint Architecture: RESTful service supporting radius search and corridor search: GET https://safetycameras.hereapi.com/v2/search?in=circle:latitude,longitude;r=radius_meters
    • Headers: Authorization: Bearer <HERE_TOKEN>
    • Responses include camera type (FIXED_SPEED_CAMERA, MOBILE_SPEED_CAMERA, RED_LIGHT_CAMERA, AVERAGE_SPEED_CAMERA), enforcement speed limit, directionality, and approach bearings.
  • Strengths:
    • Accessible via self-service developer portal without enterprise-only gatekeeping.
    • Covers both fixed infrastructure and frequent mobile speed enforcement zones gathered from OEM connected vehicles.
    • Directional vector data included in response simplifies false-positive filtering.
  • Limitations:
    • Real-time mobile police reporting is based on statistical enforcement patterns rather than instantaneous crowd sightings.

3.3. TomTom Speed Camera & Safety Services

  • Primary Source / Specification: TomTom Speed Camera Services Documentation.
  • Architecture:
    • Standard TomTom Developer Portal Traffic API (traffic/services/5/incidentDetails) does not include speed cameras.
    • Speed Camera data is provided via TomTom's Connected Services / Automotive API (delivered over Protocol Buffers or dedicated REST endpoints) and requires commercial B2B provisioning.
  • Strengths:
    • Industry gold-standard used by Tier-1 automotive navigation systems.
    • Includes French "Danger Zone" transformations out-of-the-box for regulatory compliance.
  • Limitations:
    • Requires corporate sales engagement and contractual minimums. Not suitable for immediate indie developer self-service.

3.4. Community Aggregators & Waze Unofficial Proxies

  • Primary Source: Unofficial reverse proxies (api.wazeapi.com, RapidAPI Waze Scraper, OpenWebNinja).
  • Architecture:
    • Ingests user reports from Waze drivers: POLICE_VISIBLE, POLICE_HIDDEN, SPEED_CAM, HAZARD.
  • Legal & Technical Risks:
    • Terms of Service Violation: Waze/Google explicitly bans scraping, reverse engineering, and commercial republication of crowd data outside their municipal "Waze for Cities" program.
    • Brittle Infrastructure: Waze frequently alters backend protobuf tokens and IP-blocks third-party scrapers, resulting in sudden 403 Forbidden or 429 Too Many Requests errors.
    • App Store Rejection: Direct redistribution of scraped third-party proprietary data violates Apple App Store Review Guideline 5.2.2 and Google Play Developer Program policies.
  • Architectural Recommendation:
    • Retain as an optional "User-Supplied API Key" feature: Keep the existing CommunityTrafficRoadAlertProvider in MotorSignal settings, but label it clearly as "Custom / BYO Endpoint". Users who own a personal RapidAPI key can paste it in, which insulates MotorSignal from corporate scraping liabilities.

3.5. MotorSignal Rider Swarm (In-House Pack & Cloud Crowdsourcing)

  • Primary Source: MotorSignal Firestore Infrastructure + Bluetooth BLE Group Ride Mesh.
  • How It Works: MotorSignal already has real-time Group Ride state management (group_ride_providers.dart) and Firestore syncing:
    1. 1-Tap Reporting: Rider taps a large handlebar-mounted button or uses voice command: "Report Police".
    2. Pack Broadcast (< 500 ms): The alert broadcasts instantly to all riders in the active Group Ride (via Firestore listener or direct BLE mesh if out of cell service). Trailing riders receive immediate notification.
    3. Global Cloud Aggregation: Stored in Firestore collection /road_alerts/{alertId} with geospatial GeoHash indexing and a 60-minute automated Time-To-Live (TTL).
    4. Verification & Voting: Trailing riders passing within 200m see a simple glanceable button: Confirm (👍) or Cleared (❌). Two "Cleared" votes instantly expire the alert.
  • Strengths:
    • Zero recurring third-party API license costs.
    • 100% legal, private, and owned by MotorSignal.
    • Captures motorcycle-specific hazards and twisty canyon speed traps that passenger car drivers never report.

4. Motorcycle Ergonomics & Human Factors

Operating a motorcycle at highway or track-day speeds requires a fundamentally different user interface paradigm compared to automotive navigation.

flowchart LR
    A[Incoming Alert Detected] --> B{Motorcycle Lean Angle > 15°?}
    B -- YES (In Corner) --> C[Defer Audio Notification<br/>Queue in Memory]
    C --> D{Bike Upright & Steady?<br/>Lean < 10° for 1.5s}
    D -- YES --> E[Play Concise Warning Audio]
    B -- NO (Upright / Straight) --> E
    E --> F[Display High-Contrast HUD Banner]

4.1. Lean-Angle Audio Suppression (Cornering Safety)

  • Hazard: A sudden, loud TTS voice announcement ("POLICE REPORTED AHEAD!") or alarm chime delivered into a rider's helmet intercom while dragging knee or executing a tight apex turn can induce panic braking, line disruption, or target fixation, leading to a crash.
  • Solution:
    • SensorFusionService in MotorSignal computes high-fidelity roll/pitch at 20 Hz.
    • When an alert triggers within the 400m distance threshold:
      final currentLean = ref.read(sensorFusionServiceProvider).leanAngleDegrees.abs();
      if (currentLean > 15.0) {
        // Suppress immediate audio, queue alert until bike stands upright
        _queueDeferredAlert(alert);
        return;
      }
      
    • Once the motorcycle returns to upright riding (lean < 10° for consecutive samples), the alert plays. If the rider passes the alert location while still in the turn, the audio is cleanly discarded.

4.2. Audio Design: Helmet Intercom Optimization

  • TTS vs. Tone Beeps:
    • Many riders find constant TTS voice announcements intrusive over helmet intercoms (Sena, Cardo, Packtalk) because they mute intercom communication with riding buddies or music.
    • Proposed Dual-Mode Audio Setting:
      1. Voice Mode (Default): Crisp, 4-word TTS messages: "Police 400 meters ahead." / "Speed camera ahead."
      2. Tactical Tone Mode: Two high-frequency dual beeps (e.g., 880 Hz → 1760 Hz for speed camera; 587 Hz → 1174 Hz for police trap). Fast, recognizable, and non-intrusive.
  • Audio Routing:
    • Route alerts through audio channels configured for Bluetooth HFP/A2DP headset playback with automatic audio ducking.

4.3. Visual HUD & Glove-Friendly UI

  • Glanceability:
    • The alert banner (DashboardAlertRegion) must maintain high contrast (pure black background, neon velocity blue for police, vibrant magenta for speed camera).
    • High-visibility countdown distance: 400m → 300m → 200m → PASS.
  • Glove-Friendly Reporting:
    • Tapping small icon buttons with thick leather motorcycle gloves while moving is impossible.
    • Provide a dedicated full-width "Quick Alert" gesture or long-press action on the tactical dashboard speedometer zone.

Jurisdiction Legal Status of Speed Camera Alerts Legal Status of Mobile Police Alerts Required System Behavior
United States Legal in 50 states (GPS software) Legal (First Amendment protected) Standard exact distance & location alerts enabled. (Note: Radar detector hardware is banned in VA and DC, but GPS crowdsourced apps are legal).
United Kingdom 100% Legal 100% Legal Standard exact distance & location alerts enabled.
France Prohibited (Art. R413-15 Code de la route) Prohibited if exact location Must transform exact points into a "Zone de Danger" (Danger Zone): alert covers a 4 km corridor on motorways, 2 km on secondary roads, 300 m in urban areas. Cannot state "Speed Camera"; must state "Accident / Danger Zone".
Germany Prohibited (§ 23 Abs. 1c StVO) Prohibited while driving Speed camera and speed trap warning features must be disabled when driving/riding in Germany.
Switzerland Strictly Prohibited (Art. 57b SVG) Strictly Prohibited Strict ban: device confiscation risk. Speed warning features must be automatically disabled via GPS boundary check.
Australia / New Zealand Legal in all states Legal Standard exact alerts enabled.

Geofencing Implementation Pattern

Using coarse bounding boxes or country reverse geocoding in RoadAlertService:

enum AlertComplianceJurisdiction { standard, frenchDangerZone, prohibited }

AlertComplianceJurisdiction evaluateJurisdiction(double lat, double lng) {
  if (isInSwitzerland(lat, lng) || isInGermany(lat, lng)) {
    return AlertComplianceJurisdiction.prohibited;
  }
  if (isInFrance(lat, lng)) {
    return AlertComplianceJurisdiction.frenchDangerZone;
  }
  return AlertComplianceJurisdiction.standard;
}

Phase 1: Zero-Cost Offline Static Camera Layer (OSM Cache)

  1. Offline Spatial Dataset:
    • Extract fixed speed cameras, red light cameras, and average speed camera nodes from OpenStreetMap for target regions.
    • Bundle as an offline SQLite asset or downloadable region pack (avoiding breaking changes to the core Drift Schema 7 database).
  2. Provider Integration:
    • Implement OsmRoadAlertProvider implements RoadAlertProvider.
    • Performs fast spatial bounding-box lookup around current GPS location.
    • 100% operational in mountain passes and cellular dead zones.

Phase 2: MotorSignal Rider Swarm (Real-Time Group & Cloud Crowdsourcing)

  1. Firestore Dynamic Layer:
    • Collection /road_alerts/{alertId} with GeoHash, TTL index, category (police, hazard), reporter UID, and upvote counters.
  2. Pack Mesh Broadcast:
    • When a rider in an active Group Ride reports police, broadcast immediately to the active group session so all pack members receive audio/visual warnings regardless of external API configuration.
  3. 1-Tap Handlebar / Glove UI:
    • Add a high-visibility, glove-friendly "Report Enforcement" overlay button on the dashboard and tactical map.

Phase 3: Commercial Telematics Feed (HERE Technologies)

  1. HERE Safety Cameras Provider:
    • Implement HereRoadAlertProvider implements RoadAlertProvider using HERE's /v2/search circular proximity endpoint.
    • Supports verified historical mobile speed traps and active camera points.
    • Configurable API key with graceful fallback to OSM and Swarm layers.

Phase 4: Motorcycle Ergonomics & Safety Controls

  1. Lean-Angle Audio Interlock:
    • Integrate SensorFusionService into RoadAlertService to defer or suppress audio announcements whenever bike lean angle exceeds 15°.
  2. Tactical Radar Tone Mode:
    • Add settings toggle allowing riders to choose between spoken TTS voice alerts and dual-tone radar chirps.
  3. Jurisdictional Geofencing:
    • Automatically suppress camera notifications in Germany and Switzerland, and format as "Danger Zones" in France.

7. Verification & Safety Verification Gates

Before rolling out production road alert changes, the following verification gates must pass:

  1. Telemetry Isolation: Verify TelemetryService 20 Hz acquisition cadence is untouched and zero alert computations run on the sensor thread.
  2. Drift Schema 7 Stability: Verify database migrations and schema hashes remain unmutated unless an explicit migration plan is enacted.
  3. Audio Safety: Unit test verifying audio suppression during active roll/lean states:
    test('Alert audio is suppressed when motorcycle lean angle exceeds 15 degrees', () async { ... });
    
  4. Offline Resilience: Verify alert lookups succeed when device is in Airplane Mode using local cached OSM data.
  5. Full Suite Execution:
    flutter test
    flutter analyze
    flutter build apk --debug
    

End of Architectural Research Document.