diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..301dcf5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,23 @@ +# Xcode +DerivedData/ +build/ +*.xcuserstate +xcuserdata/ +*.xccheckout +*.xcscmblueprint + +# SwiftPM +.build/ +.swiftpm/ + +# macOS +.DS_Store + +# Local diagnostic exports / secrets +DiagnosticsExports/ +*.pcap +*.pcapng +*.key +*.pem +*.p12 +Secrets.xcconfig diff --git a/Docs/HARDWARE_TEST_MATRIX.md b/Docs/HARDWARE_TEST_MATRIX.md new file mode 100644 index 0000000..a886ae3 --- /dev/null +++ b/Docs/HARDWARE_TEST_MATRIX.md @@ -0,0 +1,32 @@ +# Hardware Test Matrix + +Update this file only with sanitized, non-secret results. Never commit Wi-Fi passwords, cryptographic keys, private certificates, or precise personal route history. + +## Test target + +| Field | Value | +|---|---| +| Bike | Guerrilla 450 | +| Dash firmware | TBD | +| Dash SSID pattern | TBD / sanitize before commit | +| iPhone | TBD | +| iOS | TBD | +| Date | TBD | + +## Phase gates + +| Test | Pass condition | Result | Notes | +|---|---|---|---| +| Manual Wi-Fi join | iPhone joins dash AP | ⬜ | | +| In-app Wi-Fi join | User-approved join succeeds | ⬜ | | +| Local path | `NWPath` is satisfied on Wi-Fi | ⬜ | | +| UDP route | Network.framework state reaches ready | ⬜ | Ready does **not** prove remote response | +| Dash datagram | Expected response/event captured | ⬜ | Phase 2 | +| Authentication | 10/10 cold attempts | ⬜ | Phase 4 | +| Projection mode | Dash enters/leaves cleanly | ⬜ | Phase 5 | +| Calibration stream | iPhone pixels visible | ⬜ | Phase 7 | +| 30-minute stream | Stable at baseline profile | ⬜ | | +| Input | Known nav controls decoded | ⬜ | Phase 10 | +| Ignition cycle | Reconnect succeeds | ⬜ | Phase 11 | +| Phone lock | Behavior measured/documented | ⬜ | Phase 12 | +| 60-minute ride | Thermal/battery/network acceptable | ⬜ | Phase 13 | diff --git a/Docs/IMPLEMENTATION_STATUS.md b/Docs/IMPLEMENTATION_STATUS.md new file mode 100644 index 0000000..a1ef046 --- /dev/null +++ b/Docs/IMPLEMENTATION_STATUS.md @@ -0,0 +1,95 @@ +# RideDash Implementation Status + +RideDash is **code-complete for the planned first hardware beta**. Final validation is intentionally manual on a physical iPhone and the user's owned motorcycle display; there is no CI/CD workflow in this repository. + +## iOS product + +- [x] Native SwiftUI application targeting iOS 17+ +- [x] SwiftData local-first persistence +- [x] Vehicle profiles and active vehicle +- [x] Garage / maintenance history +- [x] Fuel logs and full-tank mileage calculation +- [x] Expense tracking and CSV export +- [x] Manual ride history +- [x] Automatic ride recording during projection sessions +- [x] Maintenance next-due km/date tracking +- [x] Local maintenance due-date notifications +- [x] MapKit route calculation and preview +- [x] CoreLocation live navigation state +- [x] Off-route detection and cooldown-protected route recalculation +- [x] Remaining-distance / ETA updates +- [x] Apple Maps hand-off +- [x] `ridedash://` route deep links +- [x] Share Extension for shared map URLs/text +- [x] Currency / distance preferences +- [x] Persisted background-navigation behavior + +## Display interoperability stack + +- [x] Hotspot Configuration entitlement +- [x] User-approved in-app Wi-Fi join request +- [x] App-managed Wi-Fi configuration +- [x] Local network path monitoring +- [x] UDP control channel bound to the configured control source port +- [x] UDP input listener +- [x] UDP video channel +- [x] Sanitized packet/session diagnostic logging +- [x] Hardware test profile +- [x] K1G/TLV framing and rolling sequence patching +- [x] Dynamic dash-provided RSA public-key parsing +- [x] New ephemeral 32-byte AES-256 session key per authentication attempt +- [x] RSA PKCS#1 v1.5 session authentication +- [x] Auth timeout and rejection handling +- [x] Bounded exponential automatic reconnect +- [x] Navigation-mode restoration after reconnect +- [x] Repeated UDP-send failure recovery +- [x] Projection/navigation-mode enter/exit sequencing +- [x] Route-card keep-alive +- [x] Active nav-info keep-alive +- [x] 1 Hz metadata/status heartbeat +- [x] Projection frame heartbeat +- [x] 526×300 off-screen renderer +- [x] Calibration grid mode +- [x] VideoToolbox low-latency H.264 Baseline encoder +- [x] SPS/PPS extraction +- [x] RTP payload type 96 packetization +- [x] FU-A fragmentation for oversized NAL units +- [x] UDP H.264/RTP streaming +- [x] Known RIGHT / LEFT / DOWN / CLICK input decoding +- [x] Input acknowledgement flow +- [x] Input debounce for repeated events +- [x] Manual stop/disconnect recovery paths +- [x] Configurable host/broadcast/ports/FPS/bitrate + +## Diagnostics / release hygiene + +- [x] Thermal-state monitoring +- [x] Battery level/state monitoring +- [x] Low Power Mode monitoring +- [x] In-app deterministic K1G/RTP/FU-A self-check (no network traffic) +- [x] Sanitized diagnostics export +- [x] Privacy manifest bundled in the app target +- [x] UserDefaults required-reason declaration (`CA92.1`) +- [x] Independent-project / interoperability NOTICE +- [x] Safety boundary documented in code and docs + +## Hardware validation still required + +The code intentionally keeps firmware-sensitive assumptions configurable. The following cannot be truthfully marked complete until the physical test: + +- [ ] Xcode compile/sign/install on the target iPhone +- [ ] Exact target-firmware endpoint/port validation +- [ ] Authentication success across cold ignition cycles +- [ ] Navigation-mode transition on the physical dash +- [ ] Calibration grid visible on the physical dash +- [ ] Stable 4 fps H.264/RTP stream for 30 minutes +- [ ] LEFT / RIGHT / DOWN / CLICK verified on the target controls +- [ ] Ignition-cycle reconnect behavior measured +- [ ] Locked-screen/background behavior measured on the target iPhone/iOS version +- [ ] 60-minute thermal/battery/network ride test + +Follow [`MANUAL_TEST_GUIDE.md`](MANUAL_TEST_GUIDE.md) in order. Do not skip directly to video projection on the first hardware session. + +## Validation policy + +No GitHub Actions or CI/CD workflow is used. The first final integration build is compiled, signed and installed manually in Xcode. Unknown protocol families remain read-only, and RideDash permanently excludes ECU, throttle, brakes, ABS, traction control, immobilizer, engine control and other safety-critical vehicle commands. diff --git a/Docs/MANUAL_TEST_GUIDE.md b/Docs/MANUAL_TEST_GUIDE.md new file mode 100644 index 0000000..7d2ef54 --- /dev/null +++ b/Docs/MANUAL_TEST_GUIDE.md @@ -0,0 +1,267 @@ +# RideDash Manual Hardware Test Guide + +This is the required validation path for the first physical iPhone + motorcycle-display beta. There is intentionally **no CI/CD pipeline** for this project. Do not skip directly to projection: each stage proves a narrower dependency and makes failures diagnosable. + +## Safety prerequisites + +- Perform initial protocol tests with the motorcycle stationary, parked securely and in a well-ventilated area. +- Use only a display/motorcycle you own or are authorized to test. +- Do not test unknown packet families while riding. +- RideDash contains no ECU, throttle, brake, ABS, traction-control, immobilizer or engine-control command path. +- Stop immediately if the normal speed/fuel/warning display does not recover after projection is stopped. + +## Before building + +Record these values in `Docs/HARDWARE_TEST_MATRIX.md` and in the app's Diagnostics screen: + +- Motorcycle model +- Dash/display firmware version +- Dash Wi-Fi SSID pattern +- iPhone model +- iOS version +- Whether the official/default navigation flow currently works + +Do **not** commit the Wi-Fi password, authentication session key, private key material, precise route history or other secrets. + +## Xcode setup + +1. Clone `DagerottDev/RideDash` and check out the `phase-1-connectivity-diagnostics` branch (or the eventual merged branch). +2. Open `RideDash.xcodeproj` in Xcode 16 or newer. +3. Select your Apple Development team for the `RideDash` and `RideDashShare` targets. +4. Change bundle identifiers if your signing account requires it. +5. Confirm the main target has **Hotspot Configuration** enabled. +6. Confirm the app shows Local Network and Location permission strings. +7. Select a physical iPhone. Do not use Simulator for dash Wi-Fi/projection validation. +8. Build and install manually. + +## Stage 0 — Baseline display/Wi-Fi + +**Goal:** establish that the phone and dash can form the expected local network before RideDash sends anything. + +1. Power on the motorcycle normally. +2. Enable the display's normal phone/navigation Wi-Fi mode. +3. Record the displayed SSID exactly. +4. Join that SSID manually from iPhone Settings once. +5. Confirm the iPhone remains associated even though the network may have no internet. +6. If possible, record the phone's local address/subnet. The public reference commonly uses a `192.168.1.x` client with the dash at `192.168.1.1`, but do not assume this if your firmware differs. +7. Disconnect and repeat after one ignition power-cycle. + +**Pass:** iPhone can reliably join the display AP. + +## Stage 1 — RideDash Wi-Fi + local network + +**Goal:** validate only Apple's Wi-Fi/local-network layer. + +1. Open RideDash → Settings → Diagnostics. +2. Enter the real SSID and password locally. +3. Tap **Request Wi-Fi Join**. +4. Accept the native iOS approval prompt if shown. +5. Grant Local Network permission. +6. Confirm Diagnostics reports a satisfied path using Wi-Fi. +7. Export a diagnostic log and verify it does not contain the Wi-Fi password. + +**Pass:** user-approved join works and `NWPath` reports usable Wi-Fi. + +## Stage 2 — UDP transport + +**Goal:** prove control/input sockets can open using the configured endpoints. + +Default research profile: + +- Dash: `192.168.1.1` +- Broadcast/control: `192.168.1.255:2000` +- Input listener: UDP `2002` +- Video: `192.168.1.1:5000` + +The control connection binds its local source port to the configured control port to match the public reference behavior. + +1. Open Settings → Connection & Projection. +2. Verify host/broadcast/ports against your observed network. +3. Do not change several variables at once. +4. Start **Connect + Authenticate** only when the bike is stationary. +5. Watch RX/TX counters and Diagnostics logs. + +**Pass:** control transport becomes ready and the input listener is bound without errors. + +## Stage 3 — Authentication + +**Goal:** complete a fresh session handshake without captured secrets. + +Expected public-reference sequence: + +1. RideDash sends the initial K1G burst including the authentication request. +2. Dash sends RSA modulus (`07 00`) and exponent (`07 03`) on the input/control response channel. +3. RideDash generates a new 32-byte AES-256 session key locally. +4. RideDash encrypts `SSID UTF-8 || AES key` using the dash-provided RSA public key with PKCS#1 v1.5. +5. RideDash sends the dynamic session-key packet. +6. Dash returns `07 01 01` for success. + +Check Diagnostics for: + +- RSA modulus received +- RSA exponent received +- Encrypted AES session key sent +- Dash authentication accepted + +Do not publish the session key or raw hardware-specific secrets. + +**Pass:** state reaches **Authenticated**. + +Repeat this stage after three cold ignition cycles. A stale/captured ciphertext must never be required. + +## Stage 4 — Enter navigation mode without video + +**Goal:** prove the control plane before H.264/RTP is involved. + +1. After authentication, tap **Enter Navigation Mode**. +2. RideDash sends navigation context, empty-list state, route-card bursts, projection-on flags and start-navigation. +3. It then starts independent keep-alives: + - projection-frame heartbeat at the configured FPS when projection is active, + - route card at ~1 Hz, + - active nav-info at ~1 Hz, + - metadata/status heartbeat at ~1 Hz. +4. Observe the dash transition. +5. Tap **Stop Projection** and verify the dash returns to its normal state. + +**Pass:** navigation/projection mode can be entered and exited repeatedly without video. + +If the display does not change state, stop here and export the diagnostic log before tuning packet ordering or firmware-specific constants. + +## Stage 5 — Calibration H.264/RTP stream + +**Goal:** display known iPhone-generated pixels before attempting live maps. + +1. Set conservative defaults first: + - 526 × 300 + - 4 fps + - 250 kbps +2. Enable **Calibration grid**. +3. Enter navigation mode. +4. Tap **Start H.264/RTP Projection**. +5. Watch: + - rendered-frame count, + - RTP packet count, + - encoded byte count, + - dash image stability. +6. Run for 2 minutes first. +7. Stop projection and verify normal display recovery. + +**Pass:** calibration grid is visible, correctly framed and stable. + +Only after this passes should you try 8 fps or higher bitrate. Change one parameter per test. + +## Stage 6 — Live route projection + +**Goal:** validate the end-to-end product path. + +1. Reconnect to an internet-capable network first if needed. +2. In RideDash → Navigate, calculate a route with MapKit **before** joining a display Wi-Fi network that has no internet. +3. Rejoin the display Wi-Fi. +4. Authenticate and enter navigation. +5. Disable Calibration grid. +6. Start projection. +7. Verify the projected frame shows: + - destination, + - current maneuver text, + - distance to maneuver, + - ETA, + - remaining distance, + - speed from CoreLocation, + - degraded-GPS state when accuracy is poor. + +The current native dash nav-info heartbeat intentionally uses a conservative generic continue/500 m value as a watchdog-compatible placeholder; the real turn instruction is rendered into the H.264 projection. Hardware results can later expand the native maneuver-code compatibility table. + +**Pass:** live MapKit state visibly updates in the projected UI. + +## Stage 7 — Handlebar/dash input + +Known public-reference input codes: + +- `0x13` → RIGHT +- `0x14` → LEFT +- `0x15` → DOWN +- `0x18` → CLICK + +1. Keep the motorcycle stationary. +2. Press each relevant navigation control once. +3. Confirm RideDash displays the last input and logs it. +4. Confirm LEFT/RIGHT changes the selected route step in the app. +5. Confirm the corresponding acknowledgement is transmitted when `respondToInput` is enabled. +6. Record unknown codes but do not add speculative acknowledgements until understood. + +**Pass:** known inputs are repeatable and do not affect safety-critical vehicle functions. + +## Stage 8 — Recovery testing + +Run these independently: + +1. Projection stop/start without turning off the motorcycle. +2. Wi-Fi off/on on the iPhone. +3. App foreground → inactive → foreground. +4. Motorcycle ignition off/on. +5. Force-close and relaunch RideDash. + +For each test, record whether manual reconnect is needed and whether the dash returns cleanly to normal mode. + +**Pass:** no reinstall/re-pair is needed and normal dash mode is recoverable. + +## Stage 9 — Screen lock/background feasibility + +This is an iOS feasibility measurement, not an assumed feature. + +Test separately: + +1. App foreground, screen on. +2. Screen dimmed. +3. App temporarily inactive. +4. Device locked. + +Record: + +- time until projection freezes (if it does), +- whether CoreLocation continues, +- whether encoder packet counters continue, +- whether UDP traffic resumes after unlock, +- thermal state and battery impact. + +Do not add silent-audio or other fake background-mode workarounds. If iOS suspends video/network work when locked, the supported product mode should remain foreground/low-brightness navigation. + +## Stage 10 — Duration tests + +Only after all earlier stages pass: + +- 10 minutes stationary +- 30 minutes stationary/on-road as appropriate +- 60 minute ride +- 120 minute extended test later + +Measure: + +- disconnects/reconnects, +- projection freezes/blinks, +- encoder/RTP counters, +- iPhone battery drain, +- `ProcessInfo.processInfo.thermalState`, +- GPS accuracy gaps, +- dash recovery after stopping. + +Start at 4 fps. Test 8 and 12 fps only after the conservative profile is stable. + +## Failure reporting + +When something fails, send/export: + +- stage number, +- exact dash firmware, +- iPhone model + iOS version, +- configured host/broadcast/ports/FPS/bitrate, +- RideDash state shown in UI, +- sanitized Diagnostic Log, +- what appeared on the physical dash, +- whether normal dash mode recovered after Stop/Disconnect. + +Do not send Wi-Fi passwords, private keys, session AES keys or personal route history. + +## First recommended test + +For the very first run, stop after **Stage 3 Authentication** and inspect the diagnostic log. If authentication is stable across three ignition cycles, proceed to Stage 4 and then the calibration stream. This gives the fastest useful feedback if the target firmware differs from the public reference. diff --git a/Docs/PROJECT_PLAN.md b/Docs/PROJECT_PLAN.md index 79b2ff5..4d90cd2 100644 --- a/Docs/PROJECT_PLAN.md +++ b/Docs/PROJECT_PLAN.md @@ -1,435 +1,472 @@ # RideDash iOS + Motorcycle Dash Projection -Complete hardware-in-the-loop implementation roadmap +Complete hardware-in-the-loop implementation roadmap and current beta status. **Primary hardware test target:** Guerrilla 450 with Tripper-style TFT dash owned by the project tester. -> Goal: Build a native iPhone app that can join a compatible motorcycle dash Wi-Fi network, establish a projection session, render navigation off-screen, encode frames as H.264, stream them over RTP/UDP, receive non-safety-critical dash input, and remain robust enough for real rides. - -## 1. Product principles - -1. Build bottom-up: connectivity before UI polish. -2. Verify every protocol assumption against owned hardware and exact firmware. -3. Keep protocol bytes and networking out of SwiftUI views. -4. Keep safety-critical motorcycle control permanently out of scope. -5. Use public iOS APIs only. -6. Keep manufacturer branding/assets/keys out of the app unless separately authorized. -7. Treat iOS lock-screen/background behavior as an early feasibility gate. - -## 2. Scope +> Goal: Build a native iPhone app that can join a compatible motorcycle dash Wi-Fi network, establish an authenticated projection session, render navigation off-screen, encode frames as H.264, stream them over RTP/UDP, receive non-safety-critical dash input, recover from connection loss, and remain robust enough for real rides. + +## 1. Current status + +RideDash is **code-complete for the planned first hardware beta**. No CI/CD pipeline is used. The remaining work is physical Xcode build/sign/install plus real-device and motorcycle-dash validation. + +### Implemented in code + +- Native SwiftUI app targeting iOS 17+. +- SwiftData local-first persistence. +- Vehicles, Garage, Fuel, Expenses, Maintenance, Rides and Settings. +- Manual and automatic ride recording during projection sessions. +- Maintenance next-due km/date tracking and local notifications. +- MapKit route search, route preview and Apple Maps hand-off. +- CoreLocation live navigation state. +- Off-route detection with cooldown-protected automatic rerouting. +- Remaining distance, ETA, GPS quality and route recalculation state. +- Share Extension and `ridedash://` route deep links. +- User-approved compatible-display Wi-Fi join via `NEHotspotConfigurationManager`. +- App-managed persistent Wi-Fi configuration. +- Local-network monitoring with `NWPathMonitor`. +- UDP control, input and video channels using Network.framework. +- Configurable protocol host, broadcast address, control/input/video ports, FPS and bitrate. +- K1G/TLV framing and rolling sequence handling. +- Dynamic RSA modulus/exponent parsing from the display. +- Fresh ephemeral AES-256 session key per authentication attempt. +- RSA PKCS#1 v1.5 session authentication. +- Auth timeout/rejection handling. +- Bounded exponential automatic reconnect. +- Navigation-mode restoration after reconnect. +- Repeated UDP-send failure recovery. +- Navigation/projection enter/exit sequencing. +- Route-card, active-nav, status and projection-frame keep-alives. +- VideoToolbox low-latency H.264 Baseline encoder. +- SPS/PPS extraction. +- RTP PT=96 packetization and FU-A fragmentation. +- 526×300 off-screen renderer and calibration grid. +- Known RIGHT / LEFT / DOWN / CLICK decoding and acknowledgements. +- Input debounce for repeated handlebar events. +- Stream/session metrics and sanitized diagnostics export. +- Thermal state, battery state and Low Power Mode monitoring. +- In-app deterministic K1G/RTP/FU-A self-check that generates no network traffic. +- Privacy manifest and required-reason declaration for UserDefaults. +- Independent interoperability NOTICE and permanent safety boundary. + +### Remaining validation only + +- Xcode compile/sign/install on the target iPhone. +- Exact target-firmware IP/port confirmation. +- Repeated authentication on the physical dash. +- Navigation-mode transition validation. +- Calibration grid visible on the physical dash. +- H.264/RTP stability testing. +- Physical LEFT / RIGHT / DOWN / CLICK validation. +- Ignition-cycle reconnect validation. +- iPhone lock/background behavior measurement. +- 30/60/120-minute thermal, battery and network endurance testing. + +## 2. Product principles + +1. Verify every firmware-sensitive assumption against owned hardware. +2. Keep protocol bytes and networking out of SwiftUI views. +3. Keep safety-critical motorcycle control permanently out of scope. +4. Use public iOS APIs only. +5. Keep manufacturer branding/assets/private keys out of the app unless separately authorized. +6. Never persist ephemeral authentication/session secrets. +7. Treat lock-screen/background projection behavior as a hardware/iOS feasibility measurement, not an assumption. +8. Do not use fake audio or other background-execution workarounds. + +## 3. Scope ### In scope -- Native Swift/SwiftUI application, initially iOS 17+. -- User-approved Wi-Fi joining with `NEHotspotConfigurationManager`. -- Local-network state monitoring using `Network.framework`. -- UDP control/diagnostic transport. -- Typed protocol codec and session state machine. -- Compatible session authentication based on lawful/public interoperability research. -- H.264 encoding using VideoToolbox. -- RTP/H.264 packetization and UDP projection. -- 526×300 off-screen dash renderer as the initial reference viewport. -- CoreLocation + MapKit navigation state. +- Native Swift/SwiftUI application. +- Compatible-display Wi-Fi joining and local-network monitoring. +- UDP session transport. +- K1G/TLV-compatible interoperability layer. +- Session authentication using dynamically supplied public-key material. +- H.264/RTP projection. +- 526×300 reference viewport, runtime-tunable where needed. +- CoreLocation + MapKit navigation. +- Route deviation and rerouting. - Non-safety-critical dash button/joystick input. -- Diagnostics, sanitized packet/session logs and hardware compatibility records. -- Vehicle, garage, expenses, ride history and settings product features. -- Share Extension for route hand-off from map apps. +- Automatic reconnect/session restoration. +- Vehicles, garage, expenses, fuel, maintenance, rides and reminders. +- Share Extension for route hand-off. +- Diagnostics, telemetry and compatibility records. ### Explicitly out of scope -- ECU, throttle, ABS, traction control, brakes, immobilizer, engine commands, or other safety-critical vehicle control. -- Firmware modification, secure-boot bypass, firmware-signing bypass, or exploitation. -- Extraction/redistribution of private manufacturer keys, certificates, proprietary assets or confidential material. -- Any design that hides required speed/fuel/warning information. -- Fake audio or other policy-violating background-execution tricks. - -## 3. Definition of done - -| Area | Acceptance criterion | -|---|---| -| Connectivity | Cold-start app can guide user to join the dash AP and establish a valid local-network path. | -| Transport | UDP channels open reliably and datagrams can be logged without UI coupling. | -| Authentication | Session handshake succeeds repeatedly without replaying another device's secrets. | -| Projection control | Dash enters/leaves projection mode cleanly. | -| Video | A stable iPhone-generated H.264 calibration stream displays for at least 30 minutes. | -| Input | Known non-safety-critical button events are decoded and mapped to app actions. | -| Navigation | Live route state is projected with position, maneuver, ETA and remaining distance. | -| Recovery | Wi-Fi loss, ignition cycle and session interruption recover cleanly. | -| Thermals | 60-minute ride has acceptable battery/thermal behavior. | -| Background | Supported screen-lock/background behavior is measured and documented per iOS/device. | -| Safety | No safety-critical vehicle command path exists. | - -## 4. Architecture +- ECU, throttle, ABS, traction control, brakes, immobilizer, engine commands or other safety-critical vehicle control. +- Firmware modification, secure-boot bypass, firmware-signing bypass or exploitation. +- Extraction or redistribution of manufacturer private keys/certificates/confidential assets. +- Any feature that suppresses required speed/fuel/warning information. +- Policy-violating background execution techniques. + +## 4. Definition of done + +| Area | Acceptance criterion | Code status | Hardware status | +|---|---|---|---| +| Connectivity | App joins the compatible display AP and sees a valid local-network path. | ✅ | ⏳ | +| Transport | UDP control/input/video channels operate reliably. | ✅ | ⏳ | +| Authentication | Session handshake succeeds repeatedly without replayed secrets. | ✅ implementation | ⏳ | +| Projection control | Display enters/leaves navigation/projection mode cleanly. | ✅ implementation | ⏳ | +| Video | Stable iPhone-generated H.264 calibration stream for ≥30 min. | ✅ implementation | ⏳ | +| Input | Known button events decode, debounce and acknowledge correctly. | ✅ implementation | ⏳ | +| Navigation | Live route, maneuver, ETA, remaining distance and reroute state project correctly. | ✅ | ⏳ road test | +| Recovery | Connection/session loss triggers bounded reconnect and navigation restoration. | ✅ | ⏳ ignition test | +| Product | Vehicles/garage/expenses/fuel/rides/reminders operate locally. | ✅ | ⏳ device smoke test | +| Thermals | 60-minute ride remains stable with acceptable battery/thermal behavior. | ✅ telemetry | ⏳ | +| Background | Lock/background behavior is measured and documented per device/iOS. | ✅ location support | ⏳ | +| Safety | No safety-critical control path exists. | ✅ | ✅ design boundary | + +## 5. Current architecture ```text RideDashApp -├── App / SwiftUI -│ ├── Pairing -│ ├── Diagnostics +├── App +│ ├── RideDashApp +│ ├── RootView +│ └── DashSessionCoordinator +├── Features +│ ├── Dashboard │ ├── Navigation -│ ├── Projection -│ ├── Vehicles / Garage / Expenses / Rides -│ └── Developer Tools +│ ├── Display Connection / Projection +│ ├── Diagnostics +│ ├── Vehicles +│ ├── Garage / Maintenance / Fuel +│ ├── Expenses +│ ├── Rides +│ └── Settings ├── DashConnectivity │ ├── TripperWiFiManager │ ├── LocalNetworkMonitor -│ ├── DashEndpointResolver │ └── DashTransport ├── DashProtocol -│ ├── K1GCodec -│ ├── TLVCodec -│ ├── DashAuthenticator -│ ├── DashSessionStateMachine -│ └── DashInputDecoder +│ └── DashProtocol.swift +│ ├── HexCodec +│ ├── K1GCodec +│ ├── DashEventDecoder +│ ├── DashAuthenticator +│ └── DashButton mapping ├── ProjectionCore -│ ├── FrameRenderer -│ ├── H264Encoder -│ ├── NALUnitParser -│ ├── RTPPacketizer -│ └── ProjectionStreamer +│ └── ProjectionCore.swift +│ ├── DashFrameRenderer +│ ├── H264Encoder +│ ├── H264NALUnit +│ ├── H264RTPPacketizer +│ └── ProjectionStreamer ├── NavigationCore -│ ├── RouteService -│ ├── NavigationState -│ ├── ManeuverMapper -│ └── OfflineRouteCache (later) +│ └── NavigationCore.swift +│ ├── NavigationLocationService +│ ├── RouteResolver +│ └── NavigationViewModel ├── Diagnostics │ ├── DiagnosticLog -│ ├── PacketTrace -│ ├── SessionTimeline -│ └── Metrics -└── Persistence / Tests - ├── SwiftData - ├── Protocol fixtures - ├── Golden packet tests - └── Hardware compatibility matrix -``` - -## 5. Core boundaries - -```swift -protocol DashWiFiJoining { - func join(ssid: String, passphrase: String) async throws - func removeConfiguration(forSSID ssid: String) async -} - -protocol DashDatagramTransport { - func start() async throws - func stop() - func send(_ data: Data, to port: UInt16) async throws - var incomingPackets: AsyncStream { get } -} - -protocol DashAuthenticating { - func authenticate(session: DashSessionContext) async throws -> AuthenticatedSession -} - -protocol FrameRendering { - var size: CGSize { get } - func render(_ state: ProjectionUIState) throws -> CVPixelBuffer -} - -protocol VideoEncoding { - func encode(_ pixelBuffer: CVPixelBuffer, pts: CMTime) throws -> [H264NALUnit] -} - -protocol RTPPacketizing { - func packetize(_ nalUnits: [H264NALUnit], timestamp: UInt32) -> [Data] -} +│ ├── DeviceHealthMonitor +│ └── deterministic protocol/RTP self-check +├── SwiftData models +│ ├── Vehicle +│ ├── Expense +│ ├── FuelLog +│ ├── MaintenanceRecord +│ └── RideRecord +└── RideDashShare + └── URL/text Share Extension ``` -## 6. Phase plan - -### Phase 0 — Baseline & hardware inventory - -- Record bike model, dash firmware, SSID format, iPhone model and iOS version. -- Verify iPhone can manually join the dash Wi-Fi. -- Create `DashTestProfile` so every exported test log contains hardware/firmware metadata. -- Record official-app behavior only on hardware/accounts the tester owns or is authorized to test. - -**Gate:** Exact firmware/device metadata captured and manual Wi-Fi join succeeds. - -### Phase 1 — iOS Wi-Fi join & local-network diagnostics - -- Add Hotspot Configuration capability. -- Implement `TripperWiFiManager` using `NEHotspotConfigurationManager`. -- Add pairing UI for SSID/passphrase and explicit user consent. -- Implement `LocalNetworkMonitor` with `NWPathMonitor`. -- Add configurable dash host (initial hypothesis `192.168.1.1`). -- Add a non-destructive route/socket readiness check. -- Add structured diagnostic timeline and export. - -**Gate:** App can request the dash network, observe a viable local path and initialize the diagnostic network stack on the physical iPhone. - -### Phase 2 — UDP transport & packet diagnostics +## 6. Session lifecycle -- Implement `DashTransport` with Network.framework UDP. -- Support multiple protocol ports and independent receive paths. -- Hex/structured packet logging with timestamp, direction, endpoint and byte count. -- Sanitized session trace export. -- Deterministic fixture replay for tests. +```text +Disconnected + ↓ +Wi-Fi joined + ↓ +UDP transport ready + ↓ +Initial K1G burst + ↓ +RSA modulus + exponent received + ↓ +Generate fresh AES-256 key + ↓ +RSA PKCS#1 v1.5 encrypted session payload + ↓ +Authenticated + ↓ +Navigation-mode control sequence + ↓ +Route/nav/status keep-alives + ↓ +H.264 renderer → encoder → RTP → UDP + ↓ +Projecting +``` -**Gate:** Bidirectional datagrams can be observed/reproduced without SwiftUI depending on raw protocol bytes. +Failure handling: -### Phase 3 — protocol codec & session state machine +```text +Transport/Auth/Repeated-send failure + ↓ +Bounded exponential reconnect +1s → 2s → 4s → 8s → 16s + ↓ +Re-authenticate + ↓ +Restore navigation mode when applicable +``` -- Typed K1G/TLV framing. -- Decode known auth/control/input families. -- State machine: disconnected → Wi-Fi joined → transport ready → authenticating → authenticated → nav-ready → projecting. -- Strict malformed-length/type handling. -- Golden packet tests. +Manual Disconnect always cancels automatic reconnect. -**Gate:** Reference/captured packets decode into typed events and transitions are unit-tested. +## 7. Protocol / projection defaults to validate + +These are **research defaults**, not guaranteed firmware constants: -### Phase 4 — session authentication +| Setting | Current default | +|---|---:| +| Display host | `192.168.1.1` | +| Broadcast/control host | `192.168.1.255` | +| Control UDP | `2000` | +| Input UDP | `2002` | +| Video RTP UDP | `5000` | +| Viewport | `526×300` | +| Initial FPS | `4` | +| Initial bitrate | `250 kbps` | +| RTP payload type | `96` | + +All firmware-sensitive network values remain configurable in the app. + +## 8. Navigation implementation -- Parse public-key material exposed by the session handshake where applicable. -- Generate ephemeral session material locally. -- Isolate cryptographic/padding details behind `DashAuthenticator`. -- Explicit auth timeout/retry/failure states. -- Never persist ephemeral secrets. +Implemented navigation behavior: + +- Destination text, coordinates or shared URL input. +- `MKLocalSearch` resolution. +- `MKDirections` automobile routing. +- Current location and heading tracking. +- Active maneuver/step tracking. +- ETA and remaining-distance updates. +- GPS degraded-state reporting. +- Off-route distance measurement against route polyline. +- Cooldown-protected route recalculation to avoid reroute loops. +- Recalculation count available for diagnostics. +- Handlebar input can move through projected navigation state without touching vehicle systems. -**Gate:** Ten consecutive cold authentication attempts succeed on the target dash. +## 9. Product features -### Phase 5 — projection control plane +### Vehicles -- Projection-on/off sequencing. -- Required navigation/session metadata. -- Keep-alive/tick handling. -- Firmware capability flags instead of global assumptions. -- Best-effort projection-off cleanup on user stop/disconnect paths. +- Multiple vehicle profiles. +- Active vehicle selection. +- Registration and odometer. +- Insurance expiry. +- PUC expiry. +- Last-service date. -**Gate:** Dash transitions between normal and projection/navigation modes repeatedly without video. +### Garage / maintenance -### Phase 6 — H.264 encoder proof +- Fuel logs. +- Full-tank mileage calculation. +- Maintenance records. +- Next-due odometer. +- Next-due date. +- Local due-date notifications. -- Create a 526×300 `CVPixelBuffer` target. -- Low-latency `VTCompressionSession`. -- Start around 4 fps and ~200–250 kbps; keep profile runtime-tunable. -- Extract SPS/PPS and NAL units. -- Local encoder harness before bike transmission. +### Expenses -**Gate:** Stable H.264 elementary stream at target dimensions. +- Fuel/service/repair/accessory/gear/food/stay/transport/other categories. +- Local persistence. +- Currency preferences. +- CSV export. -### Phase 7 — RTP/H.264 & first pixels +### Rides -- RTP sequence/timestamps. -- Single-NAL packets and FU-A fragmentation. -- Send to firmware-validated video endpoint (public references use UDP/5000 as an initial hypothesis). -- First render calibration grid/animation, not maps. -- Capture packets/sec, bitrate, sequence gaps and encode latency. +- Manual ride entries. +- Automatic ride session around projection usage. +- GPS distance accumulation. +- Start/end timestamps. +- Destination association. -**Gate:** Physical dash displays iPhone-generated calibration pixels reliably. +## 10. Diagnostics and privacy -### Phase 8 — dash-safe renderer +Diagnostics include: -- Exact target render size. -- Circular-safe-area calibration screen. -- Large glanceable typography/icons/cards/route geometry. -- Same renderer for local preview and projection. -- Snapshot tests. +- Wi-Fi join/remove events. +- Network path and interface state. +- Session state transitions. +- UDP RX/TX counts. +- Sanitized packet prefixes. +- Authentication/reconnect events. +- Encoder/RTP counters. +- Route recalculation state. +- Thermal state. +- Battery level/state. +- Low Power Mode. -**Gate:** UI is readable on the actual dash, not merely in Simulator. +The deterministic self-check validates K1G sequencing and RTP/FU-A behavior **without opening a network connection**. -### Phase 9 — navigation engine +Diagnostic export excludes by default: -- CoreLocation live position/heading. -- MapKit route generation initially. -- `NavigationState` independent of MapKit UI. -- Maneuver, distance-to-turn, ETA, remaining distance and route progress. -- Route deviation/recalculation and degraded-GPS state. +- Wi-Fi passwords. +- AES session keys. +- RSA/private key material. +- Detailed route/location history. -**Gate:** On-road projected instructions track the route correctly. +Release hygiene currently includes: -### Phase 10 — dash input +- Privacy manifest. +- UserDefaults required-reason declaration (`CA92.1`). +- Local Network permission copy. +- Location permission copy. +- Hotspot Configuration entitlement. +- Independent interoperability NOTICE. + +## 11. Recovery behavior + +Implemented recovery paths: + +- Authentication timeout. +- Authentication rejection limit. +- Transport failure detection. +- Repeated control-send failure detection. +- Bounded exponential reconnect. +- Re-authentication after reconnect. +- Navigation-mode restoration. +- User-visible reconnect attempt/reason. +- Input-event debounce. +- Manual stop/disconnect cancellation. -- Listen on firmware-validated input channel (public references use UDP/2002 as an initial hypothesis). -- Decode known LEFT/RIGHT/DOWN/CLICK-style events into semantic `DashInputAction` values. -- Ack where required. -- Debounce repeats and log unknown codes. -- Restrict actions to infotainment/navigation UI. +Still to verify physically: -**Gate:** Known buttons reliably drive projected UI. +- AP disappearance when ignition turns off. +- Rejoin timing after ignition turns on. +- Whether the display requires extra firmware-specific restart packets. +- Whether H.264 projection itself must be manually restarted after a recovered session. -### Phase 11 — recovery & ignition cycles +## 12. Hardware validation plan -- Detect AP loss, socket failure and session expiry. -- Bounded reconnect with visible state. -- Handle ignition off/on and phone Wi-Fi changes. -- Persist compatibility metadata only, not session secrets. +Run tests in this order. Do not jump directly to video on the first session. -**Gate:** Repeated ignition cycles recover without reinstall/re-pair. +### Stage A — Xcode/device baseline -### Phase 12 — lock-screen/background feasibility +1. Open `RideDash.xcodeproj`. +2. Select the developer team for RideDash and RideDashShare. +3. Compile/sign/install on the physical iPhone. +4. Fix any Xcode/compiler/signing issues found by the real SDK. +5. Open Diagnostics and run the local deterministic self-check. -- Test foreground, inactive, dim screen and locked device. -- Measure networking/encoding duration after lock on physical hardware. -- No fake audio/background tricks. -- If full lock streaming is not viable, define a supported foreground/low-brightness operating mode. +### Stage B — network -**Gate:** Supported operating mode is reproducible and documented by iPhone/iOS version. +1. Record dash firmware and iPhone/iOS version. +2. Enable the display Wi-Fi/AP through the normal motorcycle UI. +3. Record the SSID. +4. Confirm manual iOS join once. +5. Use RideDash to join the compatible display Wi-Fi. +6. Confirm `NWPath` reports Wi-Fi/local networking. +7. Confirm control transport can become ready. -### Phase 13 — thermal/battery/network tuning +### Stage C — authentication -- 30/60/120-minute tests. -- Measure thermal state and battery drain. -- Cache static frames/regions. -- Tune 4/8/12 fps profiles and bitrate. -- Correlate freezes/blinks/latency with network and encoder metrics. +1. Press **Connect + Authenticate**. +2. Confirm modulus and exponent arrive. +3. Confirm session-key packet is sent. +4. Confirm authentication accepted. +5. Repeat across at least three cold ignition cycles; target eventually 10/10. -**Gate:** 60-minute ride completes without sustained thermal warning or projection instability. +### Stage D — navigation control plane -### Phase 14 — product integration +1. Enter navigation mode without starting H.264. +2. Confirm display changes to the expected navigation/projection state. +3. Verify keep-alive stability. +4. Stop and confirm clean return. -- Vehicles, Garage, Expenses, Ride History, Settings. -- Connect/Start Projection product flows. -- Apple Maps/Google Maps Share Extension. -- Ride logging around projection session. -- Maintenance notifications as a separate product module. +### Stage E — first pixels -**Gate:** Product feels cohesive rather than a protocol demo. +1. Enable calibration grid. +2. Start H.264/RTP projection at 526×300, 4 fps, 250 kbps. +3. Confirm framing and orientation. +4. Run for 30 minutes. +5. Adjust packet size/FPS/bitrate only if hardware requires it. -### Phase 15 — compatibility & release hardening +### Stage F — controls -- Firmware/device capability records. -- Unit tests, renderer tests and hardware smoke checklist. -- Privacy manifest/permission text. -- License/NOTICE and trademark review. -- Distribution decision only after policy/legal/stability review. +Verify: -**Gate:** Tagged beta with reproducible hardware results and no safety-critical coupling. +- LEFT +- RIGHT +- DOWN +- CLICK +- acknowledgements +- debounce behavior -## 7. First hardware session +### Stage G — recovery/background/endurance -The first bike session intentionally stops before authentication/video. +- Ignition off/on reconnect. +- Wi-Fi interruption. +- Screen dim/inactive. +- Phone locked. +- 30-minute session. +- 60-minute session. +- Optional 120-minute endurance session. +- Observe thermal and battery telemetry. -1. Record dash firmware and iPhone/iOS version. -2. Enable the dash Wi-Fi/AP using the bike's normal user flow. -3. Record the displayed SSID; do not assume another bike's SSID. -4. Join manually in iOS Settings once. -5. Launch RideDash and grant Local Network permission when prompted. -6. Use the Diagnostics screen to request the Wi-Fi join configuration. -7. Observe path/interface changes. -8. Initialize the UDP diagnostic stack only after the bike is stationary. -9. Record state transitions/errors. -10. Power-cycle the bike and repeat three times. -11. Export a sanitized diagnostic log. - -## 8. Hardware test matrix +## 13. Hardware test matrix | Test | Pass condition | Result | |---|---|---| +| Xcode build/install | App launches on target iPhone | | +| Local self-check | K1G/RTP/FU-A checks pass | | | Manual Wi-Fi join | iPhone joins expected local subnet | | | In-app join | User-approved join succeeds | | -| Local Network permission | App can initialize local networking | | +| Local Network permission | App initializes local networking | | | UDP transport | Socket state reaches ready | | -| Dash datagram | At least one expected dash-originated datagram is captured once Phase 2 probes are defined | | -| Authentication | 10/10 cold attempts | | -| Enter projection | Dash transitions to navigation/projection | | -| Projection off | Dash returns cleanly | | -| Calibration grid | Correctly framed on physical dash | | +| Authentication | Repeated cold attempts succeed | | +| Enter navigation | Physical display transitions correctly | | +| Projection off | Physical display returns cleanly | | +| Calibration grid | Correct framing/orientation | | | 4 fps | 30 min stable | | | 8 fps | Stable or documented unsupported | | | 12 fps | Stable or documented unsupported | | -| Dash buttons | Known navigation inputs decoded | | -| Ignition cycle | Reconnect succeeds | | +| Dash buttons | Known navigation inputs decoded/acked | | +| Ignition cycle | Automatic reconnect succeeds | | +| Reconnect restore | Navigation mode returns automatically | | | Phone lock | Behavior measured/documented | | | 60-minute ride | Thermal/battery/network acceptable | | -## 9. Diagnostics requirements +## 14. Release decision -Before UI polish, log: +Do not treat the current branch as production-ready until hardware validation is complete. -- Wi-Fi request/join/remove events. -- `NWPath` status and active interfaces. -- Transport state transitions. -- Packet timestamp, direction, endpoint and byte count. -- Sanitized hex prefix for protocol debugging. -- Session-state transitions. -- Encoder FPS, bytes/sec, keyframes and latency. -- RTP sequence/packets/sec/fragmentation/send errors. -- Thermal state and battery level/state. -- GPS accuracy/heading accuracy/recalculation count. +Before public distribution: -Diagnostic export must exclude private keys and detailed location history by default. +- Complete physical compatibility testing. +- Document supported dash firmware/device combinations. +- Confirm background operating mode. +- Perform App Store/privacy review. +- Perform trademark/IP/interoperability review. +- Keep public branding generic unless explicit authorization exists. +- Retain the permanent safety boundary. -## 10. Suggested repository structure +## 15. Current repository workflow -```text -RideDash/ -├── RideDash.xcodeproj/ -├── RideDash/ -│ ├── App/ -│ ├── Features/ -│ │ ├── Pairing/ -│ │ ├── Diagnostics/ -│ │ ├── Projection/ -│ │ ├── Navigation/ -│ │ ├── Vehicles/ -│ │ ├── Garage/ -│ │ ├── Expenses/ -│ │ └── Rides/ -│ ├── DashConnectivity/ -│ ├── DashProtocol/ -│ ├── ProjectionCore/ -│ ├── NavigationCore/ -│ ├── Diagnostics/ -│ ├── Models/ -│ ├── Services/ -│ └── Resources/ -├── RideDashTests/ -├── Docs/ -│ ├── PROJECT_PLAN.md -│ ├── HARDWARE_TEST_MATRIX.md -│ ├── PROTOCOL_NOTES.md -│ └── SAFETY_SCOPE.md -└── NOTICE -``` +- Implementation branch: `phase-1-connectivity-diagnostics` +- Draft PR: RideDash iOS complete first hardware-beta implementation +- CI/CD: intentionally not used +- Validation: manual Xcode + physical iPhone + owned motorcycle dash + +Supporting documents: + +- `Docs/IMPLEMENTATION_STATUS.md` — exact code-completion checklist. +- `Docs/MANUAL_TEST_GUIDE.md` — step-by-step device/bike validation procedure. +- `Docs/HARDWARE_TEST_MATRIX.md` — test result record. +- `Docs/PROTOCOL_NOTES.md` — interoperability research notes. +- `Docs/SAFETY_SCOPE.md` — permanent safety exclusions. + +## 16. Immediate next action + +The next step is no longer additional feature coding. It is: + +1. Build/sign/install the branch on the physical iPhone. +2. Run the local self-check. +3. Connect to the compatible dash Wi-Fi. +4. Stop after the first successful authentication attempt and export the sanitized diagnostic log. +5. Use that hardware result to tune only firmware-specific values if needed. -## 11. Build order - -1. Wi-Fi join -2. Local-network monitor -3. UDP transport -4. Packet logger -5. Protocol codec -6. Authentication -7. Projection control plane -8. H.264 encoder -9. RTP packetizer -10. Calibration stream on physical dash -11. Renderer -12. Live navigation -13. Dash input -14. Session recovery -15. Lock/background feasibility -16. Thermal/battery tuning -17. Product integration -18. Compatibility/beta hardening - -## 12. Phase 1 acceptance checklist - -- [ ] Project builds on a physical iPhone. -- [ ] Diagnostics screen displays current `DashTestProfile`. -- [ ] User can request joining an entered dash SSID/passphrase. -- [ ] Native iOS approval/error is surfaced clearly. -- [ ] App reports current `NWPath` status/interfaces. -- [ ] Configurable dash host defaults to the current research hypothesis but is editable. -- [ ] UDP diagnostic connection can be initialized/stopped without crash. -- [ ] Structured state transitions appear in the diagnostic log. -- [ ] Diagnostic log can be exported through the share sheet. -- [ ] Three bike power-cycle attempts are recorded. -- [ ] Authentication/projection/video remains disabled until Phase 1 hardware gate passes. - -## 13. Immediate next test information needed - -To close Phase 0 and validate Phase 1 on the physical bike, record: - -- Dash firmware version -- Dash Wi-Fi SSID shown by the bike -- Whether the AP requires a password, and how the user obtains it -- iPhone model -- iOS version -- Whether manual iPhone join succeeds -- IP/subnet observed after manual join, if visible - -Do **not** commit real Wi-Fi credentials or private device/session secrets to the repository. +Do **not** commit real Wi-Fi credentials, authentication/session keys, private device secrets or precise personal route history to the repository. diff --git a/Docs/PROTOCOL_NOTES.md b/Docs/PROTOCOL_NOTES.md new file mode 100644 index 0000000..ec655b5 --- /dev/null +++ b/Docs/PROTOCOL_NOTES.md @@ -0,0 +1,132 @@ +# RideDash protocol notes + +This document records the interoperability assumptions currently encoded in RideDash. These are **not manufacturer specifications**. They are implementation notes based on publicly available independent interoperability work and must be verified against hardware you own/control. + +## Default network profile + +| Item | Current default | +|---|---:| +| Dash host | `192.168.1.1` | +| Broadcast target | `192.168.1.255` | +| Control UDP | `2000` | +| Input UDP | `2002` | +| H.264/RTP UDP | `5000` | +| Viewport | `526 × 300` | +| RTP payload type | `96` | +| RTP clock | `90000 Hz` | +| Initial FPS | `4` | +| Initial bitrate | `250 kbps` | + +All network values are represented by `DashProtocolProfile` and are editable from the developer-facing Display screen. + +## K1G envelope + +The current codec treats packets as: + +```text +0..1 outer packet length, big endian +2..3 segment count, big endian +4..7 reserved/header bytes +8.. TLV-like segments +``` + +Each segment begins with: + +```text +type:1 | subtype:1 | length:2 big endian | payload:length +``` + +Outbound reference packets contain the ASCII marker `K1G ` followed by a rolling sequence byte. `K1GCodec.patchSequence` changes only that byte. + +Unknown message families are logged; they should not become write commands until their role is understood. + +## Session authentication + +Current public-reference behavior implemented by `DashAuthenticator`: + +1. App sends the request-auth control packet. +2. Display supplies RSA public material as K1G segments: + - `07 00` — modulus + - `07 03` — exponent +3. RideDash creates a cryptographically random 32-byte AES key using `SecRandomCopyBytes`. +4. Plaintext is `UTF8(display Wi-Fi SSID) || AES-256 session key`. +5. Plaintext is encrypted with the display-provided RSA key using PKCS#1 v1.5 (`SecKeyAlgorithm.rsaEncryptionPKCS1`). +6. Ciphertext is inserted in the reference session-key K1G packet. +7. `07 01 01` is treated as explicit authentication success. + +The AES key is ephemeral and is never written to SwiftData, UserDefaults, diagnostics, or exported logs. + +## Navigation / projection control + +`DashSessionCoordinator` follows the public reference ordering: + +1. navigation context +2. empty list state +3. repeated route-card packets +4. projection frame/on state +5. start-navigation control +6. route-card heartbeat +7. projection frame heartbeat while video is active + +Stopping projection sends the reference stop/off pair and cancels both heartbeats. + +## Known input mapping + +The current reference input decoder maps `09 00` one-byte payloads: + +| Value | Semantic action | +|---:|---| +| `0x13` | RIGHT | +| `0x14` | LEFT | +| `0x15` | DOWN | +| `0x18` | CLICK | + +RideDash maps these only to navigation UI actions. The corresponding acknowledgement uses the public `06 80 0001 XX` pattern. + +## H.264 / RTP + +Video is generated natively with VideoToolbox: + +- H.264 Baseline profile +- real-time mode +- frame reordering disabled +- default 526×300 +- low initial FPS/bitrate for decoder stability + +VideoToolbox produces AVCC length-prefixed NAL units. RideDash extracts them and captures the encoder's own SPS/PPS. + +The embedded-display compatibility behavior follows the public working packetizer: + +- SEI and AUD NALs are not sent. +- Ordinary small NALs are carried in one RTP packet. +- Large NALs use H.264 FU-A fragmentation. +- STAP-A is not used. +- Before an IDR is packetized, current SPS and PPS are bundled with the IDR using embedded Annex-B `00 00 00 01` separators. +- The bundle is then sent as a normal/FU-A RTP payload plan. +- RTP marker is set only on the final payload of the access unit. + +Initial max RTP payload is 1380 bytes. If first-pixel testing shows fragmentation/MTU problems, lower this value before changing encoder semantics. + +## Hardware-validation order + +1. Wi-Fi join +2. UDP transport ready +3. RSA material received +4. auth success +5. navigation-mode transition +6. calibration grid only +7. stable low-FPS stream +8. button input +9. live MapKit navigation +10. ignition/reconnect tests +11. phone lock/background measurement + +## References used during implementation + +- `OpenMotoDash/better-dash` — public independent interoperability implementation and protocol notes. +- `subtlesayak/open-dash` — public product reference and historical interoperability context. +- Apple NetworkExtension documentation — `NEHotspotConfigurationManager`. +- Apple Network.framework documentation — UDP transport/listening. +- Apple VideoToolbox documentation — H.264 hardware encoding. + +If behavior differs on the test firmware, preserve existing behavior behind a compatibility profile rather than replacing it globally. diff --git a/Docs/SAFETY_SCOPE.md b/Docs/SAFETY_SCOPE.md new file mode 100644 index 0000000..066815c --- /dev/null +++ b/Docs/SAFETY_SCOPE.md @@ -0,0 +1,34 @@ +# Safety Scope + +RideDash is an infotainment/navigation interoperability project. + +## Allowed scope + +- Dash Wi-Fi connectivity +- Navigation/session interoperability +- Projection rendering and video transport +- Route/navigation display +- Non-safety-critical dash buttons used to control RideDash UI +- Diagnostics and compatibility testing on hardware the tester owns or is authorized to test + +## Permanently excluded + +RideDash must not implement or experiment with commands affecting: + +- ECU/engine management +- Throttle +- Brakes +- ABS +- Traction control +- Immobilizer/security systems +- Safety warnings or mandatory instrumentation +- Firmware flashing, secure boot, or firmware-signing bypass + +## Test rules + +1. Run first-time networking/protocol experiments while the motorcycle is stationary. +2. Treat unknown packet families as read-only until their purpose is understood. +3. Keep a first-class, best-effort projection-stop path. +4. Do not commit passwords, private keys, private certificates, or secret session material. +5. Do not use fake background modes to bypass iOS execution policy. +6. Do not present RideDash as manufacturer-affiliated or endorsed without authorization. diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000..7b401bf --- /dev/null +++ b/NOTICE @@ -0,0 +1,12 @@ +RideDash +Copyright (c) 2026 RideDash contributors + +RideDash is an independent, brand-neutral motorcycle navigation and ride companion project. + +The compatible-display interoperability layer is based on publicly available interoperability research and clean-room reimplementation using public iOS APIs. The project does not include manufacturer firmware, private keys, proprietary certificates, extracted assets, or safety-critical vehicle-control functionality. + +Some protocol behavior and packet sequencing were informed by publicly available open-source projects and research notes, including OpenDash / better-dash style motorcycle display interoperability work. Review and preserve the license notices of any third-party source code that is directly incorporated in future changes. + +Royal Enfield, Tripper, and any other third-party product or company names are trademarks of their respective owners. RideDash is not affiliated with, endorsed by, or sponsored by those trademark owners. + +The project permanently excludes ECU, throttle, brakes, ABS, traction control, immobilizer, firmware modification, engine control, and other safety-critical vehicle command paths. diff --git a/README.md b/README.md index de19041..e9d542e 100644 --- a/README.md +++ b/README.md @@ -1,17 +1,85 @@ # RideDash -RideDash is a native iOS motorcycle navigation and ride companion project. +RideDash is a native iOS motorcycle navigation and ride companion with an experimental interoperability layer for compatible Wi-Fi motorcycle displays. -The project is being developed phase-by-phase, starting with hardware connectivity and diagnostics, then protocol/session interoperability, projection, navigation rendering, input handling, ride resilience, and product features. +The app is intentionally brand-neutral and limits display integration to infotainment/navigation. It does **not** implement ECU, throttle, brakes, ABS, traction control, immobilizer, firmware modification, or other safety-critical vehicle control. -## Current status +## Implemented -- Project planning: in progress -- Phase 0 — hardware baseline: ready for test data -- Phase 1 — iOS Wi-Fi connectivity & diagnostics: implementation starting +### iOS product +- SwiftUI app targeting iOS 17+ +- SwiftData local-first persistence +- Vehicle profiles and active-vehicle selection +- Garage / maintenance history +- Fuel logs and full-tank mileage calculation +- Expense tracking and CSV export +- Ride history +- MapKit route search/preview +- CoreLocation live navigation state +- Apple Maps hand-off +- `ridedash://route?url=...` deep-link route intake +- Share Extension for URL/text hand-off from Maps and other apps +- Currency and distance preferences -See [`Docs/PROJECT_PLAN.md`](Docs/PROJECT_PLAN.md) for the complete roadmap. +### Compatible display stack +- User-approved Wi-Fi joining with `NEHotspotConfigurationManager` +- Local-network monitoring +- UDP control transport plus input listener +- K1G/TLV framing and sequence handling +- Dash-provided RSA public-key parsing +- Ephemeral 32-byte AES session generation +- RSA PKCS#1 v1.5 session authentication flow +- Projection/navigation-mode on/off sequencing +- 526×300 off-screen renderer +- VideoToolbox low-latency H.264 Baseline encoding +- RTP payload type 96, single-NAL and FU-A packetization +- SPS/PPS + IDR bundling matching the public interoperability reference +- UDP video streaming to a configurable endpoint +- Known non-safety-critical dash input decoding (LEFT/RIGHT/DOWN/CLICK reference values) +- Input acknowledgements +- Session/projection keep-alives +- Sanitized diagnostics and manual hardware profile logging -## Safety boundary +## Status -RideDash is limited to infotainment/navigation interoperability. It does **not** implement ECU, throttle, braking, ABS, immobilizer, traction-control, or other safety-critical vehicle control. +The implementation is **code-complete for the planned first hardware beta, but not hardware-validated yet**. No CI/CD pipeline is used for this project by design. The final validation step is a manual build/run on a physical iPhone and a user-owned motorcycle display. + +Protocol defaults in the app are research defaults and remain editable: + +- dash host: `192.168.1.1` +- control broadcast: `192.168.1.255` +- control UDP: `2000` +- input UDP: `2002` +- RTP/H.264 UDP: `5000` +- initial display viewport: `526×300` +- initial projection profile: `4 fps`, `250 kbps` + +Do not assume these values apply to every firmware. Record the exact firmware in Diagnostics before changing protocol behavior. + +## Manual test + +Read [`Docs/MANUAL_TEST_GUIDE.md`](Docs/MANUAL_TEST_GUIDE.md) before the first physical-device test. Start with the motorcycle stationary and the display in its normal user mode. + +## Documentation + +- [`Docs/PROJECT_PLAN.md`](Docs/PROJECT_PLAN.md) — complete architecture/roadmap +- [`Docs/PROTOCOL_NOTES.md`](Docs/PROTOCOL_NOTES.md) — protocol assumptions and public-reference mapping +- [`Docs/MANUAL_TEST_GUIDE.md`](Docs/MANUAL_TEST_GUIDE.md) — first end-to-end hardware test +- [`Docs/HARDWARE_TEST_MATRIX.md`](Docs/HARDWARE_TEST_MATRIX.md) — results matrix +- [`Docs/SAFETY_SCOPE.md`](Docs/SAFETY_SCOPE.md) — permanent safety boundary + +## Build + +1. Clone the repository. +2. Open `RideDash.xcodeproj` in Xcode 16 or newer. +3. Select your Apple Development team for both **RideDash** and **RideDashShare**. +4. Change bundle identifiers if your developer account requires different identifiers. +5. Confirm the **Hotspot Configuration** capability is available for the RideDash target. +6. Run on a physical iPhone. Wi-Fi accessory behavior and actual projection cannot be validated in Simulator. + +## Important limitations + +- iOS background location is enabled only for legitimate active navigation. It does not guarantee that VideoToolbox/UDP projection will keep running indefinitely after the device is locked; this must be measured on the target iPhone/iOS version. +- MapKit route calculation generally needs internet access. Calculate/cache the route before switching to a display Wi-Fi network that has no internet. +- The display protocol can vary with firmware. Keep unknown packet families read-only until understood. +- Do not test new protocol behavior while the motorcycle is moving. diff --git a/RideDash.xcodeproj/project.pbxproj b/RideDash.xcodeproj/project.pbxproj new file mode 100644 index 0000000..74434cc --- /dev/null +++ b/RideDash.xcodeproj/project.pbxproj @@ -0,0 +1,514 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 60; + objects = { + +/* Begin PBXBuildFile section */ + 000000000000000000000201 /* RideDashApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000101 /* RideDashApp.swift */; }; + 000000000000000000000202 /* RootView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000102 /* RootView.swift */; }; + 000000000000000000000203 /* DiagnosticsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000103 /* DiagnosticsView.swift */; }; + 000000000000000000000204 /* TripperWiFiManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000104 /* TripperWiFiManager.swift */; }; + 000000000000000000000205 /* LocalNetworkMonitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000105 /* LocalNetworkMonitor.swift */; }; + 000000000000000000000206 /* DashTransport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000106 /* DashTransport.swift */; }; + 000000000000000000000207 /* DiagnosticLog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000107 /* DiagnosticLog.swift */; }; + 000000000000000000000208 /* DashTestProfile.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000108 /* DashTestProfile.swift */; }; + 000000000000000000000209 /* DashSessionCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000110 /* DashSessionCoordinator.swift */; }; + 000000000000000000000210 /* DashProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000111 /* DashProtocol.swift */; }; + 000000000000000000000211 /* ProjectionCore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000112 /* ProjectionCore.swift */; }; + 000000000000000000000212 /* NavigationCore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000113 /* NavigationCore.swift */; }; + 000000000000000000000213 /* ProductFeatures.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000114 /* ProductFeatures.swift */; }; + 000000000000000000000214 /* ShareViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000116 /* ShareViewController.swift */; }; + 000000000000000000000215 /* RideDashShare.appex in Embed App Extensions */ = {isa = PBXBuildFile; fileRef = 000000000000000000000004 /* RideDashShare.appex */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; + 000000000000000000000216 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000118 /* PrivacyInfo.xcprivacy */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 000000000000000000000601 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 000000000000000000000001 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 000000000000000000000005; + remoteInfo = RideDashShare; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 000000000000000000000304 /* Embed App Extensions */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 13; + files = ( + 000000000000000000000215 /* RideDashShare.appex in Embed App Extensions */, + ); + name = "Embed App Extensions"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 000000000000000000000003 /* RideDash.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = RideDash.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 000000000000000000000004 /* RideDashShare.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = RideDashShare.appex; sourceTree = BUILT_PRODUCTS_DIR; }; + 000000000000000000000101 /* RideDashApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RideDashApp.swift; sourceTree = ""; }; + 000000000000000000000102 /* RootView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RootView.swift; sourceTree = ""; }; + 000000000000000000000103 /* DiagnosticsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DiagnosticsView.swift; sourceTree = ""; }; + 000000000000000000000104 /* TripperWiFiManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TripperWiFiManager.swift; sourceTree = ""; }; + 000000000000000000000105 /* LocalNetworkMonitor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LocalNetworkMonitor.swift; sourceTree = ""; }; + 000000000000000000000106 /* DashTransport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DashTransport.swift; sourceTree = ""; }; + 000000000000000000000107 /* DiagnosticLog.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DiagnosticLog.swift; sourceTree = ""; }; + 000000000000000000000108 /* DashTestProfile.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DashTestProfile.swift; sourceTree = ""; }; + 000000000000000000000109 /* RideDash.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = RideDash.entitlements; sourceTree = ""; }; + 000000000000000000000110 /* DashSessionCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DashSessionCoordinator.swift; sourceTree = ""; }; + 000000000000000000000111 /* DashProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DashProtocol.swift; sourceTree = ""; }; + 000000000000000000000112 /* ProjectionCore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProjectionCore.swift; sourceTree = ""; }; + 000000000000000000000113 /* NavigationCore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NavigationCore.swift; sourceTree = ""; }; + 000000000000000000000114 /* ProductFeatures.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProductFeatures.swift; sourceTree = ""; }; + 000000000000000000000115 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 000000000000000000000116 /* ShareViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShareViewController.swift; sourceTree = ""; }; + 000000000000000000000117 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 000000000000000000000118 /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = PrivacyInfo.xcprivacy; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 000000000000000000000302 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 000000000000000000000312 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 000000000000000000000010 = { + isa = PBXGroup; + children = ( + 000000000000000000000011 /* RideDash */, + 000000000000000000000023 /* RideDashShare */, + 000000000000000000000017 /* Products */, + ); + sourceTree = ""; + }; + 000000000000000000000011 /* RideDash */ = { + isa = PBXGroup; + children = ( + 000000000000000000000012 /* App */, + 000000000000000000000013 /* Features */, + 000000000000000000000014 /* DashConnectivity */, + 000000000000000000000020 /* DashProtocol */, + 000000000000000000000021 /* ProjectionCore */, + 000000000000000000000022 /* NavigationCore */, + 000000000000000000000015 /* Diagnostics */, + 000000000000000000000016 /* Models */, + 000000000000000000000115 /* Info.plist */, + 000000000000000000000109 /* RideDash.entitlements */, + 000000000000000000000118 /* PrivacyInfo.xcprivacy */, + ); + path = RideDash; + sourceTree = ""; + }; + 000000000000000000000012 /* App */ = { + isa = PBXGroup; + children = ( + 000000000000000000000101 /* RideDashApp.swift */, + 000000000000000000000102 /* RootView.swift */, + 000000000000000000000110 /* DashSessionCoordinator.swift */, + ); + path = App; + sourceTree = ""; + }; + 000000000000000000000013 /* Features */ = { + isa = PBXGroup; + children = ( + 000000000000000000000018 /* Diagnostics */, + 000000000000000000000019 /* Product */, + ); + path = Features; + sourceTree = ""; + }; + 000000000000000000000018 /* Diagnostics */ = { + isa = PBXGroup; + children = ( + 000000000000000000000103 /* DiagnosticsView.swift */, + ); + path = Diagnostics; + sourceTree = ""; + }; + 000000000000000000000019 /* Product */ = { + isa = PBXGroup; + children = ( + 000000000000000000000114 /* ProductFeatures.swift */, + ); + path = Product; + sourceTree = ""; + }; + 000000000000000000000014 /* DashConnectivity */ = { + isa = PBXGroup; + children = ( + 000000000000000000000104 /* TripperWiFiManager.swift */, + 000000000000000000000105 /* LocalNetworkMonitor.swift */, + 000000000000000000000106 /* DashTransport.swift */, + ); + path = DashConnectivity; + sourceTree = ""; + }; + 000000000000000000000020 /* DashProtocol */ = { + isa = PBXGroup; + children = ( + 000000000000000000000111 /* DashProtocol.swift */, + ); + path = DashProtocol; + sourceTree = ""; + }; + 000000000000000000000021 /* ProjectionCore */ = { + isa = PBXGroup; + children = ( + 000000000000000000000112 /* ProjectionCore.swift */, + ); + path = ProjectionCore; + sourceTree = ""; + }; + 000000000000000000000022 /* NavigationCore */ = { + isa = PBXGroup; + children = ( + 000000000000000000000113 /* NavigationCore.swift */, + ); + path = NavigationCore; + sourceTree = ""; + }; + 000000000000000000000015 /* Diagnostics */ = { + isa = PBXGroup; + children = ( + 000000000000000000000107 /* DiagnosticLog.swift */, + ); + path = Diagnostics; + sourceTree = ""; + }; + 000000000000000000000016 /* Models */ = { + isa = PBXGroup; + children = ( + 000000000000000000000108 /* DashTestProfile.swift */, + ); + path = Models; + sourceTree = ""; + }; + 000000000000000000000023 /* RideDashShare */ = { + isa = PBXGroup; + children = ( + 000000000000000000000116 /* ShareViewController.swift */, + 000000000000000000000117 /* Info.plist */, + ); + path = RideDashShare; + sourceTree = ""; + }; + 000000000000000000000017 /* Products */ = { + isa = PBXGroup; + children = ( + 000000000000000000000003 /* RideDash.app */, + 000000000000000000000004 /* RideDashShare.appex */, + ); + name = Products; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 000000000000000000000002 /* RideDash */ = { + isa = PBXNativeTarget; + buildConfigurationList = 000000000000000000000402 /* Build configuration list for PBXNativeTarget "RideDash" */; + buildPhases = ( + 000000000000000000000301 /* Sources */, + 000000000000000000000302 /* Frameworks */, + 000000000000000000000303 /* Resources */, + 000000000000000000000304 /* Embed App Extensions */, + ); + buildRules = ( + ); + dependencies = ( + 000000000000000000000602 /* PBXTargetDependency */, + ); + name = RideDash; + productName = RideDash; + productReference = 000000000000000000000003 /* RideDash.app */; + productType = "com.apple.product-type.application"; + }; + 000000000000000000000005 /* RideDashShare */ = { + isa = PBXNativeTarget; + buildConfigurationList = 000000000000000000000403 /* Build configuration list for PBXNativeTarget "RideDashShare" */; + buildPhases = ( + 000000000000000000000311 /* Sources */, + 000000000000000000000312 /* Frameworks */, + 000000000000000000000313 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = RideDashShare; + productName = RideDashShare; + productReference = 000000000000000000000004 /* RideDashShare.appex */; + productType = "com.apple.product-type.app-extension"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 000000000000000000000001 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = 1; + LastSwiftUpdateCheck = 1600; + LastUpgradeCheck = 1600; + TargetAttributes = { + 000000000000000000000002 = { + CreatedOnToolsVersion = 16.0; + }; + 000000000000000000000005 = { + CreatedOnToolsVersion = 16.0; + }; + }; + }; + buildConfigurationList = 000000000000000000000401 /* Build configuration list for PBXProject "RideDash" */; + compatibilityVersion = "Xcode 14.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 000000000000000000000010; + productRefGroup = 000000000000000000000017 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 000000000000000000000002 /* RideDash */, + 000000000000000000000005 /* RideDashShare */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 000000000000000000000303 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 000000000000000000000216 /* PrivacyInfo.xcprivacy in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 000000000000000000000313 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 000000000000000000000301 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 000000000000000000000201 /* RideDashApp.swift in Sources */, + 000000000000000000000202 /* RootView.swift in Sources */, + 000000000000000000000203 /* DiagnosticsView.swift in Sources */, + 000000000000000000000204 /* TripperWiFiManager.swift in Sources */, + 000000000000000000000205 /* LocalNetworkMonitor.swift in Sources */, + 000000000000000000000206 /* DashTransport.swift in Sources */, + 000000000000000000000207 /* DiagnosticLog.swift in Sources */, + 000000000000000000000208 /* DashTestProfile.swift in Sources */, + 000000000000000000000209 /* DashSessionCoordinator.swift in Sources */, + 000000000000000000000210 /* DashProtocol.swift in Sources */, + 000000000000000000000211 /* ProjectionCore.swift in Sources */, + 000000000000000000000212 /* NavigationCore.swift in Sources */, + 000000000000000000000213 /* ProductFeatures.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 000000000000000000000311 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 000000000000000000000214 /* ShareViewController.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 000000000000000000000602 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 000000000000000000000005 /* RideDashShare */; + targetProxy = 000000000000000000000601 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 000000000000000000000501 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_OPTIMIZATION_LEVEL = 0; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 000000000000000000000502 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + GCC_C_LANGUAGE_STANDARD = gnu17; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; + SDKROOT = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 000000000000000000000503 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_ENTITLEMENTS = RideDash/RideDash.entitlements; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = ""; + GENERATE_INFOPLIST_FILE = NO; + INFOPLIST_FILE = RideDash/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + MARKETING_VERSION = 0.2.0; + PRODUCT_BUNDLE_IDENTIFIER = dev.dagerott.RideDash; + PRODUCT_NAME = "$(TARGET_NAME)"; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator"; + SUPPORTS_MACCATALYST = NO; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_STRICT_CONCURRENCY = targeted; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 000000000000000000000504 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_ENTITLEMENTS = RideDash/RideDash.entitlements; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = ""; + GENERATE_INFOPLIST_FILE = NO; + INFOPLIST_FILE = RideDash/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + MARKETING_VERSION = 0.2.0; + PRODUCT_BUNDLE_IDENTIFIER = dev.dagerott.RideDash; + PRODUCT_NAME = "$(TARGET_NAME)"; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator"; + SUPPORTS_MACCATALYST = NO; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_STRICT_CONCURRENCY = targeted; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Release; + }; + 000000000000000000000505 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + APPLICATION_EXTENSION_API_ONLY = YES; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = ""; + GENERATE_INFOPLIST_FILE = NO; + INFOPLIST_FILE = RideDashShare/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks"; + MARKETING_VERSION = 0.2.0; + PRODUCT_BUNDLE_IDENTIFIER = dev.dagerott.RideDash.ShareExtension; + PRODUCT_NAME = "$(TARGET_NAME)"; + SKIP_INSTALL = YES; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 000000000000000000000506 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + APPLICATION_EXTENSION_API_ONLY = YES; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = ""; + GENERATE_INFOPLIST_FILE = NO; + INFOPLIST_FILE = RideDashShare/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks"; + MARKETING_VERSION = 0.2.0; + PRODUCT_BUNDLE_IDENTIFIER = dev.dagerott.RideDash.ShareExtension; + PRODUCT_NAME = "$(TARGET_NAME)"; + SKIP_INSTALL = YES; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 000000000000000000000401 /* Build configuration list for PBXProject "RideDash" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 000000000000000000000501 /* Debug */, + 000000000000000000000502 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 000000000000000000000402 /* Build configuration list for PBXNativeTarget "RideDash" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 000000000000000000000503 /* Debug */, + 000000000000000000000504 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 000000000000000000000403 /* Build configuration list for PBXNativeTarget "RideDashShare" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 000000000000000000000505 /* Debug */, + 000000000000000000000506 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 000000000000000000000001 /* Project object */; +} diff --git a/RideDash/App/DashSessionCoordinator.swift b/RideDash/App/DashSessionCoordinator.swift new file mode 100644 index 0000000..7fe4fcb --- /dev/null +++ b/RideDash/App/DashSessionCoordinator.swift @@ -0,0 +1,590 @@ +import Combine +import Foundation + +@MainActor +final class DashSessionCoordinator: ObservableObject { + enum State: Equatable { + case disconnected + case startingTransport + case requestingAuthentication + case awaitingPublicKey + case sendingSessionKey + case authenticated + case enteringNavigation + case navigationReady + case projecting + case stopping + case failed(String) + + var label: String { + switch self { + case .disconnected: return "Disconnected" + case .startingTransport: return "Starting transport" + case .requestingAuthentication: return "Requesting authentication" + case .awaitingPublicKey: return "Waiting for dash public key" + case .sendingSessionKey: return "Sending encrypted session key" + case .authenticated: return "Authenticated" + case .enteringNavigation: return "Entering navigation" + case .navigationReady: return "Navigation ready" + case .projecting: return "Projecting" + case .stopping: return "Stopping" + case .failed(let message): return "Failed: \(message)" + } + } + } + + @Published private(set) var state: State = .disconnected + @Published private(set) var lastButton: DashButton? + @Published private(set) var authenticatedSession: DashAuthenticatedSession? + @Published private(set) var reconnectAttempt = 0 + @Published private(set) var lastReconnectReason: String? + @Published var automaticReconnectEnabled = true + @Published var routeTitle = "Navigation" + + let transport: DashTransport + let log: DiagnosticLog + + var onButton: ((DashButton) -> Void)? + var onAuthenticated: (() -> Void)? + + private var profile = DashProtocolProfile.publicReference + private var ssid = "" + private var hostname = "iPhone" + private var sequence: UInt8 = 0 + private var modulus: Data? + private var exponent: Data? + private var pendingAESKey: Data? + private var authConfirmed = false + private var navEntered = false + private var shouldMaintainConnection = false + private var restoreNavigationAfterReconnect = false + private var authRejectCount = 0 + private var consecutiveSendFailures = 0 + + private var lastAcceptedButton: DashButton? + private var lastAcceptedButtonAt = Date.distantPast + private let buttonDebounceInterval: TimeInterval = 0.12 + + private var authTimeoutTask: Task? + private var projectionHeartbeatTask: Task? + private var routeHeartbeatTask: Task? + private var navInfoHeartbeatTask: Task? + private var statusHeartbeatTask: Task? + private var reconnectTask: Task? + private var transportStateCancellable: AnyCancellable? + + private let maximumReconnectAttempts = 5 + + init(transport: DashTransport = DashTransport(), log: DiagnosticLog = DiagnosticLog()) { + self.transport = transport + self.log = log + + transport.onDatagram = { [weak self] datagram in + Task { @MainActor in self?.handle(datagram) } + } + + transportStateCancellable = transport.$state + .dropFirst() + .sink { [weak self] transportState in + guard let self else { return } + if case .failed(let message) = transportState { + self.scheduleReconnect(reason: "Transport failed: \(message)") + } + } + } + + func connect( + ssid: String, + hostname: String, + profile: DashProtocolProfile = .publicReference, + authTimeout: Duration = .seconds(8) + ) async { + reconnectTask?.cancel() + reconnectTask = nil + reconnectAttempt = 0 + lastReconnectReason = nil + shouldMaintainConnection = true + restoreNavigationAfterReconnect = false + + self.ssid = ssid.trimmingCharacters(in: .whitespacesAndNewlines) + self.hostname = hostname.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? "iPhone" : hostname + self.profile = profile + + guard !self.ssid.isEmpty else { + shouldMaintainConnection = false + state = .failed("Display SSID is required") + return + } + + await establishConnection(authTimeout: authTimeout) + } + + func retryLastConnection() async { + guard !ssid.isEmpty else { return } + reconnectTask?.cancel() + reconnectTask = nil + reconnectAttempt = 0 + shouldMaintainConnection = true + await establishConnection(authTimeout: .seconds(8)) + } + + func enterNavigation(title: String? = nil) async throws { + guard authConfirmed, authenticatedSession != nil else { + throw DashSessionError.notAuthenticated + } + if let title, !title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + routeTitle = title + } + + cancelNavigationKeepAlives() + state = .enteringNavigation + + try await sendHex(K1GCodec.navContextHex) + try await sendHex(K1GCodec.emptyListsHex) + + for index in 0..<4 { + try await sendRaw(K1GCodec.routeCard(title: routeTitle, projectionOn: index == 3)) + if index < 3 { try await Task.sleep(for: .milliseconds(350)) } + } + + try await sendHex(K1GCodec.projectionFrameHex) + try await sendHex(K1GCodec.projectionOnHex) + try await sendHex(K1GCodec.startNavigationHex) + try await sendRaw(K1GCodec.routeCard(title: routeTitle, projectionOn: true)) + + navEntered = true + state = .navigationReady + startRouteHeartbeat() + startNavInfoHeartbeat() + startStatusHeartbeat() + log.append("Navigation control plane entered; route/nav/status keep-alives running", category: "session") + } + + func beginProjectionHeartbeat() { + guard navEntered, authConfirmed else { return } + projectionHeartbeatTask?.cancel() + let fps = max(1, profile.fps) + + projectionHeartbeatTask = Task { [weak self] in + while !Task.isCancelled { + guard let self else { return } + do { + try await self.sendHex(K1GCodec.projectionFrameHex) + } catch { + self.log.append(error.localizedDescription, category: "projection", level: .error) + } + try? await Task.sleep(for: .seconds(1.0 / Double(fps))) + } + } + state = .projecting + } + + func stopProjection() async { + projectionHeartbeatTask?.cancel() + cancelNavigationKeepAlives() + projectionHeartbeatTask = nil + restoreNavigationAfterReconnect = false + + guard navEntered else { return } + state = .stopping + do { + try await sendHex(K1GCodec.projectionStopHex) + try await sendHex(K1GCodec.projectionOffHex) + navEntered = false + state = authConfirmed ? .authenticated : .disconnected + log.append("Projection-off sequence sent", category: "projection") + } catch { + navEntered = false + state = .failed(error.localizedDescription) + log.append(error.localizedDescription, category: "projection", level: .error) + } + } + + func disconnect() { + shouldMaintainConnection = false + reconnectTask?.cancel() + reconnectTask = nil + reconnectAttempt = 0 + lastReconnectReason = nil + restoreNavigationAfterReconnect = false + resetSessionState(stopTransport: true) + state = .disconnected + } + + // MARK: - Connection / recovery + + private func establishConnection(authTimeout: Duration) async { + resetSessionState(stopTransport: true) + + do { + state = .startingTransport + try transport.start(profile: profile) + log.append("Control/input/video UDP transport requested", category: "session") + try await waitForTransportReady(timeout: .seconds(3)) + + state = .requestingAuthentication + try await sendInitialBurst() + state = .awaitingPublicKey + log.append("Initial K1G burst sent; awaiting RSA public key", category: "auth") + startAuthTimeout(authTimeout) + } catch { + state = .failed(error.localizedDescription) + log.append(error.localizedDescription, category: "session", level: .error) + scheduleReconnect(reason: error.localizedDescription) + } + } + + private func scheduleReconnect(reason: String) { + guard shouldMaintainConnection, + automaticReconnectEnabled, + reconnectTask == nil, + reconnectAttempt < maximumReconnectAttempts else { return } + + if navEntered || state == .navigationReady || state == .projecting { + restoreNavigationAfterReconnect = true + } + + reconnectAttempt += 1 + lastReconnectReason = reason + let delaySeconds = min(16, 1 << max(0, reconnectAttempt - 1)) + log.append( + "Reconnect \(reconnectAttempt)/\(maximumReconnectAttempts) scheduled in \(delaySeconds)s: \(reason)", + category: "reconnect", + level: .warning + ) + + reconnectTask = Task { [weak self] in + try? await Task.sleep(for: .seconds(delaySeconds)) + guard !Task.isCancelled, let self, self.shouldMaintainConnection else { return } + self.reconnectTask = nil + await self.establishConnection(authTimeout: .seconds(8)) + } + } + + private func resetSessionState(stopTransport: Bool) { + authTimeoutTask?.cancel() + projectionHeartbeatTask?.cancel() + cancelNavigationKeepAlives() + authTimeoutTask = nil + projectionHeartbeatTask = nil + + if stopTransport { transport.stop() } + sequence = 0 + modulus = nil + exponent = nil + pendingAESKey = nil + authenticatedSession = nil + authConfirmed = false + navEntered = false + authRejectCount = 0 + consecutiveSendFailures = 0 + lastButton = nil + lastAcceptedButton = nil + lastAcceptedButtonAt = .distantPast + } + + // MARK: - Receive path + + private func handle(_ datagram: DashDatagram) { + guard datagram.direction == .inbound else { return } + log.append( + "RX \(datagram.data.count)B \(HexCodec.string(datagram.data, maxBytes: 24))", + category: "packet" + ) + + for event in DashEventDecoder.events(from: datagram.data) { + switch event { + case .rsaModulus(let data): + modulus = data + log.append("RSA modulus received (\(data.count)B)", category: "auth") + attemptSessionKeyIfReady() + + case .rsaExponent(let data): + exponent = data + log.append("RSA exponent received: \(HexCodec.string(data))", category: "auth") + attemptSessionKeyIfReady() + + case .authAccepted: + authTimeoutTask?.cancel() + guard let key = pendingAESKey else { + state = .failed("Dash accepted auth but no local session key is available") + scheduleReconnect(reason: "Auth accepted without local session material") + return + } + authenticatedSession = DashAuthenticatedSession(aesKey: key) + pendingAESKey = nil + authConfirmed = true + authRejectCount = 0 + reconnectAttempt = 0 + lastReconnectReason = nil + state = .authenticated + log.append("Dash authentication accepted", category: "auth") + onAuthenticated?() + + if restoreNavigationAfterReconnect { + restoreNavigationAfterReconnect = false + Task { [weak self] in + guard let self else { return } + do { + try await self.enterNavigation(title: self.routeTitle) + self.log.append("Navigation mode restored after reconnect", category: "reconnect") + } catch { + self.log.append(error.localizedDescription, category: "reconnect", level: .error) + } + } + } + + case .authRejected(let status): + pendingAESKey = nil + authenticatedSession = nil + authConfirmed = false + modulus = nil + exponent = nil + authRejectCount += 1 + log.append( + "Dash authentication rejected status=0x\(String(format: "%02X", status)); attempt \(authRejectCount)/3", + category: "auth", + level: .error + ) + + guard authRejectCount < 3 else { + state = .failed("Authentication rejected repeatedly") + scheduleReconnect(reason: "Authentication rejected three times") + return + } + + state = .requestingAuthentication + Task { [weak self] in + guard let self else { return } + try? await self.sendHex(K1GCodec.requestAuthHex) + self.state = .awaitingPublicKey + } + + case .button(let button): + let now = Date() + let isRepeat = lastAcceptedButton == button && now.timeIntervalSince(lastAcceptedButtonAt) < buttonDebounceInterval + + lastButton = button + if !isRepeat { + lastAcceptedButton = button + lastAcceptedButtonAt = now + log.append("Dash input: \(String(describing: button))", category: "input") + onButton?(button) + } else { + log.append("Debounced repeated dash input: \(String(describing: button))", category: "input") + } + + // Ack even debounced repeats so the embedded sender never waits for an app response. + if profile.respondToInput { + Task { [weak self] in + guard let self, + let ack = try? K1GCodec.buttonAck(button.rawValue) else { return } + try? await self.sendRaw(ack) + } + } + + case .segment(let segment): + if segment.type != 0x05 && segment.type != 0x06 { + log.append("Unknown segment \(segment.hex.prefix(80))", category: "protocol") + } + } + } + } + + private func attemptSessionKeyIfReady() { + guard pendingAESKey == nil, + !authConfirmed, + let modulus, + let exponent, + !ssid.isEmpty else { return } + + state = .sendingSessionKey + Task { [weak self] in + guard let self else { return } + do { + let aesKey = try DashAuthenticator.randomAES256Key() + let ciphertext = try DashAuthenticator.encryptedSessionPayload( + ssid: self.ssid, + modulus: modulus, + exponent: exponent, + aesKey: aesKey + ) + try await self.sendRaw(K1GCodec.buildSessionKeyPacket(ciphertext: ciphertext)) + self.pendingAESKey = aesKey + self.state = .awaitingPublicKey + self.log.append("Encrypted AES session key sent; awaiting auth status", category: "auth") + } catch { + self.pendingAESKey = nil + self.state = .failed(error.localizedDescription) + self.log.append(error.localizedDescription, category: "auth", level: .error) + self.scheduleReconnect(reason: error.localizedDescription) + } + } + } + + // MARK: - Send path + + private func sendInitialBurst() async throws { + for entry in K1GCodec.initialBurst { + let packet = try entry.map { try HexCodec.data(from: $0) } ?? K1GCodec.hostnameAnnounce(hostname) + try await sendRaw(packet) + try await Task.sleep(for: .milliseconds(20)) + } + } + + private func sendHex(_ hex: String) async throws { + try await sendRaw(HexCodec.data(from: hex)) + } + + private func sendRaw(_ packet: Data) async throws { + let patched = try K1GCodec.patchSequence(packet, sequence: sequence) + sequence &+= 1 + do { + try await transport.sendControl(patched) + consecutiveSendFailures = 0 + } catch { + consecutiveSendFailures += 1 + if consecutiveSendFailures >= 3 { + scheduleReconnect(reason: "Repeated UDP send failures") + } + throw error + } + } + + // MARK: - Navigation keep-alives + + private func startRouteHeartbeat() { + routeHeartbeatTask?.cancel() + routeHeartbeatTask = Task { [weak self] in + while !Task.isCancelled { + guard let self else { return } + do { + try await self.sendRaw( + K1GCodec.routeCard(title: self.routeTitle, projectionOn: true) + ) + } catch { + self.log.append(error.localizedDescription, category: "heartbeat", level: .error) + } + try? await Task.sleep(for: .seconds(1)) + } + } + } + + /// Public interoperability captures show the stock app refreshing an active-navigation + /// TLV bundle at ~1 Hz. The custom H.264 renderer contains the real MapKit instruction; + /// this native-dash packet intentionally uses a conservative generic continue/500 m value + /// until the target firmware's complete maneuver enum is validated on owned hardware. + private func startNavInfoHeartbeat() { + navInfoHeartbeatTask?.cancel() + navInfoHeartbeatTask = Task { [weak self] in + while !Task.isCancelled { + guard let self else { return } + do { + try await self.sendRaw(try self.buildActiveNavInfoPacket()) + } catch { + self.log.append(error.localizedDescription, category: "nav-info", level: .error) + } + try? await Task.sleep(for: .seconds(1)) + } + } + } + + /// Mirrors the public reference's foreground-service cadence: one 0x0049-shaped + /// status heartbeat plus a 0x0030 metadata packet each second. Values are benign + /// phone/display metadata placeholders and never touch motorcycle control systems. + private func startStatusHeartbeat() { + statusHeartbeatTask?.cancel() + statusHeartbeatTask = Task { [weak self] in + while !Task.isCancelled { + guard let self else { return } + do { + try await self.sendHex(Self.statusHeartbeat0049Hex) + try await self.sendHex(Self.metadataHeartbeat0030Hex) + } catch { + self.log.append(error.localizedDescription, category: "status-tick", level: .error) + } + try? await Task.sleep(for: .seconds(1)) + } + } + } + + private func cancelNavigationKeepAlives() { + routeHeartbeatTask?.cancel() + navInfoHeartbeatTask?.cancel() + statusHeartbeatTask?.cancel() + routeHeartbeatTask = nil + navInfoHeartbeatTask = nil + statusHeartbeatTask = nil + } + + private func buildActiveNavInfoPacket() throws -> Data { + let maneuver = "050200010B" // public reference: generic continue + let primaryDistance = "0504000201F4" // 500 m + let primaryUnit = "0506000130" // unit code decimal 30 => byte 0x30 (metres) + let totalDistance = "0509000201F4" // 500 m + let totalUnit = "0546000130" // metres + let decimalSeparator = "050A000155" // dot / normal integer formatting + let projectionOn = "0605000155" + let decimalFormattingOff = "060D0001AA" + + let payload = maneuver + primaryDistance + primaryUnit + totalDistance + totalUnit + + decimalSeparator + projectionOn + decimalFormattingOff + let segmentCount = 9 // 8 nav TLVs + K1G container segment + let k1gHeader = "00000000020100054B31472000" + let inner = String(format: "%04X", segmentCount) + k1gHeader + payload + let innerBytes = inner.count / 2 + let full = String(format: "%04X", innerBytes + 2) + inner + return try HexCodec.data(from: full) + } + + private static let statusHeartbeat0049Hex = + "0049000B00000000020100054B3147200006080001050610000139060300015506040001A2060F0001AA" + + "0601000101054C000113052D00020000051B0001190521000132054D000132" + + private static let metadataHeartbeat0030Hex = + "0030000600000000020100054B3147200006080001FF054C000117052D00020000051B0001160521000132054D000132" + + private func startAuthTimeout(_ timeout: Duration) { + authTimeoutTask?.cancel() + authTimeoutTask = Task { [weak self] in + try? await Task.sleep(for: timeout) + guard !Task.isCancelled, let self, !self.authConfirmed else { return } + self.state = .failed("Authentication timed out") + self.log.append("Authentication timeout", category: "auth", level: .error) + self.scheduleReconnect(reason: "Authentication timed out") + } + } + + private func waitForTransportReady(timeout: Duration) async throws { + let clock = ContinuousClock() + let deadline = clock.now.advanced(by: timeout) + while clock.now < deadline { + switch transport.state { + case .ready: + return + case .failed(let message): + throw DashSessionError.transportFailed(message) + default: + try await Task.sleep(for: .milliseconds(50)) + } + } + throw DashSessionError.transportTimedOut + } +} + +enum DashSessionError: LocalizedError { + case notAuthenticated + case transportTimedOut + case transportFailed(String) + + var errorDescription: String? { + switch self { + case .notAuthenticated: + return "Authenticate with the display before entering navigation mode." + case .transportTimedOut: + return "UDP transport did not become ready before the timeout." + case .transportFailed(let message): + return "UDP transport failed: \(message)" + } + } +} diff --git a/RideDash/App/RideDashApp.swift b/RideDash/App/RideDashApp.swift new file mode 100644 index 0000000..6934678 --- /dev/null +++ b/RideDash/App/RideDashApp.swift @@ -0,0 +1,18 @@ +import SwiftData +import SwiftUI + +@main +struct RideDashApp: App { + var body: some Scene { + WindowGroup { + RootView() + } + .modelContainer(for: [ + Vehicle.self, + Expense.self, + FuelLog.self, + MaintenanceRecord.self, + RideRecord.self + ]) + } +} diff --git a/RideDash/App/RootView.swift b/RideDash/App/RootView.swift new file mode 100644 index 0000000..53e0b7a --- /dev/null +++ b/RideDash/App/RootView.swift @@ -0,0 +1,107 @@ +import CoreLocation +import SwiftData +import SwiftUI + +struct RootView: View { + enum Tab: Hashable { case home, navigation, garage, expenses, rides, settings } + + @Environment(\.modelContext) private var modelContext + @StateObject private var session = DashSessionCoordinator() + @StateObject private var navigation = NavigationViewModel() + @StateObject private var streamer = ProjectionStreamer() + @State private var selectedTab: Tab = .home + @State private var activeRide: RideRecord? + @State private var previousRideLocation: CLLocation? + + var body: some View { + TabView(selection: $selectedTab) { + NavigationStack { DashboardView() } + .tabItem { Label("Home", systemImage: "motorcycle") } + .tag(Tab.home) + + NavigationStack { RideNavigationView() } + .tabItem { Label("Navigate", systemImage: "map.fill") } + .tag(Tab.navigation) + + NavigationStack { GarageView() } + .tabItem { Label("Garage", systemImage: "wrench.and.screwdriver.fill") } + .tag(Tab.garage) + + NavigationStack { ExpensesView() } + .tabItem { Label("Expenses", systemImage: "indianrupeesign.circle.fill") } + .tag(Tab.expenses) + + NavigationStack { RidesView() } + .tabItem { Label("Rides", systemImage: "road.lanes") } + .tag(Tab.rides) + + NavigationStack { SettingsView() } + .tabItem { Label("Settings", systemImage: "gearshape.fill") } + .tag(Tab.settings) + } + .tint(.orange) + .environmentObject(session) + .environmentObject(navigation) + .environmentObject(streamer) + .onAppear { + session.onButton = { [weak navigation] button in + navigation?.handleDashButton(button) + } + navigation.startLocation() + } + .onChange(of: session.state) { oldState, newState in + handleSessionTransition(from: oldState, to: newState) + } + .onReceive(navigation.locationService.$location.compactMap { $0 }) { location in + recordRideLocation(location) + } + .onOpenURL { url in + navigation.importURL(url) + selectedTab = .navigation + } + } + + private func handleSessionTransition(from oldState: DashSessionCoordinator.State, to newState: DashSessionCoordinator.State) { + if newState == .projecting, activeRide == nil { + let ride = RideRecord( + startedAt: .now, + destination: navigation.destination?.name ?? "", + distanceKm: 0, + notes: "Recorded automatically during display projection" + ) + modelContext.insert(ride) + activeRide = ride + previousRideLocation = navigation.locationService.location + session.log.append("Automatic ride recording started", category: "ride") + } + + if oldState == .projecting, newState != .projecting, let ride = activeRide { + ride.endedAt = .now + activeRide = nil + previousRideLocation = nil + session.log.append( + "Automatic ride recording stopped at \(String(format: "%.2f", ride.distanceKm)) km", + category: "ride" + ) + } + } + + private func recordRideLocation(_ location: CLLocation) { + guard let ride = activeRide, + location.horizontalAccuracy >= 0, + location.horizontalAccuracy <= 50 else { return } + + defer { previousRideLocation = location } + guard let previousRideLocation else { return } + + let delta = location.distance(from: previousRideLocation) + // Ignore GPS jitter and implausible one-sample jumps. Real route deviation is handled separately. + guard delta >= 2, delta <= 500 else { return } + ride.distanceKm += delta / 1_000 + } +} + +#Preview { + RootView() + .modelContainer(for: [Vehicle.self, Expense.self, FuelLog.self, MaintenanceRecord.self, RideRecord.self], inMemory: true) +} diff --git a/RideDash/DashConnectivity/DashTransport.swift b/RideDash/DashConnectivity/DashTransport.swift new file mode 100644 index 0000000..9f77539 --- /dev/null +++ b/RideDash/DashConnectivity/DashTransport.swift @@ -0,0 +1,283 @@ +import Combine +import Foundation +import Network + +struct DashDatagram: Identifiable, Sendable { + enum Direction: String, Sendable { case inbound, outbound } + enum Channel: String, Sendable { case control, input, video } + + let id = UUID() + let timestamp: Date + let direction: Direction + let channel: Channel + let endpoint: String + let data: Data +} + +@MainActor +final class DashTransport: ObservableObject { + enum State: Equatable { + case stopped + case preparing + case ready + case waiting(String) + case failed(String) + + var description: String { + switch self { + case .stopped: return "Stopped" + case .preparing: return "Preparing" + case .ready: return "UDP transport ready" + case .waiting(let reason): return "Waiting: \(reason)" + case .failed(let error): return "Failed: \(error)" + } + } + } + + @Published private(set) var state: State = .stopped + @Published private(set) var receivedPackets = 0 + @Published private(set) var sentPackets = 0 + @Published private(set) var lastError: String? + + var onDatagram: (@Sendable (DashDatagram) -> Void)? + + private let queue = DispatchQueue(label: "dev.dagerott.RideDash.dash-transport") + private var controlConnection: NWConnection? + private var videoConnection: NWConnection? + private var inputListener: NWListener? + private var inputConnections: [ObjectIdentifier: NWConnection] = [:] + private var controlReady = false + private var listenerReady = false + + func start(profile: DashProtocolProfile) throws { + stop() + guard !profile.host.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, + !profile.broadcastHost.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + throw DashTransportError.invalidHost + } + guard let controlPort = NWEndpoint.Port(rawValue: profile.controlPort), + let videoPort = NWEndpoint.Port(rawValue: profile.videoPort), + let inputPort = NWEndpoint.Port(rawValue: profile.inputPort) else { + throw DashTransportError.invalidPort + } + + state = .preparing + lastError = nil + controlReady = false + listenerReady = false + + // The public reference binds the control socket to UDP/2000 before broadcasting. + // Preserve that source-port behavior: some embedded firmwares use it as part of + // their fixed control-channel routing rather than replying to an arbitrary port. + let controlParameters = NWParameters.udp + controlParameters.allowLocalEndpointReuse = true + controlParameters.requiredLocalEndpoint = .hostPort( + host: NWEndpoint.Host("0.0.0.0"), + port: controlPort + ) + + let control = NWConnection( + host: NWEndpoint.Host(profile.broadcastHost), + port: controlPort, + using: controlParameters + ) + controlConnection = control + control.stateUpdateHandler = { [weak self] newState in + Task { @MainActor in self?.handleControlState(newState) } + } + control.start(queue: queue) + + let video = NWConnection( + host: NWEndpoint.Host(profile.host), + port: videoPort, + using: .udp + ) + videoConnection = video + video.stateUpdateHandler = { [weak self] newState in + guard case .failed(let error) = newState else { return } + Task { @MainActor in + self?.lastError = "Video UDP: \(error.localizedDescription)" + } + } + video.start(queue: queue) + + let parameters = NWParameters.udp + parameters.allowLocalEndpointReuse = true + let listener = try NWListener(using: parameters, on: inputPort) + inputListener = listener + listener.stateUpdateHandler = { [weak self] newState in + Task { @MainActor in self?.handleListenerState(newState) } + } + listener.newConnectionHandler = { [weak self] connection in + Task { @MainActor in self?.acceptInput(connection) } + } + listener.start(queue: queue) + } + + /// Lightweight diagnostic mode retained for the Diagnostics screen. + func start(host: String, port: UInt16) throws { + var profile = DashProtocolProfile.publicReference + profile.host = host + profile.broadcastHost = host + profile.controlPort = port + profile.videoPort = port + try start(profile: profile) + } + + func stop() { + controlConnection?.cancel() + videoConnection?.cancel() + inputListener?.cancel() + inputConnections.values.forEach { $0.cancel() } + controlConnection = nil + videoConnection = nil + inputListener = nil + inputConnections.removeAll() + controlReady = false + listenerReady = false + state = .stopped + } + + func sendControl(_ data: Data) async throws { + guard let connection = controlConnection else { throw DashTransportError.notStarted } + try await send(data, on: connection, channel: .control) + } + + func sendVideo(_ data: Data) async throws { + guard let connection = videoConnection else { throw DashTransportError.notStarted } + try await send(data, on: connection, channel: .video) + } + + private func send(_ data: Data, on connection: NWConnection, channel: DashDatagram.Channel) async throws { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + connection.send(content: data, completion: .contentProcessed { [weak self] error in + if let error { + continuation.resume(throwing: error) + return + } + Task { @MainActor in + guard let self else { return } + self.sentPackets += 1 + self.emit(.init( + timestamp: .now, + direction: .outbound, + channel: channel, + endpoint: self.endpointDescription(connection.endpoint), + data: data + )) + } + continuation.resume() + }) + } + } + + private func handleControlState(_ newState: NWConnection.State) { + switch newState { + case .setup, .preparing: + controlReady = false + state = .preparing + case .ready: + controlReady = true + updateReadyState() + case .waiting(let error): + controlReady = false + state = .waiting("Control: \(error.localizedDescription)") + case .failed(let error): + controlReady = false + lastError = error.localizedDescription + state = .failed("Control: \(error.localizedDescription)") + case .cancelled: + controlReady = false + @unknown default: + state = .waiting("Unknown control transport state") + } + } + + private func handleListenerState(_ newState: NWListener.State) { + switch newState { + case .setup: + listenerReady = false + case .waiting(let error): + listenerReady = false + state = .waiting("Input listener: \(error.localizedDescription)") + case .ready: + listenerReady = true + updateReadyState() + case .failed(let error): + listenerReady = false + lastError = error.localizedDescription + state = .failed("Input listener: \(error.localizedDescription)") + case .cancelled: + listenerReady = false + @unknown default: + break + } + } + + private func updateReadyState() { + if controlReady && listenerReady { state = .ready } + } + + private func acceptInput(_ connection: NWConnection) { + let id = ObjectIdentifier(connection) + inputConnections[id] = connection + connection.stateUpdateHandler = { [weak self, weak connection] state in + Task { @MainActor in + guard let self, let connection else { return } + switch state { + case .ready: + self.receiveNext(on: connection) + case .failed, .cancelled: + self.inputConnections.removeValue(forKey: id) + default: + break + } + } + } + connection.start(queue: queue) + } + + private func receiveNext(on connection: NWConnection) { + connection.receiveMessage { [weak self, weak connection] data, _, _, error in + Task { @MainActor in + guard let self, let connection else { return } + if let data, !data.isEmpty { + self.receivedPackets += 1 + self.emit(.init( + timestamp: .now, + direction: .inbound, + channel: .input, + endpoint: self.endpointDescription(connection.endpoint), + data: data + )) + } + if error == nil { self.receiveNext(on: connection) } + } + } + } + + private func emit(_ datagram: DashDatagram) { + onDatagram?(datagram) + } + + private func endpointDescription(_ endpoint: NWEndpoint) -> String { + switch endpoint { + case .hostPort(let host, let port): return "\(host):\(port)" + default: return String(describing: endpoint) + } + } +} + +enum DashTransportError: LocalizedError { + case invalidHost + case invalidPort + case notStarted + + var errorDescription: String? { + switch self { + case .invalidHost: return "Dash host/broadcast host is empty." + case .invalidPort: return "A configured UDP port is invalid." + case .notStarted: return "Dash UDP transport has not been started." + } + } +} diff --git a/RideDash/DashConnectivity/LocalNetworkMonitor.swift b/RideDash/DashConnectivity/LocalNetworkMonitor.swift new file mode 100644 index 0000000..950cf1d --- /dev/null +++ b/RideDash/DashConnectivity/LocalNetworkMonitor.swift @@ -0,0 +1,56 @@ +import Combine +import Foundation +import Network + +final class LocalNetworkMonitor: ObservableObject { + @Published private(set) var statusText = "Not started" + @Published private(set) var interfaceNames: [String] = [] + @Published private(set) var usesWiFi = false + + private let monitor = NWPathMonitor() + private let queue = DispatchQueue(label: "dev.dagerott.RideDash.path-monitor") + private var started = false + + func start() { + guard !started else { return } + started = true + + monitor.pathUpdateHandler = { [weak self] path in + let statusText: String + switch path.status { + case .satisfied: statusText = "Satisfied" + case .unsatisfied: statusText = "Unsatisfied" + case .requiresConnection: statusText = "Requires connection" + @unknown default: statusText = "Unknown" + } + + let interfaces = path.availableInterfaces.map { interface in + "\(Self.name(for: interface.type)): \(interface.name)" + } + let usesWiFi = path.usesInterfaceType(.wifi) + + DispatchQueue.main.async { + self?.statusText = statusText + self?.interfaceNames = interfaces + self?.usesWiFi = usesWiFi + } + } + + monitor.start(queue: queue) + } + + func stop() { + monitor.cancel() + } + + private static func name(for type: NWInterface.InterfaceType) -> String { + switch type { + case .wifi: return "Wi-Fi" + case .cellular: return "Cellular" + case .wiredEthernet: return "Ethernet" + case .loopback: return "Loopback" + case .other: return "Other" + @unknown default: return "Unknown" + } + } +} diff --git a/RideDash/DashConnectivity/TripperWiFiManager.swift b/RideDash/DashConnectivity/TripperWiFiManager.swift new file mode 100644 index 0000000..4d3e41c --- /dev/null +++ b/RideDash/DashConnectivity/TripperWiFiManager.swift @@ -0,0 +1,93 @@ +import Combine +import Foundation +import NetworkExtension + +protocol DashWiFiJoining { + func join(ssid: String, passphrase: String) async throws + func removeConfiguration(forSSID ssid: String) async +} + +@MainActor +final class TripperWiFiManager: ObservableObject, DashWiFiJoining { + enum Status: Equatable { + case idle + case requesting + case joined + case failed(String) + + var description: String { + switch self { + case .idle: return "Idle" + case .requesting: return "Requesting Wi-Fi join…" + case .joined: return "Join request completed" + case .failed(let message): return "Failed: \(message)" + } + } + } + + @Published private(set) var status: Status = .idle + + func join(ssid: String, passphrase: String) async throws { + let trimmedSSID = ssid.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmedSSID.isEmpty else { + throw WiFiJoinError.missingSSID + } + + status = .requesting + + let configuration: NEHotspotConfiguration + if passphrase.isEmpty { + configuration = NEHotspotConfiguration(ssid: trimmedSSID) + } else { + configuration = NEHotspotConfiguration( + ssid: trimmedSSID, + passphrase: passphrase, + isWEP: false + ) + } + + // Persist the app-managed accessory-network configuration instead of using + // joinOnce. Projection sessions can last for hours and joinOnce is intentionally + // short-lived. The user can remove this configuration explicitly from RideDash. + configuration.joinOnce = false + + do { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + NEHotspotConfigurationManager.shared.apply(configuration) { error in + if let nsError = error as NSError?, + nsError.domain == NEHotspotConfigurationErrorDomain, + nsError.code == NEHotspotConfigurationError.alreadyAssociated.rawValue { + // Already being on the requested accessory network is success for our flow. + continuation.resume(returning: ()) + } else if let error { + continuation.resume(throwing: error) + } else { + continuation.resume(returning: ()) + } + } + } + status = .joined + } catch { + status = .failed(error.localizedDescription) + throw error + } + } + + func removeConfiguration(forSSID ssid: String) async { + let trimmedSSID = ssid.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmedSSID.isEmpty else { return } + NEHotspotConfigurationManager.shared.removeConfiguration(forSSID: trimmedSSID) + status = .idle + } +} + +enum WiFiJoinError: LocalizedError { + case missingSSID + + var errorDescription: String? { + switch self { + case .missingSSID: + return "Enter the dash Wi-Fi SSID first." + } + } +} diff --git a/RideDash/DashProtocol/DashProtocol.swift b/RideDash/DashProtocol/DashProtocol.swift new file mode 100644 index 0000000..16a652e --- /dev/null +++ b/RideDash/DashProtocol/DashProtocol.swift @@ -0,0 +1,332 @@ +import Foundation +import Security + +// MARK: - Protocol profile + +struct DashProtocolProfile: Codable, Hashable, Sendable { + var host: String = "192.168.1.1" + var broadcastHost: String = "192.168.1.255" + var controlPort: UInt16 = 2000 + var inputPort: UInt16 = 2002 + var videoPort: UInt16 = 5000 + var renderWidth: Int = 526 + var renderHeight: Int = 300 + var fps: Int = 4 + var bitrateKbps: Int = 250 + var respondToInput: Bool = true + + static let publicReference = DashProtocolProfile() +} + +// MARK: - Hex helpers + +enum HexCodec { + static func data(from string: String) throws -> Data { + let clean = string + .replacingOccurrences(of: " ", with: "") + .replacingOccurrences(of: "\n", with: "") + .replacingOccurrences(of: "\t", with: "") + guard clean.count.isMultiple(of: 2) else { throw DashProtocolError.invalidHex } + + var output = Data(capacity: clean.count / 2) + var index = clean.startIndex + while index < clean.endIndex { + let next = clean.index(index, offsetBy: 2) + guard let byte = UInt8(clean[index.. String { + let bytes = maxBytes.map { data.prefix($0) } ?? data[...] + return bytes.map { String(format: "%02X", $0) }.joined() + } +} + +// MARK: - K1G + +struct K1GSegment: Hashable, Sendable { + let type: UInt8 + let subtype: UInt8 + let payload: Data + + var hex: String { + let length = UInt16(clamping: payload.count) + return String(format: "%02X%02X%04X", type, subtype, length) + HexCodec.string(payload) + } +} + +struct K1GEnvelope: Hashable, Sendable { + let outerLength: Int + let declaredSegmentCount: Int + let segments: [K1GSegment] +} + +enum K1GCodec { + static let requestAuthHex = "0016000200000000020100054B314720000804000101" + static let sessionKeyPrefixHex = "0095000200000000020100054B3147200008000080" + static let navContextHex = "0016000200000000020100054B31472000052E00011E" + static let emptyListsHex = "002A000600000000020100054B31472000052F0001000530000100053100010005320001000533000100" + static let startNavigationHex = "0016000200000000020100054B31472000068000010B" + static let projectionFrameHex = "0016000200000000020100054B314720000556000155" + static let projectionOnHex = "0016000200000000020100054B314720000605000155" + static let projectionStopHex = "0016000200000000020100054B3147200005560001AA" + static let projectionOffHex = "0016000200000000020100054B3147200006050001AA" + static let buttonAckPrefixHex = "0016000200000000020100054B3147200006800001" + + static let initialBurst: [String?] = [ + requestAuthHex, + nil, + "0018000200000000020100054B31472002060600030E3334", + "0016000200000000020100054B314720030557000155", + "0016000200000000020100054B3147200405560001AA", + "0016000200000000020100054B3147200506050001AA", + "0016000200000000020100054B3147200605170001AA", + "001D000200000000020100054B314720080A020008AA55000000000000", + "0044000A00000000020100054B3147200906080001FF060300015506040001A2060F0001AA0601000101054C000113052D00020000051B0001190521000132054D000132" + ] + + private static let navTemplateHex = + "007E001100000000020100054B31472025050100145461696C6C65206465204D617320647520477200" + + "050200013C050300013405050002000A05060001300507000130050800043033303305540001300509" + + "0002004F0546000110050A000155050C000104050B0006303031303030055500012006050001AA060D0001AA" + + static func decode(_ data: Data) -> K1GEnvelope? { + guard data.count >= 8 else { return nil } + let outerLength = Int(data[0]) << 8 | Int(data[1]) + let segmentCount = Int(data[2]) << 8 | Int(data[3]) + var offset = 8 + var segments: [K1GSegment] = [] + segments.reserveCapacity(segmentCount) + + for _ in 0.. Data { + var bytes = [UInt8](packet) + let marker: [UInt8] = [0x4B, 0x31, 0x47, 0x20] + guard let markerIndex = find(marker, in: bytes), markerIndex + 4 < bytes.count else { + throw DashProtocolError.missingK1GMarker + } + bytes[markerIndex + 4] = sequence + return Data(bytes) + } + + static func hostnameAnnounce(_ hostname: String) -> Data { + let raw = Data(hostname.utf8.prefix(200)) + var body = (try? HexCodec.data(from: "0021000200000000020100054B314720")) ?? Data() + body.append(contentsOf: [0x01, 0x06, 0x0B, 0x00, UInt8(clamping: raw.count + 1)]) + body.append(raw) + body.append(0) + setUInt16BE(UInt16(clamping: body.count), at: 0, in: &body) + return body + } + + static func routeCard(title: String, projectionOn: Bool) throws -> Data { + let template = try HexCodec.data(from: navTemplateHex) + guard let markerRange = template.range(of: Data("K1G ".utf8)) else { + throw DashProtocolError.missingK1GMarker + } + let sequenceOffset = markerRange.lowerBound + 4 + let titleTLVOffset = sequenceOffset + 1 + guard titleTLVOffset + 4 <= template.count, + template[titleTLVOffset] == 0x05, + template[titleTLVOffset + 1] == 0x01 else { + throw DashProtocolError.invalidTemplate + } + + let oldLength = Int(template[titleTLVOffset + 2]) << 8 | Int(template[titleTLVOffset + 3]) + let oldTitleStart = titleTLVOffset + 4 + let oldTitleEnd = min(template.count, oldTitleStart + oldLength) + let titleData = Data(title.utf8.prefix(60)) + Data([0]) + + var output = Data(template.prefix(oldTitleStart)) + let lengthBytes = withUnsafeBytes(of: UInt16(clamping: titleData.count).bigEndian) { Data($0) } + output.replaceSubrange(titleTLVOffset + 2.. Data { + try HexCodec.data(from: buttonAckPrefixHex + String(format: "%02X", buttonByte)) + } + + static func buildSessionKeyPacket(ciphertext: Data) throws -> Data { + guard ciphertext.count == 128 else { throw DashProtocolError.unexpectedRSAKeySize } + return try HexCodec.data(from: sessionKeyPrefixHex) + ciphertext + } + + private static func find(_ needle: [UInt8], in haystack: [UInt8]) -> Int? { + guard !needle.isEmpty, haystack.count >= needle.count else { return nil } + for i in 0...(haystack.count - needle.count) { + if haystack[i..<(i + needle.count)].elementsEqual(needle) { return i } + } + return nil + } + + private static func setUInt16BE(_ value: UInt16, at offset: Int, in data: inout Data) { + guard data.count >= offset + 2 else { return } + data[offset] = UInt8((value >> 8) & 0xFF) + data[offset + 1] = UInt8(value & 0xFF) + } +} + +// MARK: - Input / auth events + +enum DashButton: UInt8, Codable, Hashable, Sendable, CaseIterable { + case right = 0x13 + case left = 0x14 + case down = 0x15 + case click = 0x18 +} + +enum DashProtocolEvent: Hashable, Sendable { + case rsaModulus(Data) + case rsaExponent(Data) + case authAccepted + case authRejected(UInt8) + case button(DashButton) + case segment(K1GSegment) +} + +enum DashEventDecoder { + static func events(from datagram: Data) -> [DashProtocolEvent] { + guard let envelope = K1GCodec.decode(datagram) else { return [] } + return envelope.segments.map { segment in + switch (segment.type, segment.subtype) { + case (0x07, 0x00): return .rsaModulus(segment.payload) + case (0x07, 0x03): return .rsaExponent(segment.payload) + case (0x07, 0x01): + let status = segment.payload.first ?? 0 + return status == 0x01 ? .authAccepted : .authRejected(status) + case (0x09, 0x00): + if let value = segment.payload.first, let button = DashButton(rawValue: value) { return .button(button) } + return .segment(segment) + default: return .segment(segment) + } + } + } +} + +// MARK: - Authentication + +struct DashAuthenticatedSession: Sendable { + let aesKey: Data +} + +enum DashAuthenticator { + static func randomAES256Key() throws -> Data { + var bytes = [UInt8](repeating: 0, count: 32) + let status = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) + guard status == errSecSuccess else { throw DashProtocolError.randomGenerationFailed(status) } + return Data(bytes) + } + + static func encryptedSessionPayload( + ssid: String, + modulus: Data, + exponent: Data, + aesKey: Data + ) throws -> Data { + guard aesKey.count == 32 else { throw DashProtocolError.invalidAESKey } + let publicKeyDER = DER.rsaPublicKey(modulus: modulus, exponent: exponent) + let attributes: [CFString: Any] = [ + kSecAttrKeyType: kSecAttrKeyTypeRSA, + kSecAttrKeyClass: kSecAttrKeyClassPublic, + kSecAttrKeySizeInBits: modulus.count * 8 + ] + + var error: Unmanaged? + guard let key = SecKeyCreateWithData(publicKeyDER as CFData, attributes as CFDictionary, &error) else { + if let error { throw error.takeRetainedValue() } + throw DashProtocolError.publicKeyCreationFailed + } + guard SecKeyIsAlgorithmSupported(key, .encrypt, .rsaEncryptionPKCS1) else { + throw DashProtocolError.unsupportedRSAAlgorithm + } + + let payload = Data(ssid.utf8) + aesKey + guard let encrypted = SecKeyCreateEncryptedData(key, .rsaEncryptionPKCS1, payload as CFData, &error) else { + if let error { throw error.takeRetainedValue() } + throw DashProtocolError.rsaEncryptionFailed + } + return encrypted as Data + } +} + +private enum DER { + static func rsaPublicKey(modulus: Data, exponent: Data) -> Data { + sequence(integer(modulus) + integer(exponent)) + } + + private static func integer(_ raw: Data) -> Data { + var body = Data(raw.drop(while: { $0 == 0 })) + if body.isEmpty { body.append(0) } + if let first = body.first, first & 0x80 != 0 { body.insert(0, at: 0) } + return Data([0x02]) + length(body.count) + body + } + + private static func sequence(_ content: Data) -> Data { + Data([0x30]) + length(content.count) + content + } + + private static func length(_ count: Int) -> Data { + if count < 0x80 { return Data([UInt8(count)]) } + var value = count + var bytes: [UInt8] = [] + while value > 0 { + bytes.insert(UInt8(value & 0xFF), at: 0) + value >>= 8 + } + return Data([0x80 | UInt8(bytes.count)]) + Data(bytes) + } +} + +enum DashProtocolError: LocalizedError { + case invalidHex + case missingK1GMarker + case invalidTemplate + case unexpectedRSAKeySize + case invalidAESKey + case randomGenerationFailed(OSStatus) + case publicKeyCreationFailed + case unsupportedRSAAlgorithm + case rsaEncryptionFailed + + var errorDescription: String? { + switch self { + case .invalidHex: return "Protocol hex string is malformed." + case .missingK1GMarker: return "K1G marker was not found in the packet." + case .invalidTemplate: return "The navigation packet template is invalid." + case .unexpectedRSAKeySize: return "The current protocol profile expects an RSA-1024 key." + case .invalidAESKey: return "The negotiated AES session key must be 32 bytes." + case .randomGenerationFailed(let status): return "Secure random generation failed (\(status))." + case .publicKeyCreationFailed: return "Could not create the dash RSA public key." + case .unsupportedRSAAlgorithm: return "RSA PKCS#1 v1.5 encryption is not supported by this key." + case .rsaEncryptionFailed: return "Could not encrypt the dash session payload." + } + } +} diff --git a/RideDash/Diagnostics/DiagnosticLog.swift b/RideDash/Diagnostics/DiagnosticLog.swift new file mode 100644 index 0000000..56dc1cd --- /dev/null +++ b/RideDash/Diagnostics/DiagnosticLog.swift @@ -0,0 +1,67 @@ +import Combine +import Foundation + +@MainActor +final class DiagnosticLog: ObservableObject { + struct Entry: Identifiable, Codable, Equatable { + enum Level: String, Codable { + case info + case warning + case error + } + + let id: UUID + let timestamp: Date + let level: Level + let category: String + let message: String + + init(level: Level, category: String, message: String) { + self.id = UUID() + self.timestamp = Date() + self.level = level + self.category = category + self.message = message + } + } + + @Published private(set) var entries: [Entry] = [] + + func append(_ message: String, category: String, level: Entry.Level = .info) { + entries.append(Entry(level: level, category: category, message: message)) + } + + func clear() { + entries.removeAll() + } + + func exportText(profile: DashTestProfile) -> String { + let formatter = ISO8601DateFormatter() + var lines: [String] = [ + "RideDash diagnostic session", + "Generated: \(formatter.string(from: Date()))", + "Bike: \(profile.bikeModel)", + "Dash firmware: \(profile.dashFirmware.isEmpty ? "unknown" : profile.dashFirmware)", + "Dash SSID: \(sanitizedSSID(profile.dashSSID))", + "Dash host: \(profile.dashHost)", + "Phone: \(profile.iPhoneModel)", + "iOS: \(profile.iOSVersion)", + "", + "Timeline" + ] + + lines.append(contentsOf: entries.map { entry in + "\(formatter.string(from: entry.timestamp)) [\(entry.level.rawValue.uppercased())] [\(entry.category)] \(entry.message)" + }) + + lines.append("") + lines.append("Credentials, private keys and precise route history are intentionally excluded.") + return lines.joined(separator: "\n") + } + + private func sanitizedSSID(_ ssid: String) -> String { + guard !ssid.isEmpty else { return "unknown" } + guard ssid.count > 4 else { return "" } + return "\(ssid.prefix(2))…\(ssid.suffix(2))" + } +} diff --git a/RideDash/Features/Diagnostics/DiagnosticsView.swift b/RideDash/Features/Diagnostics/DiagnosticsView.swift new file mode 100644 index 0000000..f185709 --- /dev/null +++ b/RideDash/Features/Diagnostics/DiagnosticsView.swift @@ -0,0 +1,328 @@ +import Combine +import SwiftUI +import UIKit + +struct DiagnosticsView: View { + @StateObject private var wiFiManager = TripperWiFiManager() + @StateObject private var networkMonitor = LocalNetworkMonitor() + @StateObject private var transport = DashTransport() + @StateObject private var log = DiagnosticLog() + @StateObject private var deviceHealth = DeviceHealthMonitor() + + @AppStorage("dash.test.bikeModel") private var bikeModel = "Test motorcycle" + @AppStorage("dash.test.firmware") private var dashFirmware = "" + @AppStorage("dash.test.ssid") private var dashSSID = "" + @AppStorage("dash.test.host") private var dashHost = "192.168.1.1" + @AppStorage("dash.test.port") private var dashPort = 2000 + + @State private var passphrase = "" + @State private var selfCheckResult: ProtocolSelfCheck.Result? + + private var profile: DashTestProfile { + var profile = DashTestProfile.defaultProfile + profile.bikeModel = bikeModel + profile.dashFirmware = dashFirmware + profile.dashSSID = dashSSID + profile.dashHost = dashHost + return profile + } + + var body: some View { + Form { + hardwareSection + deviceHealthSection + wiFiSection + networkSection + transportSection + selfCheckSection + logSection + } + .navigationTitle("Dash Diagnostics") + .onAppear { + networkMonitor.start() + deviceHealth.start() + log.append("Diagnostics screen opened", category: "app") + logDeviceHealth() + } + .onDisappear { + transport.stop() + deviceHealth.stop() + } + .onChange(of: networkMonitor.statusText) { _, newValue in + log.append("Path status: \(newValue); Wi-Fi=\(networkMonitor.usesWiFi)", category: "network") + } + .onChange(of: transport.state) { _, newValue in + log.append("Transport: \(newValue.description)", category: "udp") + } + .onChange(of: deviceHealth.thermalStateText) { _, _ in logDeviceHealth() } + } + + private var hardwareSection: some View { + Section("Hardware test profile") { + TextField("Motorcycle model", text: $bikeModel) + TextField("Display firmware", text: $dashFirmware) + .textInputAutocapitalization(.never) + LabeledContent("Phone", value: profile.iPhoneModel) + LabeledContent("iOS", value: profile.iOSVersion) + } + } + + private var deviceHealthSection: some View { + Section("Device health") { + LabeledContent("Thermal", value: deviceHealth.thermalStateText) + LabeledContent("Battery", value: deviceHealth.batteryLevelText) + LabeledContent("Battery state", value: deviceHealth.batteryStateText) + LabeledContent("Low Power Mode", value: deviceHealth.lowPowerMode ? "On" : "Off") + } footer: { + Text("Use these values during 30/60/120-minute projection tests to correlate throttling, battery drain and stream instability.") + } + } + + private var wiFiSection: some View { + Section { + TextField("Display Wi-Fi SSID", text: $dashSSID) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + SecureField("Wi-Fi password (if required)", text: $passphrase) + + Button("Request Wi-Fi Join") { + Task { + log.append("Wi-Fi join requested for configured display SSID", category: "wifi") + do { + try await wiFiManager.join(ssid: dashSSID, passphrase: passphrase) + log.append("Wi-Fi join request completed", category: "wifi") + passphrase = "" + } catch { + log.append(error.localizedDescription, category: "wifi", level: .error) + } + } + } + .disabled(dashSSID.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + + Button("Remove Saved Configuration", role: .destructive) { + Task { + await wiFiManager.removeConfiguration(forSSID: dashSSID) + log.append("Removed app-managed Wi-Fi configuration", category: "wifi") + } + } + + LabeledContent("Join state", value: wiFiManager.status.description) + } header: { + Text("Wi-Fi") + } footer: { + Text("The password exists only in this screen state and is never written to diagnostic logs.") + } + } + + private var networkSection: some View { + Section("Local network") { + LabeledContent("Path", value: networkMonitor.statusText) + LabeledContent("Using Wi-Fi", value: networkMonitor.usesWiFi ? "Yes" : "No") + if networkMonitor.interfaceNames.isEmpty { + Text("No interfaces reported yet").foregroundStyle(.secondary) + } else { + ForEach(networkMonitor.interfaceNames, id: \.self) { name in + Text(name).font(.caption) + } + } + } + } + + private var transportSection: some View { + Section { + TextField("Display host", text: $dashHost) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + TextField("UDP port", value: $dashPort, format: .number) + .keyboardType(.numberPad) + + Button("Open UDP Route") { + do { + try transport.start(host: dashHost, port: UInt16(clamping: dashPort)) + log.append("Opening UDP route to \(dashHost):\(dashPort)", category: "udp") + } catch { + log.append(error.localizedDescription, category: "udp", level: .error) + } + } + + Button("Stop UDP Route", role: .destructive) { + transport.stop() + } + + LabeledContent("Transport", value: transport.state.description) + LabeledContent("RX packets", value: "\(transport.receivedPackets)") + LabeledContent("TX packets", value: "\(transport.sentPackets)") + } header: { + Text("UDP diagnostic route") + } footer: { + Text("This screen is intentionally transport-only. Use Settings → Connection & Projection for authentication, navigation-mode control and H.264/RTP projection.") + } + } + + private var selfCheckSection: some View { + Section("Local self-check") { + Button("Run Protocol + RTP Self-Check") { + let result = ProtocolSelfCheck.run() + selfCheckResult = result + log.append( + "Self-check \(result.passed ? "passed" : "failed"): \(result.summary)", + category: "self-check", + level: result.passed ? .info : .error + ) + } + + if let result = selfCheckResult { + Label(result.passed ? "Passed" : "Failed", systemImage: result.passed ? "checkmark.circle.fill" : "xmark.octagon.fill") + .foregroundStyle(result.passed ? .green : .red) + Text(result.summary) + .font(.caption) + .textSelection(.enabled) + } + } footer: { + Text("This performs deterministic in-app checks of K1G decoding/sequence patching, route-card generation and RTP/FU-A packet construction. It sends nothing to the motorcycle.") + } + } + + private var logSection: some View { + Section { + if log.entries.isEmpty { + Text("No diagnostic events yet").foregroundStyle(.secondary) + } else { + ForEach(log.entries.suffix(30)) { entry in + VStack(alignment: .leading, spacing: 3) { + Text("\(entry.category.uppercased()) · \(entry.level.rawValue.uppercased())") + .font(.caption2) + .foregroundStyle(.secondary) + Text(entry.message).font(.caption) + } + } + } + + ShareLink( + item: log.exportText(profile: profile), + subject: Text("RideDash diagnostic log"), + message: Text("Sanitized RideDash hardware test log") + ) { + Label("Export Diagnostic Log", systemImage: "square.and.arrow.up") + } + + Button("Clear Log", role: .destructive) { log.clear() } + } header: { + Text("Session log") + } footer: { + Text("Export redacts most of the SSID and excludes the Wi-Fi password, cryptographic session keys and route history.") + } + } + + private func logDeviceHealth() { + log.append( + "Thermal=\(deviceHealth.thermalStateText), battery=\(deviceHealth.batteryLevelText), state=\(deviceHealth.batteryStateText), lowPower=\(deviceHealth.lowPowerMode)", + category: "health" + ) + } +} + +@MainActor +final class DeviceHealthMonitor: ObservableObject { + @Published private(set) var thermalStateText = "Unknown" + @Published private(set) var batteryLevelText = "Unknown" + @Published private(set) var batteryStateText = "Unknown" + @Published private(set) var lowPowerMode = ProcessInfo.processInfo.isLowPowerModeEnabled + + private var cancellables: Set = [] + + func start() { + UIDevice.current.isBatteryMonitoringEnabled = true + refresh() + + NotificationCenter.default.publisher(for: ProcessInfo.thermalStateDidChangeNotification) + .merge(with: NotificationCenter.default.publisher(for: .NSProcessInfoPowerStateDidChange)) + .receive(on: DispatchQueue.main) + .sink { [weak self] _ in self?.refresh() } + .store(in: &cancellables) + + NotificationCenter.default.publisher(for: UIDevice.batteryLevelDidChangeNotification) + .merge(with: NotificationCenter.default.publisher(for: UIDevice.batteryStateDidChangeNotification)) + .receive(on: DispatchQueue.main) + .sink { [weak self] _ in self?.refresh() } + .store(in: &cancellables) + } + + func stop() { + cancellables.removeAll() + UIDevice.current.isBatteryMonitoringEnabled = false + } + + private func refresh() { + switch ProcessInfo.processInfo.thermalState { + case .nominal: thermalStateText = "Nominal" + case .fair: thermalStateText = "Fair" + case .serious: thermalStateText = "Serious" + case .critical: thermalStateText = "Critical" + @unknown default: thermalStateText = "Unknown" + } + + let level = UIDevice.current.batteryLevel + batteryLevelText = level < 0 ? "Unknown" : "\(Int((level * 100).rounded()))%" + + switch UIDevice.current.batteryState { + case .unknown: batteryStateText = "Unknown" + case .unplugged: batteryStateText = "Unplugged" + case .charging: batteryStateText = "Charging" + case .full: batteryStateText = "Full" + @unknown default: batteryStateText = "Unknown" + } + + lowPowerMode = ProcessInfo.processInfo.isLowPowerModeEnabled + } +} + +enum ProtocolSelfCheck { + struct Result { + let passed: Bool + let summary: String + } + + static func run() -> Result { + do { + let auth = try HexCodec.data(from: K1GCodec.requestAuthHex) + guard K1GCodec.decode(auth) != nil else { + return .init(passed: false, summary: "K1G request-auth packet did not decode") + } + + let patched = try K1GCodec.patchSequence(auth, sequence: 0xA5) + guard let marker = patched.range(of: Data("K1G ".utf8)), marker.upperBound < patched.endIndex, + patched[marker.upperBound] == 0xA5 else { + return .init(passed: false, summary: "Rolling sequence patch did not update the K1G sequence byte") + } + + let route = try K1GCodec.routeCard(title: "RideDash Self Check", projectionOn: true) + guard K1GCodec.decode(route) != nil else { + return .init(passed: false, summary: "Generated route card did not decode") + } + + let packetizer = H264RTPPacketizer(fps: 4, maxPayload: 300) + _ = packetizer.packetize([ + H264NALUnit(bytes: Data([0x67, 0x42, 0x00, 0x1E]), isParameterSet: true), + H264NALUnit(bytes: Data([0x68, 0xCE, 0x06, 0xE2]), isParameterSet: true) + ]) + let oversizedIDR = Data([0x65]) + Data(repeating: 0xAB, count: 900) + let rtp = packetizer.packetize([H264NALUnit(bytes: oversizedIDR, isParameterSet: false)]) + guard rtp.count > 1, + rtp.allSatisfy({ $0.count >= 12 && $0[0] == 0x80 && ($0[1] & 0x7F) == 96 }) else { + return .init(passed: false, summary: "RTP/FU-A packetization did not produce valid RTP v2/PT96 fragments") + } + + return .init( + passed: true, + summary: "K1G decode, sequence patch, route-card generation and RTP/FU-A fragmentation all passed" + ) + } catch { + return .init(passed: false, summary: error.localizedDescription) + } + } +} + +#Preview { + NavigationStack { DiagnosticsView() } +} diff --git a/RideDash/Features/Product/ProductFeatures.swift b/RideDash/Features/Product/ProductFeatures.swift new file mode 100644 index 0000000..567e6ab --- /dev/null +++ b/RideDash/Features/Product/ProductFeatures.swift @@ -0,0 +1,1106 @@ +import MapKit +import SwiftData +import SwiftUI +import UIKit +import UserNotifications + +// MARK: - Local models + +@Model +final class Vehicle { + var id: UUID + var name: String + var registrationNumber: String + var odometerKm: Double + var insuranceExpiry: Date? + var pucExpiry: Date? + var lastServiceDate: Date? + var isActive: Bool + + init( + name: String, + registrationNumber: String = "", + odometerKm: Double = 0, + insuranceExpiry: Date? = nil, + pucExpiry: Date? = nil, + lastServiceDate: Date? = nil, + isActive: Bool = false + ) { + id = UUID() + self.name = name + self.registrationNumber = registrationNumber + self.odometerKm = odometerKm + self.insuranceExpiry = insuranceExpiry + self.pucExpiry = pucExpiry + self.lastServiceDate = lastServiceDate + self.isActive = isActive + } +} + +enum ExpenseCategory: String, CaseIterable, Identifiable, Codable { + case fuel = "Fuel" + case service = "Service" + case repair = "Repair" + case accessory = "Accessory" + case gear = "Riding Gear" + case food = "Food" + case stay = "Stay" + case transport = "Transport" + case other = "Other" + + var id: String { rawValue } +} + +@Model +final class Expense { + var id: UUID + var date: Date + var categoryRaw: String + var amount: Double + var odometerKm: Double? + var notes: String + + var category: ExpenseCategory { + get { ExpenseCategory(rawValue: categoryRaw) ?? .other } + set { categoryRaw = newValue.rawValue } + } + + init( + date: Date = .now, + category: ExpenseCategory, + amount: Double, + odometerKm: Double? = nil, + notes: String = "" + ) { + id = UUID() + self.date = date + categoryRaw = category.rawValue + self.amount = amount + self.odometerKm = odometerKm + self.notes = notes + } +} + +enum MaintenanceKind: String, CaseIterable, Identifiable, Codable { + case service = "Service" + case chainClean = "Chain Clean" + case chainLube = "Chain Lube" + case tyre = "Tyre" + case brake = "Brake" + case accessory = "Accessory" + case other = "Other" + + var id: String { rawValue } +} + +@Model +final class MaintenanceRecord { + var id: UUID + var date: Date + var kindRaw: String + var odometerKm: Double + var notes: String + var nextDueKm: Double? + var nextDueDate: Date? + + var kind: MaintenanceKind { + get { MaintenanceKind(rawValue: kindRaw) ?? .other } + set { kindRaw = newValue.rawValue } + } + + init( + date: Date = .now, + kind: MaintenanceKind, + odometerKm: Double, + notes: String = "", + nextDueKm: Double? = nil, + nextDueDate: Date? = nil + ) { + id = UUID() + self.date = date + kindRaw = kind.rawValue + self.odometerKm = odometerKm + self.notes = notes + self.nextDueKm = nextDueKm + self.nextDueDate = nextDueDate + } +} + +@Model +final class FuelLog { + var id: UUID + var date: Date + var odometerKm: Double + var litres: Double + var totalCost: Double + var fullTank: Bool + + init( + date: Date = .now, + odometerKm: Double, + litres: Double, + totalCost: Double, + fullTank: Bool = true + ) { + id = UUID() + self.date = date + self.odometerKm = odometerKm + self.litres = litres + self.totalCost = totalCost + self.fullTank = fullTank + } +} + +@Model +final class RideRecord { + var id: UUID + var startedAt: Date + var endedAt: Date? + var destination: String + var distanceKm: Double + var notes: String + + init( + startedAt: Date = .now, + endedAt: Date? = nil, + destination: String = "", + distanceKm: Double = 0, + notes: String = "" + ) { + id = UUID() + self.startedAt = startedAt + self.endedAt = endedAt + self.destination = destination + self.distanceKm = distanceKm + self.notes = notes + } +} + +// MARK: - Dashboard + +struct DashboardView: View { + @EnvironmentObject private var session: DashSessionCoordinator + @EnvironmentObject private var navigation: NavigationViewModel + @Query(sort: \Vehicle.name) private var vehicles: [Vehicle] + @Query(sort: \Expense.date, order: .reverse) private var expenses: [Expense] + @AppStorage("settings.currency") private var currency = "INR" + + private var activeVehicle: Vehicle? { + vehicles.first(where: { $0.isActive }) ?? vehicles.first + } + + var body: some View { + List { + Section("Display") { + HStack { + VStack(alignment: .leading, spacing: 3) { + Text(session.state.label).font(.headline) + Text("RX \(session.transport.receivedPackets) · TX \(session.transport.sentPackets)") + .font(.caption) + .foregroundStyle(.secondary) + } + Spacer() + Circle() + .fill(connectionColor) + .frame(width: 12, height: 12) + } + if session.reconnectAttempt > 0 { + LabeledContent("Reconnect", value: "\(session.reconnectAttempt)/5") + } + } + + Section("Active vehicle") { + if let vehicle = activeVehicle { + LabeledContent(vehicle.name, value: "\(vehicle.odometerKm, specifier: "%.0f") km") + if !vehicle.registrationNumber.isEmpty { + LabeledContent("Registration", value: vehicle.registrationNumber) + } + } else { + Text("Add a vehicle from Settings → Vehicles") + .foregroundStyle(.secondary) + } + } + + Section("Navigation") { + LabeledContent("Destination", value: navigation.destination?.name ?? "Not set") + LabeledContent("Instruction", value: navigation.projectionState.maneuver) + LabeledContent("Next turn", value: navigation.projectionState.distanceToManeuver) + if navigation.recalculationCount > 0 { + LabeledContent("Reroutes", value: "\(navigation.recalculationCount)") + } + } + + Section("This month") { + LabeledContent("Expenses", value: currentMonthSpend.formatted(.currency(code: currency))) + } + } + .navigationTitle("RideDash") + } + + private var currentMonthSpend: Double { + let calendar = Calendar.current + return expenses + .filter { calendar.isDate($0.date, equalTo: .now, toGranularity: .month) } + .reduce(0) { $0 + $1.amount } + } + + private var connectionColor: Color { + switch session.state { + case .projecting, .navigationReady, .authenticated: return .green + case .failed: return .red + case .disconnected: return .secondary + default: return .orange + } + } +} + +// MARK: - Route UI + +struct RideNavigationView: View { + @EnvironmentObject private var navigation: NavigationViewModel + @EnvironmentObject private var session: DashSessionCoordinator + @EnvironmentObject private var streamer: ProjectionStreamer + + @AppStorage("dash.profile.host") private var dashHost = "192.168.1.1" + @AppStorage("dash.profile.broadcast") private var broadcastHost = "192.168.1.255" + @AppStorage("dash.profile.fps") private var fps = 4 + @AppStorage("dash.profile.bitrate") private var bitrate = 250 + + var body: some View { + VStack(spacing: 0) { + Map { + UserAnnotation() + if let destination = navigation.destination { + Marker(destination.name, coordinate: destination.coordinate) + } + if let route = navigation.route { + MapPolyline(route.polyline) + .stroke(.orange, lineWidth: 6) + } + } + .mapControls { + MapCompass() + MapUserLocationButton() + } + .frame(maxHeight: .infinity) + + VStack(spacing: 10) { + HStack { + TextField("Destination, coordinates, or map URL", text: $navigation.destinationInput) + .textFieldStyle(.roundedBorder) + .textInputAutocapitalization(.never) + Button { + Task { await navigation.calculateRoute() } + } label: { + if navigation.isCalculating || navigation.isRecalculating { + ProgressView() + } else { + Image(systemName: "arrow.triangle.turn.up.right.diamond.fill") + } + } + .buttonStyle(.borderedProminent) + } + + if let error = navigation.errorMessage { + Text(error).font(.caption).foregroundStyle(.red) + } + + if navigation.route != nil { + HStack { + VStack(alignment: .leading, spacing: 2) { + Text(navigation.projectionState.maneuver) + .font(.headline) + .lineLimit(1) + Text("\(navigation.projectionState.distanceToManeuver) · ETA \(navigation.projectionState.eta)") + .font(.caption) + .foregroundStyle(.secondary) + if navigation.isRecalculating { + Text("Recalculating route…") + .font(.caption2) + .foregroundStyle(.orange) + } + } + Spacer() + Button("Apple Maps") { navigation.openInAppleMaps() } + .buttonStyle(.bordered) + } + } + + displayActions + } + .padding() + .background(.regularMaterial) + } + .navigationTitle("Navigation") + .navigationBarTitleDisplayMode(.inline) + .onAppear { navigation.startLocation() } + } + + @ViewBuilder + private var displayActions: some View { + if session.state == .authenticated || session.state == .navigationReady || session.state == .projecting { + HStack { + Button("Dash Nav") { + Task { + try? await session.enterNavigation(title: navigation.destination?.name ?? "Navigation") + } + } + .buttonStyle(.bordered) + + Button(streamer.state == .streaming ? "Streaming" : "Project") { + startProjection() + } + .buttonStyle(.borderedProminent) + .disabled(session.state != .navigationReady && session.state != .projecting) + + Button("Stop", role: .destructive) { + streamer.stop() + Task { await session.stopProjection() } + } + .buttonStyle(.bordered) + } + } + } + + private func startProjection() { + var profile = DashProtocolProfile.publicReference + profile.host = dashHost + profile.broadcastHost = broadcastHost + profile.fps = fps + profile.bitrateKbps = bitrate + + do { + try streamer.start(coordinator: session, profile: profile) { + navigation.projectionState + } + } catch { + session.log.append(error.localizedDescription, category: "projection", level: .error) + } + } +} + +// MARK: - Display connection / projection lab + +struct DisplayConnectionView: View { + @EnvironmentObject private var session: DashSessionCoordinator + @EnvironmentObject private var navigation: NavigationViewModel + @EnvironmentObject private var streamer: ProjectionStreamer + @StateObject private var wifi = TripperWiFiManager() + + @AppStorage("dash.test.ssid") private var ssid = "" + @AppStorage("dash.profile.host") private var host = "192.168.1.1" + @AppStorage("dash.profile.broadcast") private var broadcastHost = "192.168.1.255" + @AppStorage("dash.profile.controlPort") private var controlPort = 2000 + @AppStorage("dash.profile.inputPort") private var inputPort = 2002 + @AppStorage("dash.profile.videoPort") private var videoPort = 5000 + @AppStorage("dash.profile.fps") private var fps = 4 + @AppStorage("dash.profile.bitrate") private var bitrate = 250 + + @State private var passphrase = "" + @State private var hostname = UIDevice.current.name + @State private var calibrationGrid = true + + var body: some View { + Form { + Section("Compatible display Wi-Fi") { + TextField("SSID", text: $ssid) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + SecureField("Password", text: $passphrase) + Button("Join Wi-Fi") { + Task { + do { + try await wifi.join(ssid: ssid, passphrase: passphrase) + passphrase = "" + } catch { + session.log.append(error.localizedDescription, category: "wifi", level: .error) + } + } + } + .disabled(ssid.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + LabeledContent("Wi-Fi", value: wifi.status.description) + } + + Section("Protocol profile") { + TextField("Dash host", text: $host) + .textInputAutocapitalization(.never) + TextField("Broadcast", text: $broadcastHost) + .textInputAutocapitalization(.never) + Stepper("Control UDP \(controlPort)", value: $controlPort, in: 1...65_535) + Stepper("Input UDP \(inputPort)", value: $inputPort, in: 1...65_535) + Stepper("Video UDP \(videoPort)", value: $videoPort, in: 1...65_535) + Stepper("FPS \(fps)", value: $fps, in: 1...15) + Stepper("Bitrate \(bitrate) kbps", value: $bitrate, in: 100...800, step: 25) + } + + Section("Session") { + TextField("Phone hostname", text: $hostname) + Toggle("Automatic reconnect", isOn: $session.automaticReconnectEnabled) + LabeledContent("State", value: session.state.label) + LabeledContent("RX packets", value: "\(session.transport.receivedPackets)") + LabeledContent("TX packets", value: "\(session.transport.sentPackets)") + if session.reconnectAttempt > 0 { + LabeledContent("Reconnect attempt", value: "\(session.reconnectAttempt)/5") + } + if let reason = session.lastReconnectReason { + Text(reason) + .font(.caption) + .foregroundStyle(.secondary) + } + if let button = session.lastButton { + LabeledContent("Last dash input", value: String(describing: button)) + } + + Button("Connect + Authenticate") { + Task { + await session.connect(ssid: ssid, hostname: hostname, profile: profile) + } + } + .buttonStyle(.borderedProminent) + .disabled(ssid.isEmpty) + + if session.state == .authenticated || session.state == .navigationReady || session.state == .projecting { + Button("Enter Navigation Mode") { + Task { + try? await session.enterNavigation(title: navigation.destination?.name ?? "RideDash") + } + } + } + + if session.state == .navigationReady || session.state == .projecting { + Toggle("Calibration grid", isOn: $calibrationGrid) + Button("Start H.264/RTP Projection") { + startProjection() + } + .buttonStyle(.borderedProminent) + } + + Button("Stop Projection", role: .destructive) { + streamer.stop() + Task { await session.stopProjection() } + } + + Button("Disconnect", role: .destructive) { + streamer.stop() + session.disconnect() + } + } + + Section("Stream metrics") { + LabeledContent("State", value: String(describing: streamer.state)) + LabeledContent("Rendered frames", value: "\(streamer.renderedFrames)") + LabeledContent("RTP packets", value: "\(streamer.sentRTPPackets)") + LabeledContent( + "Encoded", + value: ByteCountFormatter.string(fromByteCount: Int64(streamer.encodedBytes), countStyle: .file) + ) + } + } + .navigationTitle("Display") + } + + private var profile: DashProtocolProfile { + DashProtocolProfile( + host: host, + broadcastHost: broadcastHost, + controlPort: UInt16(clamping: controlPort), + inputPort: UInt16(clamping: inputPort), + videoPort: UInt16(clamping: videoPort), + renderWidth: 526, + renderHeight: 300, + fps: fps, + bitrateKbps: bitrate, + respondToInput: true + ) + } + + private func startProjection() { + do { + try streamer.start(coordinator: session, profile: profile) { + var state = navigation.projectionState + state.isCalibrationGrid = calibrationGrid + return state + } + } catch { + session.log.append(error.localizedDescription, category: "projection", level: .error) + } + } +} + +// MARK: - Vehicles + +struct VehiclesView: View { + @Environment(\.modelContext) private var context + @Query(sort: \Vehicle.name) private var vehicles: [Vehicle] + @State private var showingAdd = false + + var body: some View { + List { + if vehicles.isEmpty { + ContentUnavailableView( + "No vehicles", + systemImage: "motorcycle", + description: Text("Add a motorcycle to track maintenance, expenses and rides.") + ) + } + + ForEach(vehicles) { vehicle in + NavigationLink { + VehicleDetailView(vehicle: vehicle) + } label: { + HStack { + VStack(alignment: .leading, spacing: 3) { + Text(vehicle.name).font(.headline) + Text("\(vehicle.odometerKm, specifier: "%.0f") km") + .font(.caption) + .foregroundStyle(.secondary) + } + Spacer() + if vehicle.isActive { + Image(systemName: "checkmark.circle.fill").foregroundStyle(.green) + } + } + } + .swipeActions(edge: .leading) { + Button("Active") { makeActive(vehicle) } + .tint(.green) + } + } + .onDelete { offsets in + offsets.forEach { context.delete(vehicles[$0]) } + } + } + .navigationTitle("Vehicles") + .toolbar { + Button { showingAdd = true } label: { Image(systemName: "plus") } + } + .sheet(isPresented: $showingAdd) { AddVehicleView() } + } + + private func makeActive(_ selected: Vehicle) { + vehicles.forEach { $0.isActive = $0.id == selected.id } + } +} + +struct AddVehicleView: View { + @Environment(\.dismiss) private var dismiss + @Environment(\.modelContext) private var context + @Query private var vehicles: [Vehicle] + + @State private var name = "" + @State private var registration = "" + @State private var odometer = 0.0 + + var body: some View { + NavigationStack { + Form { + TextField("Vehicle name", text: $name) + TextField("Registration", text: $registration) + TextField("Odometer km", value: $odometer, format: .number) + .keyboardType(.decimalPad) + } + .navigationTitle("Add Vehicle") + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button("Cancel") { dismiss() } + } + ToolbarItem(placement: .confirmationAction) { + Button("Save") { + context.insert( + Vehicle( + name: name, + registrationNumber: registration, + odometerKm: odometer, + isActive: vehicles.isEmpty + ) + ) + dismiss() + } + .disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + } + } + } + } +} + +struct VehicleDetailView: View { + @Bindable var vehicle: Vehicle + + var body: some View { + Form { + Section("Vehicle") { + TextField("Name", text: $vehicle.name) + TextField("Registration", text: $vehicle.registrationNumber) + TextField("Odometer km", value: $vehicle.odometerKm, format: .number) + .keyboardType(.decimalPad) + } + Section("Documents") { + OptionalDateEditor(title: "Insurance expiry", date: $vehicle.insuranceExpiry) + OptionalDateEditor(title: "PUC expiry", date: $vehicle.pucExpiry) + OptionalDateEditor(title: "Last service", date: $vehicle.lastServiceDate) + } + } + .navigationTitle(vehicle.name) + } +} + +struct OptionalDateEditor: View { + let title: String + @Binding var date: Date? + + var body: some View { + Toggle( + title, + isOn: Binding( + get: { date != nil }, + set: { date = $0 ? (date ?? .now) : nil } + ) + ) + if date != nil { + DatePicker( + title, + selection: Binding(get: { date ?? .now }, set: { date = $0 }), + displayedComponents: .date + ) + } + } +} + +// MARK: - Garage + +struct GarageView: View { + @Environment(\.modelContext) private var context + @Query(sort: \FuelLog.date, order: .reverse) private var fuelLogs: [FuelLog] + @Query(sort: \MaintenanceRecord.date, order: .reverse) private var maintenance: [MaintenanceRecord] + @State private var showingFuel = false + @State private var showingMaintenance = false + + var body: some View { + List { + Section("Overview") { + LabeledContent("Fuel logs", value: "\(fuelLogs.count)") + LabeledContent("Maintenance logs", value: "\(maintenance.count)") + LabeledContent( + "Calculated mileage", + value: mileage.map { String(format: "%.1f km/L", $0) } ?? "Need 2 full tanks" + ) + } + + Section("Quick actions") { + Button("Log fuel") { showingFuel = true } + Button("Log maintenance") { showingMaintenance = true } + } + + Section("Recent fuel") { + ForEach(Array(fuelLogs.prefix(10))) { entry in + LabeledContent( + "\(entry.litres, specifier: "%.1f") L", + value: "\(entry.odometerKm, specifier: "%.0f") km" + ) + } + } + + Section("Recent maintenance") { + ForEach(Array(maintenance.prefix(10))) { entry in + VStack(alignment: .leading, spacing: 3) { + Text(entry.kind.rawValue).font(.headline) + Text("\(entry.odometerKm, specifier: "%.0f") km · \(entry.date.formatted(date: .abbreviated, time: .omitted))") + .font(.caption) + .foregroundStyle(.secondary) + if let dueDate = entry.nextDueDate { + Text("Due \(dueDate.formatted(date: .abbreviated, time: .omitted))") + .font(.caption2) + .foregroundStyle(.orange) + } else if let dueKm = entry.nextDueKm { + Text("Due at \(dueKm, specifier: "%.0f") km") + .font(.caption2) + .foregroundStyle(.orange) + } + } + } + } + } + .navigationTitle("Garage") + .sheet(isPresented: $showingFuel) { AddFuelView() } + .sheet(isPresented: $showingMaintenance) { AddMaintenanceView() } + } + + private var mileage: Double? { + let fullTanks = fuelLogs + .filter { $0.fullTank } + .sorted { $0.odometerKm < $1.odometerKm } + guard fullTanks.count >= 2, + let latest = fullTanks.last else { return nil } + let previous = fullTanks[fullTanks.count - 2] + let distance = latest.odometerKm - previous.odometerKm + guard distance > 0, latest.litres > 0 else { return nil } + return distance / latest.litres + } +} + +struct AddFuelView: View { + @Environment(\.dismiss) private var dismiss + @Environment(\.modelContext) private var context + @State private var odometer = 0.0 + @State private var litres = 0.0 + @State private var cost = 0.0 + @State private var fullTank = true + + var body: some View { + NavigationStack { + Form { + TextField("Odometer km", value: $odometer, format: .number).keyboardType(.decimalPad) + TextField("Litres", value: $litres, format: .number).keyboardType(.decimalPad) + TextField("Total cost", value: $cost, format: .number).keyboardType(.decimalPad) + Toggle("Full tank", isOn: $fullTank) + } + .navigationTitle("Fuel") + .toolbar { + ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } } + ToolbarItem(placement: .confirmationAction) { + Button("Save") { + context.insert(FuelLog(odometerKm: odometer, litres: litres, totalCost: cost, fullTank: fullTank)) + context.insert(Expense(category: .fuel, amount: cost, odometerKm: odometer, notes: "Fuel log")) + dismiss() + } + .disabled(litres <= 0) + } + } + } + } +} + +struct AddMaintenanceView: View { + @Environment(\.dismiss) private var dismiss + @Environment(\.modelContext) private var context + @State private var kind: MaintenanceKind = .service + @State private var odometer = 0.0 + @State private var notes = "" + @State private var nextDueKmEnabled = false + @State private var nextDueKm = 0.0 + @State private var nextDueDateEnabled = false + @State private var nextDueDate = Calendar.current.date(byAdding: .month, value: 6, to: .now) ?? .now + + var body: some View { + NavigationStack { + Form { + Section("Maintenance") { + Picker("Type", selection: $kind) { + ForEach(MaintenanceKind.allCases) { Text($0.rawValue).tag($0) } + } + TextField("Odometer km", value: $odometer, format: .number).keyboardType(.decimalPad) + TextField("Notes", text: $notes, axis: .vertical) + } + + Section("Next due") { + Toggle("Track next due odometer", isOn: $nextDueKmEnabled) + if nextDueKmEnabled { + TextField("Next due km", value: $nextDueKm, format: .number) + .keyboardType(.decimalPad) + } + + Toggle("Remind on a date", isOn: $nextDueDateEnabled) + if nextDueDateEnabled { + DatePicker("Due date", selection: $nextDueDate, displayedComponents: .date) + Text("RideDash will request notification permission when you save this reminder.") + .font(.caption) + .foregroundStyle(.secondary) + } + } + } + .navigationTitle("Maintenance") + .toolbar { + ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } } + ToolbarItem(placement: .confirmationAction) { + Button("Save") { + let record = MaintenanceRecord( + kind: kind, + odometerKm: odometer, + notes: notes, + nextDueKm: nextDueKmEnabled ? nextDueKm : nil, + nextDueDate: nextDueDateEnabled ? nextDueDate : nil + ) + context.insert(record) + if nextDueDateEnabled { + Task { + await MaintenanceReminderScheduler.schedule( + id: record.id, + title: record.kind.rawValue, + dueDate: nextDueDate + ) + } + } + dismiss() + } + } + } + } + } +} + +enum MaintenanceReminderScheduler { + static func schedule(id: UUID, title: String, dueDate: Date) async { + guard dueDate > .now else { return } + let center = UNUserNotificationCenter.current() + + do { + let settings = await center.notificationSettings() + var authorized = settings.authorizationStatus == .authorized || settings.authorizationStatus == .provisional + if settings.authorizationStatus == .notDetermined { + authorized = try await center.requestAuthorization(options: [.alert, .sound, .badge]) + } + guard authorized else { return } + + let identifier = "maintenance-\(id.uuidString)" + center.removePendingNotificationRequests(withIdentifiers: [identifier]) + + let content = UNMutableNotificationContent() + content.title = "Maintenance due" + content.body = "\(title) is due today. Open RideDash to review your garage log." + content.sound = .default + + var components = Calendar.current.dateComponents([.year, .month, .day], from: dueDate) + components.hour = 9 + components.minute = 0 + let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false) + try await center.add(UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)) + } catch { + // Reminder failure must never block saving maintenance history. + } + } + + static func cancel(id: UUID) { + UNUserNotificationCenter.current().removePendingNotificationRequests( + withIdentifiers: ["maintenance-\(id.uuidString)"] + ) + } +} + +// MARK: - Expenses + +struct ExpensesView: View { + @Environment(\.modelContext) private var context + @Query(sort: \Expense.date, order: .reverse) private var expenses: [Expense] + @State private var selectedCategory: ExpenseCategory? + @State private var showingAdd = false + @AppStorage("settings.currency") private var currency = "INR" + + private var filtered: [Expense] { + guard let selectedCategory else { return expenses } + return expenses.filter { $0.category == selectedCategory } + } + + var body: some View { + List { + Section { + LabeledContent( + "Total", + value: filtered.reduce(0) { $0 + $1.amount }.formatted(.currency(code: currency)) + ) + Picker("Filter", selection: $selectedCategory) { + Text("All").tag(Optional.none) + ForEach(ExpenseCategory.allCases) { category in + Text(category.rawValue).tag(Optional(category)) + } + } + } + + ForEach(filtered) { expense in + HStack { + VStack(alignment: .leading, spacing: 2) { + Text(expense.category.rawValue).font(.headline) + Text(expense.date.formatted(date: .abbreviated, time: .omitted)) + .font(.caption) + .foregroundStyle(.secondary) + } + Spacer() + Text(expense.amount.formatted(.currency(code: currency))) + } + } + .onDelete { offsets in + offsets.forEach { context.delete(filtered[$0]) } + } + } + .navigationTitle("Expenses") + .toolbar { + ToolbarItemGroup(placement: .topBarTrailing) { + ShareLink(item: CSVExporter.expenses(expenses)) { + Image(systemName: "square.and.arrow.up") + } + Button { showingAdd = true } label: { Image(systemName: "plus") } + } + } + .sheet(isPresented: $showingAdd) { AddExpenseView() } + } +} + +struct AddExpenseView: View { + @Environment(\.dismiss) private var dismiss + @Environment(\.modelContext) private var context + @State private var category: ExpenseCategory = .other + @State private var amount = 0.0 + @State private var notes = "" + + var body: some View { + NavigationStack { + Form { + Picker("Category", selection: $category) { + ForEach(ExpenseCategory.allCases) { Text($0.rawValue).tag($0) } + } + TextField("Amount", value: $amount, format: .number).keyboardType(.decimalPad) + TextField("Notes", text: $notes, axis: .vertical) + } + .navigationTitle("Expense") + .toolbar { + ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } } + ToolbarItem(placement: .confirmationAction) { + Button("Save") { + context.insert(Expense(category: category, amount: amount, notes: notes)) + dismiss() + } + .disabled(amount <= 0) + } + } + } + } +} + +enum CSVExporter { + static func expenses(_ expenses: [Expense]) -> String { + let formatter = ISO8601DateFormatter() + var rows = ["Date,Category,Amount,OdometerKm,Notes"] + for item in expenses { + rows.append([ + formatter.string(from: item.date), + escape(item.category.rawValue), + String(item.amount), + item.odometerKm.map { String($0) } ?? "", + escape(item.notes) + ].joined(separator: ",")) + } + return rows.joined(separator: "\n") + } + + private static func escape(_ value: String) -> String { + "\"" + value.replacingOccurrences(of: "\"", with: "\"\"") + "\"" + } +} + +// MARK: - Rides + +struct RidesView: View { + @Environment(\.modelContext) private var context + @Query(sort: \RideRecord.startedAt, order: .reverse) private var rides: [RideRecord] + @State private var showingAdd = false + + var body: some View { + List { + if rides.isEmpty { + ContentUnavailableView( + "No rides", + systemImage: "road.lanes", + description: Text("Save completed rides here.") + ) + } + ForEach(rides) { ride in + VStack(alignment: .leading, spacing: 3) { + Text(ride.destination.isEmpty ? "Ride" : ride.destination).font(.headline) + Text("\(ride.distanceKm, specifier: "%.1f") km · \(ride.startedAt.formatted(date: .abbreviated, time: .shortened))") + .font(.caption) + .foregroundStyle(.secondary) + } + } + .onDelete { offsets in + offsets.forEach { context.delete(rides[$0]) } + } + } + .navigationTitle("Rides") + .toolbar { + Button { showingAdd = true } label: { Image(systemName: "plus") } + } + .sheet(isPresented: $showingAdd) { AddRideView() } + } +} + +struct AddRideView: View { + @Environment(\.dismiss) private var dismiss + @Environment(\.modelContext) private var context + @State private var destination = "" + @State private var distance = 0.0 + + var body: some View { + NavigationStack { + Form { + TextField("Destination", text: $destination) + TextField("Distance km", value: $distance, format: .number).keyboardType(.decimalPad) + } + .navigationTitle("Ride") + .toolbar { + ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } } + ToolbarItem(placement: .confirmationAction) { + Button("Save") { + context.insert(RideRecord(destination: destination, distanceKm: distance)) + dismiss() + } + } + } + } + } +} + +// MARK: - Settings + +struct SettingsView: View { + @AppStorage("settings.currency") private var currency = "INR" + @AppStorage("settings.distance") private var distanceUnit = "km" + @AppStorage("settings.backgroundLocation") private var backgroundLocation = false + @EnvironmentObject private var navigation: NavigationViewModel + + var body: some View { + Form { + Section("Units") { + Picker("Currency", selection: $currency) { + Text("INR ₹").tag("INR") + Text("USD $").tag("USD") + Text("EUR €").tag("EUR") + Text("GBP £").tag("GBP") + } + Picker("Distance", selection: $distanceUnit) { + Text("Kilometres").tag("km") + Text("Miles").tag("mi") + } + } + + Section("Display integration") { + NavigationLink("Connection & Projection") { DisplayConnectionView() } + NavigationLink("Diagnostics") { DiagnosticsView() } + NavigationLink("Vehicles") { VehiclesView() } + } + + Section("Navigation behavior") { + Toggle("Background navigation location", isOn: $backgroundLocation) + .onChange(of: backgroundLocation) { _, enabled in + navigation.locationService.setBackgroundNavigationEnabled(enabled) + } + Text("Location background mode supports active navigation. iOS may still suspend video encoding/network projection after device lock; verify this manually on your iPhone.") + .font(.caption) + .foregroundStyle(.secondary) + } + + Section("Maintenance reminders") { + Text("When a maintenance entry includes a due date, RideDash schedules a local notification for 9:00 AM on that date after you grant notification permission.") + .font(.caption) + .foregroundStyle(.secondary) + } + + Section("Safety") { + Text("RideDash limits display integration to navigation/infotainment. It does not send ECU, throttle, brake, ABS, immobilizer or other safety-critical vehicle-control commands.") + .font(.caption) + } + } + .navigationTitle("Settings") + .onAppear { + navigation.locationService.setBackgroundNavigationEnabled(backgroundLocation) + } + } +} diff --git a/RideDash/Info.plist b/RideDash/Info.plist new file mode 100644 index 0000000..6db2526 --- /dev/null +++ b/RideDash/Info.plist @@ -0,0 +1,51 @@ + + + + + CFBundleDisplayName + RideDash + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + $(MARKETING_VERSION) + CFBundleVersion + $(CURRENT_PROJECT_VERSION) + LSRequiresIPhoneOS + + NSLocalNetworkUsageDescription + RideDash uses the local network to connect to a compatible motorcycle display for navigation and diagnostics. + NSLocationWhenInUseUsageDescription + RideDash uses your location to calculate routes and provide live riding navigation. + UIBackgroundModes + + location + + UIApplicationSupportsIndirectInputEvents + + CFBundleURLTypes + + + CFBundleURLName + dev.dagerott.RideDash.route + CFBundleURLSchemes + + ridedash + + + + UILaunchScreen + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + + + diff --git a/RideDash/Models/DashTestProfile.swift b/RideDash/Models/DashTestProfile.swift new file mode 100644 index 0000000..9e14488 --- /dev/null +++ b/RideDash/Models/DashTestProfile.swift @@ -0,0 +1,22 @@ +import Foundation +import UIKit + +struct DashTestProfile: Codable, Equatable { + var bikeModel: String + var dashFirmware: String + var dashSSID: String + var dashHost: String + var iPhoneModel: String + var iOSVersion: String + + static var defaultProfile: DashTestProfile { + DashTestProfile( + bikeModel: "Test motorcycle", + dashFirmware: "", + dashSSID: "", + dashHost: "192.168.1.1", + iPhoneModel: UIDevice.current.model, + iOSVersion: UIDevice.current.systemVersion + ) + } +} diff --git a/RideDash/NavigationCore/NavigationCore.swift b/RideDash/NavigationCore/NavigationCore.swift new file mode 100644 index 0000000..f6d8614 --- /dev/null +++ b/RideDash/NavigationCore/NavigationCore.swift @@ -0,0 +1,423 @@ +import Combine +import CoreLocation +import Foundation +import MapKit + +@MainActor +final class NavigationLocationService: NSObject, ObservableObject, CLLocationManagerDelegate { + @Published private(set) var authorizationStatus: CLAuthorizationStatus + @Published private(set) var location: CLLocation? + @Published private(set) var heading: CLHeading? + @Published private(set) var errorMessage: String? + + private let manager = CLLocationManager() + + override init() { + authorizationStatus = manager.authorizationStatus + super.init() + manager.delegate = self + manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation + manager.distanceFilter = 3 + manager.headingFilter = 2 + manager.activityType = .automotiveNavigation + manager.pausesLocationUpdatesAutomatically = false + } + + func requestPermission() { + manager.requestWhenInUseAuthorization() + } + + func start() { + if manager.authorizationStatus == .notDetermined { requestPermission() } + manager.startUpdatingLocation() + if CLLocationManager.headingAvailable() { manager.startUpdatingHeading() } + } + + func stop() { + manager.stopUpdatingLocation() + manager.stopUpdatingHeading() + } + + func setBackgroundNavigationEnabled(_ enabled: Bool) { + manager.allowsBackgroundLocationUpdates = enabled + manager.showsBackgroundLocationIndicator = enabled + } + + func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) { + authorizationStatus = manager.authorizationStatus + } + + func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { + guard let newest = locations.last else { return } + location = newest + } + + func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) { + heading = newHeading + } + + func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { + errorMessage = error.localizedDescription + } +} + +struct ResolvedDestination: Identifiable, Hashable { + let id = UUID() + let name: String + let coordinate: CLLocationCoordinate2D + + static func == (lhs: ResolvedDestination, rhs: ResolvedDestination) -> Bool { + lhs.name == rhs.name && + lhs.coordinate.latitude == rhs.coordinate.latitude && + lhs.coordinate.longitude == rhs.coordinate.longitude + } + + func hash(into hasher: inout Hasher) { + hasher.combine(name) + hasher.combine(coordinate.latitude) + hasher.combine(coordinate.longitude) + } +} + +enum RouteResolver { + static func resolve(_ input: String, near location: CLLocation?) async throws -> ResolvedDestination { + let trimmed = input.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { throw NavigationError.emptyDestination } + + if let coordinate = coordinate(from: trimmed) { + return .init(name: trimmed, coordinate: coordinate) + } + + if let url = URL(string: trimmed), url.scheme != nil { + if let coordinate = coordinate(from: url.absoluteString) { + return .init(name: url.host ?? "Shared destination", coordinate: coordinate) + } + let components = URLComponents(url: url, resolvingAgainstBaseURL: false) + let keys = Set(["q", "query", "destination", "daddr", "ll"]) + if let value = components?.queryItems?.first(where: { keys.contains($0.name.lowercased()) })?.value, + !value.isEmpty { + if let coordinate = coordinate(from: value) { + return .init(name: value, coordinate: coordinate) + } + return try await localSearch(value, near: location) + } + } + + return try await localSearch(trimmed, near: location) + } + + private static func localSearch(_ query: String, near location: CLLocation?) async throws -> ResolvedDestination { + let request = MKLocalSearch.Request() + request.naturalLanguageQuery = query + if let location { + request.region = MKCoordinateRegion( + center: location.coordinate, + latitudinalMeters: 100_000, + longitudinalMeters: 100_000 + ) + } + let response = try await MKLocalSearch(request: request).start() + guard let item = response.mapItems.first else { throw NavigationError.destinationNotFound } + return .init(name: item.name ?? query, coordinate: item.placemark.coordinate) + } + + private static func coordinate(from text: String) -> CLLocationCoordinate2D? { + let pattern = #"(-?\d{1,2}(?:\.\d+)?)\s*[, ]\s*(-?\d{1,3}(?:\.\d+)?)"# + guard let regex = try? NSRegularExpression(pattern: pattern), + let match = regex.firstMatch(in: text, range: NSRange(text.startIndex..., in: text)), + let latRange = Range(match.range(at: 1), in: text), + let lonRange = Range(match.range(at: 2), in: text), + let latitude = Double(text[latRange]), + let longitude = Double(text[lonRange]), + (-90...90).contains(latitude), + (-180...180).contains(longitude) else { return nil } + return CLLocationCoordinate2D(latitude: latitude, longitude: longitude) + } +} + +@MainActor +final class NavigationViewModel: ObservableObject { + @Published var destinationInput = "" + @Published private(set) var destination: ResolvedDestination? + @Published private(set) var route: MKRoute? + @Published private(set) var activeStepIndex = 0 + @Published private(set) var isCalculating = false + @Published private(set) var isRecalculating = false + @Published private(set) var recalculationCount = 0 + @Published private(set) var distanceFromRouteMeters: CLLocationDistance = 0 + @Published private(set) var errorMessage: String? + @Published private(set) var projectionState = ProjectionUIState() + + let locationService: NavigationLocationService + private var cancellables: Set = [] + private var lastRecalculationAt = Date.distantPast + + private let deviationThresholdMeters: CLLocationDistance = 75 + private let recalculationCooldown: TimeInterval = 20 + + init(locationService: NavigationLocationService = NavigationLocationService()) { + self.locationService = locationService + locationService.$location + .sink { [weak self] location in self?.handleLocation(location) } + .store(in: &cancellables) + } + + func startLocation() { locationService.start() } + func stopLocation() { locationService.stop() } + + func calculateRoute() async { + isCalculating = true + errorMessage = nil + defer { isCalculating = false } + + do { + let resolved = try await RouteResolver.resolve(destinationInput, near: locationService.location) + destination = resolved + guard let originLocation = locationService.location else { + throw NavigationError.locationUnavailable + } + + let newRoute = try await directions(from: originLocation, to: resolved) + apply(route: newRoute, from: originLocation) + } catch { + errorMessage = error.localizedDescription + } + } + + func clearRoute() { + route = nil + destination = nil + activeStepIndex = 0 + recalculationCount = 0 + distanceFromRouteMeters = 0 + errorMessage = nil + projectionState = ProjectionUIState() + } + + func openInAppleMaps() { + guard let destination else { return } + let item = MKMapItem(placemark: MKPlacemark(coordinate: destination.coordinate)) + item.name = destination.name + item.openInMaps(launchOptions: [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving]) + } + + func importURL(_ url: URL) { + if url.scheme?.lowercased() == "ridedash" { + let components = URLComponents(url: url, resolvingAgainstBaseURL: false) + if let value = components?.queryItems?.first(where: { + ["url", "q", "destination"].contains($0.name.lowercased()) + })?.value { + destinationInput = value + } + } else { + destinationInput = url.absoluteString + } + } + + func handleDashButton(_ button: DashButton) { + guard let route, !route.steps.isEmpty else { return } + let lastIndex = route.steps.count - 1 + switch button { + case .left: + activeStepIndex = max(firstUsableStep(in: route), activeStepIndex - 1) + case .right: + activeStepIndex = min(lastIndex, activeStepIndex + 1) + case .down, .click: + if let location = locationService.location { + activeStepIndex = nearestUpcomingStep(in: route, to: location) + } + } + rebuildProjectionState(location: locationService.location) + } + + private func handleLocation(_ location: CLLocation?) { + guard let location else { return } + + if let route, !route.steps.isEmpty { + let suggested = nearestUpcomingStep(in: route, to: location) + if suggested >= activeStepIndex { activeStepIndex = suggested } + + distanceFromRouteMeters = distanceFromRoute(location, route: route) + if distanceFromRouteMeters > deviationThresholdMeters { + Task { [weak self] in + await self?.recalculateIfNeeded(from: location) + } + } + } + + rebuildProjectionState(location: location) + } + + private func recalculateIfNeeded(from location: CLLocation) async { + guard !isRecalculating, + let destination, + Date().timeIntervalSince(lastRecalculationAt) >= recalculationCooldown else { return } + + isRecalculating = true + lastRecalculationAt = .now + errorMessage = nil + defer { isRecalculating = false } + + do { + let newRoute = try await directions(from: location, to: destination) + recalculationCount += 1 + apply(route: newRoute, from: location) + } catch { + errorMessage = "Route recalculation failed: \(error.localizedDescription)" + rebuildProjectionState(location: location, forcedStatus: "Off route · reconnecting route") + } + } + + private func directions(from origin: CLLocation, to destination: ResolvedDestination) async throws -> MKRoute { + let request = MKDirections.Request() + request.source = MKMapItem(placemark: MKPlacemark(coordinate: origin.coordinate)) + request.destination = MKMapItem(placemark: MKPlacemark(coordinate: destination.coordinate)) + request.transportType = .automobile + request.requestsAlternateRoutes = false + + let response = try await MKDirections(request: request).calculate() + guard let route = response.routes.first else { throw NavigationError.routeNotFound } + return route + } + + private func apply(route: MKRoute, from origin: CLLocation) { + self.route = route + activeStepIndex = firstUsableStep(in: route) + distanceFromRouteMeters = 0 + rebuildProjectionState(location: origin) + } + + private func rebuildProjectionState(location: CLLocation?, forcedStatus: String? = nil) { + guard let route, let destination else { + projectionState = ProjectionUIState( + destination: destination?.name ?? "RideDash", + speedKph: max(0, (location?.speed ?? 0) * 3.6), + gpsAccuracy: location?.horizontalAccuracy, + statusMessage: forcedStatus + ) + return + } + + let step: MKRoute.Step? = route.steps.isEmpty + ? nil + : route.steps[min(max(0, activeStepIndex), route.steps.count - 1)] + let instruction = (step?.instructions.isEmpty == false) ? (step?.instructions ?? "Continue") : "Continue" + let distanceToStep = distanceToEnd(of: step, from: location) ?? step?.distance ?? 0 + + let remainingDistance = remainingRouteDistance(route, from: location) + let ratio = route.distance > 0 ? min(1, max(0, remainingDistance / route.distance)) : 1 + let remainingTravelTime = route.expectedTravelTime * ratio + let etaDate = Date().addingTimeInterval(remainingTravelTime) + let etaFormatter = DateFormatter() + etaFormatter.dateFormat = "HH:mm" + + var status = forcedStatus + if status == nil, isRecalculating { status = "Recalculating route…" } + if status == nil, (location?.horizontalAccuracy ?? 0) > 50 { status = "GPS accuracy degraded" } + if status == nil, distanceFromRouteMeters > deviationThresholdMeters { status = "Off route" } + + projectionState = ProjectionUIState( + destination: destination.name, + maneuver: instruction, + distanceToManeuver: Self.formatDistance(distanceToStep), + eta: etaFormatter.string(from: etaDate), + remainingDistance: Self.formatDistance(remainingDistance), + speedKph: max(0, (location?.speed ?? 0) * 3.6), + gpsAccuracy: location?.horizontalAccuracy, + isCalibrationGrid: false, + statusMessage: status + ) + } + + private func firstUsableStep(in route: MKRoute?) -> Int { + guard let route, !route.steps.isEmpty else { return 0 } + return route.steps.firstIndex(where: { !$0.instructions.isEmpty && $0.distance > 0 }) ?? 0 + } + + private func nearestUpcomingStep(in route: MKRoute, to location: CLLocation) -> Int { + guard !route.steps.isEmpty else { return 0 } + let start = min(max(0, activeStepIndex), route.steps.count - 1) + var bestIndex = start + var bestDistance = CLLocationDistance.greatestFiniteMagnitude + + for index in start.. 0 else { continue } + let points = step.polyline.points() + let endPoint = points[step.polyline.pointCount - 1].coordinate + let endLocation = CLLocation(latitude: endPoint.latitude, longitude: endPoint.longitude) + let distance = location.distance(from: endLocation) + if distance < bestDistance { + bestDistance = distance + bestIndex = index + } + if distance < 30, index + 1 < route.steps.count { return index + 1 } + } + return bestIndex + } + + private func remainingRouteDistance(_ route: MKRoute, from location: CLLocation?) -> CLLocationDistance { + guard !route.steps.isEmpty else { return route.distance } + let index = min(max(0, activeStepIndex), route.steps.count - 1) + let currentStepRemaining = distanceToEnd(of: route.steps[index], from: location) ?? route.steps[index].distance + let future = route.steps.dropFirst(index + 1).reduce(0.0) { $0 + $1.distance } + return max(0, currentStepRemaining + future) + } + + private func distanceToEnd(of step: MKRoute.Step?, from location: CLLocation?) -> CLLocationDistance? { + guard let step, let location, step.polyline.pointCount > 0 else { return nil } + let points = step.polyline.points() + let coordinate = points[step.polyline.pointCount - 1].coordinate + return location.distance(from: CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)) + } + + private func distanceFromRoute(_ location: CLLocation, route: MKRoute) -> CLLocationDistance { + let polyline = route.polyline + guard polyline.pointCount > 1 else { return .greatestFiniteMagnitude } + + let target = MKMapPoint(location.coordinate) + let points = polyline.points() + var best = CLLocationDistance.greatestFiniteMagnitude + + for index in 0..<(polyline.pointCount - 1) { + let a = points[index] + let b = points[index + 1] + let dx = b.x - a.x + let dy = b.y - a.y + let lengthSquared = dx * dx + dy * dy + + let t: Double + if lengthSquared <= .ulpOfOne { + t = 0 + } else { + t = min(1, max(0, ((target.x - a.x) * dx + (target.y - a.y) * dy) / lengthSquared)) + } + + let projected = MKMapPoint(x: a.x + t * dx, y: a.y + t * dy) + best = min(best, target.distance(to: projected)) + } + return best + } + + private static func formatDistance(_ meters: CLLocationDistance) -> String { + let safeMeters = max(0, meters) + if safeMeters < 1_000 { return "\(Int(safeMeters.rounded())) m" } + return String(format: "%.1f km", safeMeters / 1_000) + } +} + +enum NavigationError: LocalizedError { + case emptyDestination + case destinationNotFound + case locationUnavailable + case routeNotFound + + var errorDescription: String? { + switch self { + case .emptyDestination: return "Enter a destination, coordinate, or map URL." + case .destinationNotFound: return "The destination could not be resolved." + case .locationUnavailable: return "Current location is not available yet." + case .routeNotFound: return "MapKit did not return a driving route." + } + } +} diff --git a/RideDash/PrivacyInfo.xcprivacy b/RideDash/PrivacyInfo.xcprivacy new file mode 100644 index 0000000..937278f --- /dev/null +++ b/RideDash/PrivacyInfo.xcprivacy @@ -0,0 +1,23 @@ + + + + + NSPrivacyTracking + + NSPrivacyTrackingDomains + + NSPrivacyCollectedDataTypes + + NSPrivacyAccessedAPITypes + + + NSPrivacyAccessedAPIType + NSPrivacyAccessedAPICategoryUserDefaults + NSPrivacyAccessedAPITypeReasons + + CA92.1 + + + + + diff --git a/RideDash/ProjectionCore/ProjectionCore.swift b/RideDash/ProjectionCore/ProjectionCore.swift new file mode 100644 index 0000000..f93e2e5 --- /dev/null +++ b/RideDash/ProjectionCore/ProjectionCore.swift @@ -0,0 +1,560 @@ +import CoreGraphics +import CoreMedia +import CoreVideo +import Foundation +import UIKit +import VideoToolbox + +struct ProjectionUIState: Sendable, Hashable { + var destination = "RideDash" + var maneuver = "Continue" + var distanceToManeuver = "--" + var eta = "--" + var remainingDistance = "--" + var speedKph: Double = 0 + var gpsAccuracy: Double? + var isCalibrationGrid = false + var statusMessage: String? +} + +// MARK: - 526 × 300 renderer + +final class DashFrameRenderer { + let width: Int + let height: Int + + init(width: Int = 526, height: Int = 300) { + self.width = width + self.height = height + } + + func render(_ state: ProjectionUIState) throws -> CVPixelBuffer { + var buffer: CVPixelBuffer? + let attributes: [CFString: Any] = [ + kCVPixelBufferCGImageCompatibilityKey: true, + kCVPixelBufferCGBitmapContextCompatibilityKey: true, + kCVPixelBufferIOSurfacePropertiesKey: [:] + ] + let status = CVPixelBufferCreate( + kCFAllocatorDefault, + width, + height, + kCVPixelFormatType_32BGRA, + attributes as CFDictionary, + &buffer + ) + guard status == kCVReturnSuccess, let buffer else { + throw ProjectionError.pixelBufferCreationFailed(status) + } + + CVPixelBufferLockBaseAddress(buffer, []) + defer { CVPixelBufferUnlockBaseAddress(buffer, []) } + guard let base = CVPixelBufferGetBaseAddress(buffer) else { + throw ProjectionError.pixelBufferMissingBaseAddress + } + + guard let context = CGContext( + data: base, + width: width, + height: height, + bitsPerComponent: 8, + bytesPerRow: CVPixelBufferGetBytesPerRow(buffer), + space: CGColorSpaceCreateDeviceRGB(), + bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue + ) else { + throw ProjectionError.contextCreationFailed + } + + context.setFillColor(UIColor.black.cgColor) + context.fill(CGRect(x: 0, y: 0, width: CGFloat(width), height: CGFloat(height))) + UIGraphicsPushContext(context) + defer { UIGraphicsPopContext() } + + if state.isCalibrationGrid { + drawCalibration(context) + } else { + drawNavigation(state) + } + return buffer + } + + private func drawCalibration(_ context: CGContext) { + let w = CGFloat(width) + let h = CGFloat(height) + context.setStrokeColor(UIColor.white.withAlphaComponent(0.32).cgColor) + context.setLineWidth(1) + stride(from: 0, through: width, by: 25).forEach { x in + context.move(to: CGPoint(x: CGFloat(x), y: 0)) + context.addLine(to: CGPoint(x: CGFloat(x), y: h)) + } + stride(from: 0, through: height, by: 25).forEach { y in + context.move(to: CGPoint(x: 0, y: CGFloat(y))) + context.addLine(to: CGPoint(x: w, y: CGFloat(y))) + } + context.strokePath() + + context.setStrokeColor(UIColor.systemOrange.cgColor) + context.setLineWidth(3) + context.strokeEllipse(in: CGRect(x: 7, y: 7, width: w - 14, height: h - 14)) + context.move(to: CGPoint(x: w / 2, y: 0)) + context.addLine(to: CGPoint(x: w / 2, y: h)) + context.move(to: CGPoint(x: 0, y: h / 2)) + context.addLine(to: CGPoint(x: w, y: h / 2)) + context.strokePath() + + drawText( + "526 × 300 CALIBRATION", + frame: CGRect(x: 70, y: 124, width: w - 140, height: 42), + size: 24, + weight: .bold, + alignment: .center + ) + } + + private func drawNavigation(_ state: ProjectionUIState) { + let w = CGFloat(width) + let h = CGFloat(height) + let safe = CGRect(x: 34, y: 22, width: w - 68, height: h - 44) + + drawText( + state.destination, + frame: CGRect(x: safe.minX + 12, y: safe.minY + 2, width: safe.width - 24, height: 30), + size: 18, + weight: .semibold, + alignment: .center, + color: .systemGray3 + ) + + let card = CGRect(x: safe.minX + 34, y: safe.minY + 40, width: safe.width - 68, height: 104) + UIColor(white: 0.10, alpha: 1).setFill() + UIBezierPath(roundedRect: card, cornerRadius: 24).fill() + + drawText( + state.maneuver, + frame: CGRect(x: card.minX + 16, y: card.minY + 13, width: card.width - 32, height: 42), + size: 30, + weight: .bold, + alignment: .center + ) + drawText( + state.distanceToManeuver, + frame: CGRect(x: card.minX + 16, y: card.minY + 58, width: card.width - 32, height: 32), + size: 24, + weight: .semibold, + alignment: .center, + color: .systemOrange + ) + + drawMetric(title: "ETA", value: state.eta, x: safe.minX + 22, y: safe.maxY - 70, width: 105) + drawMetric(title: "LEFT", value: state.remainingDistance, x: safe.midX - 52, y: safe.maxY - 70, width: 105) + drawMetric(title: "SPEED", value: String(Int(state.speedKph.rounded())), x: safe.maxX - 127, y: safe.maxY - 70, width: 105) + + if let status = state.statusMessage { + drawText( + status, + frame: CGRect(x: 80, y: h - 24, width: w - 160, height: 17), + size: 11, + weight: .medium, + alignment: .center, + color: .systemYellow + ) + } + } + + private func drawMetric(title: String, value: String, x: CGFloat, y: CGFloat, width: CGFloat) { + drawText(title, frame: CGRect(x: x, y: y, width: width, height: 17), size: 11, weight: .semibold, alignment: .center, color: .systemGray) + drawText(value, frame: CGRect(x: x, y: y + 16, width: width, height: 29), size: 19, weight: .bold, alignment: .center) + } + + private func drawText( + _ value: String, + frame: CGRect, + size: CGFloat, + weight: UIFont.Weight, + alignment: NSTextAlignment, + color: UIColor = .white + ) { + let style = NSMutableParagraphStyle() + style.alignment = alignment + style.lineBreakMode = .byTruncatingTail + (value as NSString).draw( + in: frame, + withAttributes: [ + .font: UIFont.systemFont(ofSize: size, weight: weight), + .foregroundColor: color, + .paragraphStyle: style + ] + ) + } +} + +// MARK: - H.264 encoder + +struct H264NALUnit: Sendable, Hashable { + let bytes: Data + let isParameterSet: Bool + + var type: UInt8 { (bytes.first ?? 0) & 0x1F } +} + +final class H264Encoder { + var onNALUnits: (([H264NALUnit], CMTime) -> Void)? + + private let fps: Int + private let bitrate: Int + private var session: VTCompressionSession? + + init(width: Int, height: Int, fps: Int, bitrateKbps: Int) throws { + self.fps = max(1, fps) + self.bitrate = max(64, bitrateKbps) * 1_000 + try configure(width: Int32(width), height: Int32(height)) + } + + deinit { + if let session { + VTCompressionSessionCompleteFrames(session, untilPresentationTimeStamp: CMTime.invalid) + VTCompressionSessionInvalidate(session) + } + } + + func encode(_ buffer: CVPixelBuffer, pts: CMTime) throws { + guard let session else { throw ProjectionError.encoderNotReady } + var flags = VTEncodeInfoFlags() + let status = VTCompressionSessionEncodeFrame( + session, + imageBuffer: buffer, + presentationTimeStamp: pts, + duration: CMTime(value: 1, timescale: CMTimeScale(fps)), + frameProperties: nil, + sourceFrameRefcon: nil, + infoFlagsOut: &flags + ) + guard status == noErr else { throw ProjectionError.videoToolbox(status) } + } + + private func configure(width: Int32, height: Int32) throws { + var created: VTCompressionSession? + let status = VTCompressionSessionCreate( + allocator: kCFAllocatorDefault, + width: width, + height: height, + codecType: kCMVideoCodecType_H264, + encoderSpecification: nil, + imageBufferAttributes: nil, + compressedDataAllocator: nil, + outputCallback: Self.outputCallback, + refcon: Unmanaged.passUnretained(self).toOpaque(), + compressionSessionOut: &created + ) + guard status == noErr, let created else { throw ProjectionError.videoToolbox(status) } + session = created + + try set(kVTCompressionPropertyKey_RealTime, kCFBooleanTrue) + try set(kVTCompressionPropertyKey_ProfileLevel, kVTProfileLevel_H264_Baseline_AutoLevel) + try set(kVTCompressionPropertyKey_AllowFrameReordering, kCFBooleanFalse) + try set(kVTCompressionPropertyKey_AverageBitRate, NSNumber(value: bitrate)) + try set(kVTCompressionPropertyKey_ExpectedFrameRate, NSNumber(value: fps)) + try set(kVTCompressionPropertyKey_MaxKeyFrameInterval, NSNumber(value: fps * 2)) + let rateLimits = [NSNumber(value: bitrate / 8), NSNumber(value: 1)] as CFArray + try set(kVTCompressionPropertyKey_DataRateLimits, rateLimits) + + let prepare = VTCompressionSessionPrepareToEncodeFrames(created) + guard prepare == noErr else { throw ProjectionError.videoToolbox(prepare) } + } + + private func set(_ key: CFString, _ value: CFTypeRef) throws { + guard let session else { throw ProjectionError.encoderNotReady } + let status = VTSessionSetProperty(session, key: key, value: value) + guard status == noErr else { throw ProjectionError.videoToolbox(status) } + } + + private static let outputCallback: VTCompressionOutputCallback = { refcon, _, status, _, sampleBuffer in + guard status == noErr, + let refcon, + let sampleBuffer, + CMSampleBufferDataIsReady(sampleBuffer) else { return } + let encoder = Unmanaged.fromOpaque(refcon).takeUnretainedValue() + encoder.consume(sampleBuffer) + } + + private func consume(_ sampleBuffer: CMSampleBuffer) { + var units: [H264NALUnit] = [] + + // Ask VideoToolbox for the SPS/PPS matching the current encoder output. + if let format = CMSampleBufferGetFormatDescription(sampleBuffer) { + for index in 0..<2 { + var pointer: UnsafePointer? + var size = 0 + var setCount = 0 + var headerLength: Int32 = 0 + let result = CMVideoFormatDescriptionGetH264ParameterSetAtIndex( + format, + parameterSetIndex: index, + parameterSetPointerOut: &pointer, + parameterSetSizeOut: &size, + parameterSetCountOut: &setCount, + nalUnitHeaderLengthOut: &headerLength + ) + if result == noErr, let pointer, size > 0 { + units.append(H264NALUnit(bytes: Data(bytes: pointer, count: size), isParameterSet: true)) + } + } + } + + guard let block = CMSampleBufferGetDataBuffer(sampleBuffer) else { return } + var totalLength = 0 + var contiguousLength = 0 + var pointer: UnsafeMutablePointer? + let pointerStatus = CMBlockBufferGetDataPointer( + block, + atOffset: 0, + lengthAtOffsetOut: &contiguousLength, + totalLengthOut: &totalLength, + dataPointerOut: &pointer + ) + guard pointerStatus == kCMBlockBufferNoErr, let pointer else { return } + + let bytes = UnsafeRawPointer(pointer).assumingMemoryBound(to: UInt8.self) + var offset = 0 + while offset + 4 <= totalLength { + let length = Int(bytes[offset]) << 24 | + Int(bytes[offset + 1]) << 16 | + Int(bytes[offset + 2]) << 8 | + Int(bytes[offset + 3]) + offset += 4 + guard length > 0, offset + length <= totalLength else { break } + units.append( + H264NALUnit( + bytes: Data(bytes: bytes.advanced(by: offset), count: length), + isParameterSet: false + ) + ) + offset += length + } + + if !units.isEmpty { + onNALUnits?(units, CMSampleBufferGetPresentationTimeStamp(sampleBuffer)) + } + } +} + +// MARK: - Dash-compatible H.264/RTP + +final class H264RTPPacketizer { + private var sequence = UInt16.random(in: 0...UInt16.max) + private var timestamp = UInt32.random(in: 0...UInt32.max) + private let ssrc = UInt32.random(in: 1...UInt32.max) + private let payloadType: UInt8 = 96 + private let timestampStep: UInt32 + private let maxPayload: Int + + private var sps: Data? + private var pps: Data? + + /// The working public reference uses ~1380 bytes. Keep it configurable if firmware needs tuning. + init(fps: Int, maxPayload: Int = 1_380) { + timestampStep = UInt32(90_000 / max(1, fps)) + self.maxPayload = max(300, maxPayload) + } + + func packetize(_ units: [H264NALUnit]) -> [Data] { + var frameNALs: [Data] = [] + + for unit in units where !unit.bytes.isEmpty { + switch unit.type { + case 7: + sps = unit.bytes + case 8: + pps = unit.bytes + case 6, 9: + // Drop SEI/AUD. The reference does not send them to the embedded decoder. + continue + case 5: + if let sps, let pps { + var bundled = Data() + bundled.append(sps) + bundled.append(contentsOf: [0x00, 0x00, 0x00, 0x01]) + bundled.append(pps) + bundled.append(contentsOf: [0x00, 0x00, 0x00, 0x01]) + bundled.append(unit.bytes) + frameNALs.append(bundled) + } else { + frameNALs.append(unit.bytes) + } + default: + frameNALs.append(unit.bytes) + } + } + + guard !frameNALs.isEmpty else { return [] } + var plannedPayloads: [Data] = [] + for nal in frameNALs { + plannedPayloads.append(contentsOf: payloads(for: nal)) + } + + var result: [Data] = [] + result.reserveCapacity(plannedPayloads.count) + for index in plannedPayloads.indices { + result.append(makeRTPPacket(payload: plannedPayloads[index], marker: index == plannedPayloads.count - 1)) + } + timestamp &+= timestampStep + return result + } + + private func payloads(for nal: Data) -> [Data] { + guard let first = nal.first else { return [] } + if nal.count <= maxPayload { return [nal] } + + let fuIndicator = (first & 0xE0) | 28 + let nalType = first & 0x1F + let body = Data(nal.dropFirst()) + let chunkSize = maxPayload - 2 + var result: [Data] = [] + var offset = 0 + + while offset < body.count { + let end = min(body.count, offset + chunkSize) + let startBit: UInt8 = offset == 0 ? 0x80 : 0 + let endBit: UInt8 = end == body.count ? 0x40 : 0 + let fuHeader = startBit | endBit | nalType + var payload = Data([fuIndicator, fuHeader]) + payload.append(body.subdata(in: offset.. Data { + var packet = Data(capacity: 12 + payload.count) + packet.append(0x80) // RTP v2 + packet.append((marker ? 0x80 : 0) | payloadType) + appendBigEndian(sequence, to: &packet) + appendBigEndian(timestamp, to: &packet) + appendBigEndian(ssrc, to: &packet) + packet.append(payload) + sequence &+= 1 + return packet + } + + private func appendBigEndian(_ value: T, to data: inout Data) { + var big = value.bigEndian + withUnsafeBytes(of: &big) { data.append(contentsOf: $0) } + } +} + +// MARK: - Renderer → encoder → RTP → UDP + +@MainActor +final class ProjectionStreamer: ObservableObject { + enum State: Equatable { + case stopped + case starting + case streaming + case failed(String) + } + + @Published private(set) var state: State = .stopped + @Published private(set) var renderedFrames = 0 + @Published private(set) var sentRTPPackets = 0 + @Published private(set) var encodedBytes = 0 + + private var renderTask: Task? + private var encoder: H264Encoder? + private var packetizer: H264RTPPacketizer? + private var renderer = DashFrameRenderer() + + func start( + coordinator: DashSessionCoordinator, + profile: DashProtocolProfile, + stateProvider: @escaping @MainActor () -> ProjectionUIState + ) throws { + stop() + state = .starting + renderedFrames = 0 + sentRTPPackets = 0 + encodedBytes = 0 + + renderer = DashFrameRenderer(width: profile.renderWidth, height: profile.renderHeight) + let encoder = try H264Encoder( + width: profile.renderWidth, + height: profile.renderHeight, + fps: profile.fps, + bitrateKbps: profile.bitrateKbps + ) + let packetizer = H264RTPPacketizer(fps: profile.fps) + self.encoder = encoder + self.packetizer = packetizer + + encoder.onNALUnits = { [weak self, weak coordinator] units, _ in + guard let self, let coordinator else { return } + let packets = packetizer.packetize(units) + let bytes = units.reduce(0) { $0 + $1.bytes.count } + Task { @MainActor in + self.encodedBytes += bytes + for packet in packets { + do { + try await coordinator.transport.sendVideo(packet) + self.sentRTPPackets += 1 + } catch { + self.state = .failed(error.localizedDescription) + coordinator.log.append(error.localizedDescription, category: "rtp", level: .error) + return + } + } + } + } + + coordinator.beginProjectionHeartbeat() + state = .streaming + let fps = max(1, profile.fps) + let frameInterval = 1.0 / Double(fps) + + renderTask = Task { [weak self, weak coordinator] in + guard let coordinator else { return } + var frameNumber: Int64 = 0 + while !Task.isCancelled { + guard let self else { return } + do { + let pixelBuffer = try self.renderer.render(stateProvider()) + let pts = CMTime(value: frameNumber, timescale: CMTimeScale(fps)) + try encoder.encode(pixelBuffer, pts: pts) + self.renderedFrames += 1 + frameNumber += 1 + } catch { + self.state = .failed(error.localizedDescription) + coordinator.log.append(error.localizedDescription, category: "encoder", level: .error) + return + } + try? await Task.sleep(for: .seconds(frameInterval)) + } + } + } + + func stop() { + renderTask?.cancel() + renderTask = nil + encoder = nil + packetizer = nil + if case .failed = state { return } + state = .stopped + } +} + +enum ProjectionError: LocalizedError { + case pixelBufferCreationFailed(CVReturn) + case pixelBufferMissingBaseAddress + case contextCreationFailed + case encoderNotReady + case videoToolbox(OSStatus) + + var errorDescription: String? { + switch self { + case .pixelBufferCreationFailed(let status): return "Pixel buffer creation failed (\(status))." + case .pixelBufferMissingBaseAddress: return "Pixel buffer has no writable base address." + case .contextCreationFailed: return "Could not create the dash graphics context." + case .encoderNotReady: return "H.264 encoder is not ready." + case .videoToolbox(let status): return "VideoToolbox returned status \(status)." + } + } +} diff --git a/RideDash/RideDash.entitlements b/RideDash/RideDash.entitlements new file mode 100644 index 0000000..b8245cd --- /dev/null +++ b/RideDash/RideDash.entitlements @@ -0,0 +1,8 @@ + + + + + com.apple.developer.networking.HotspotConfiguration + + + diff --git a/RideDashShare/Info.plist b/RideDashShare/Info.plist new file mode 100644 index 0000000..fb81492 --- /dev/null +++ b/RideDashShare/Info.plist @@ -0,0 +1,39 @@ + + + + + CFBundleDisplayName + RideDash + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + XPC! + CFBundleShortVersionString + $(MARKETING_VERSION) + CFBundleVersion + $(CURRENT_PROJECT_VERSION) + NSExtension + + NSExtensionAttributes + + NSExtensionActivationRule + + NSExtensionActivationSupportsText + + NSExtensionActivationSupportsWebURLWithMaxCount + 1 + + + NSExtensionPointIdentifier + com.apple.share-services + NSExtensionPrincipalClass + $(PRODUCT_MODULE_NAME).ShareViewController + + + diff --git a/RideDashShare/ShareViewController.swift b/RideDashShare/ShareViewController.swift new file mode 100644 index 0000000..a9d24c7 --- /dev/null +++ b/RideDashShare/ShareViewController.swift @@ -0,0 +1,71 @@ +import UIKit +import UniformTypeIdentifiers + +final class ShareViewController: UIViewController { + private var hasCompleted = false + + override func viewDidAppear(_ animated: Bool) { + super.viewDidAppear(animated) + processSharedContent() + } + + private func processSharedContent() { + guard !hasCompleted, + let items = extensionContext?.inputItems as? [NSExtensionItem] else { + complete() + return + } + + let providers = items.flatMap { $0.attachments ?? [] } + if let provider = providers.first(where: { $0.hasItemConformingToTypeIdentifier(UTType.url.identifier) }) { + provider.loadItem(forTypeIdentifier: UTType.url.identifier, options: nil) { [weak self] value, _ in + let text: String? + if let url = value as? URL { + text = url.absoluteString + } else if let string = value as? String { + text = string + } else { + text = nil + } + DispatchQueue.main.async { self?.openRideDash(with: text) } + } + return + } + + if let provider = providers.first(where: { $0.hasItemConformingToTypeIdentifier(UTType.plainText.identifier) }) { + provider.loadItem(forTypeIdentifier: UTType.plainText.identifier, options: nil) { [weak self] value, _ in + DispatchQueue.main.async { + self?.openRideDash(with: value as? String) + } + } + return + } + + complete() + } + + private func openRideDash(with sharedValue: String?) { + guard let sharedValue, + !sharedValue.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, + var components = URLComponents(string: "ridedash://route") else { + complete() + return + } + + components.queryItems = [URLQueryItem(name: "url", value: sharedValue)] + guard let url = components.url else { + complete() + return + } + + extensionContext?.open(url) { [weak self] _ in + self?.complete() + } + } + + private func complete() { + guard !hasCompleted else { return } + hasCompleted = true + extensionContext?.completeRequest(returningItems: nil) + } +}