From 40cadf9f1d5a266db8509340bbdf7495fda642c5 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 16:35:18 +0530 Subject: [PATCH 001/112] feat: add Phase 1 connectivity and diagnostics foundation --- .gitignore | 23 ++ Docs/HARDWARE_TEST_MATRIX.md | 32 ++ Docs/SAFETY_SCOPE.md | 34 ++ RideDash.xcodeproj/project.pbxproj | 316 ++++++++++++++++++ RideDash/App/RideDashApp.swift | 10 + RideDash/App/RootView.swift | 13 + RideDash/DashConnectivity/DashTransport.swift | 89 +++++ .../LocalNetworkMonitor.swift | 55 +++ .../DashConnectivity/TripperWiFiManager.swift | 83 +++++ RideDash/Diagnostics/DiagnosticLog.swift | 66 ++++ .../Diagnostics/DiagnosticsView.swift | 178 ++++++++++ RideDash/Models/DashTestProfile.swift | 22 ++ RideDash/RideDash.entitlements | 8 + 13 files changed, 929 insertions(+) create mode 100644 .gitignore create mode 100644 Docs/HARDWARE_TEST_MATRIX.md create mode 100644 Docs/SAFETY_SCOPE.md create mode 100644 RideDash.xcodeproj/project.pbxproj create mode 100644 RideDash/App/RideDashApp.swift create mode 100644 RideDash/App/RootView.swift create mode 100644 RideDash/DashConnectivity/DashTransport.swift create mode 100644 RideDash/DashConnectivity/LocalNetworkMonitor.swift create mode 100644 RideDash/DashConnectivity/TripperWiFiManager.swift create mode 100644 RideDash/Diagnostics/DiagnosticLog.swift create mode 100644 RideDash/Features/Diagnostics/DiagnosticsView.swift create mode 100644 RideDash/Models/DashTestProfile.swift create mode 100644 RideDash/RideDash.entitlements 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/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/RideDash.xcodeproj/project.pbxproj b/RideDash.xcodeproj/project.pbxproj new file mode 100644 index 0000000..b21fab7 --- /dev/null +++ b/RideDash.xcodeproj/project.pbxproj @@ -0,0 +1,316 @@ +// !$*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 */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + 000000000000000000000003 /* RideDash.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = RideDash.app; 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 = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 000000000000000000000302 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 000000000000000000000010 = { + isa = PBXGroup; + children = ( + 000000000000000000000011 /* RideDash */, + 000000000000000000000017 /* Products */, + ); + sourceTree = ""; + }; + 000000000000000000000011 /* RideDash */ = { + isa = PBXGroup; + children = ( + 000000000000000000000012 /* App */, + 000000000000000000000013 /* Features */, + 000000000000000000000014 /* DashConnectivity */, + 000000000000000000000015 /* Diagnostics */, + 000000000000000000000016 /* Models */, + 000000000000000000000109 /* RideDash.entitlements */, + ); + path = RideDash; + sourceTree = ""; + }; + 000000000000000000000012 /* App */ = { + isa = PBXGroup; + children = ( + 000000000000000000000101 /* RideDashApp.swift */, + 000000000000000000000102 /* RootView.swift */, + ); + path = App; + sourceTree = ""; + }; + 000000000000000000000013 /* Features */ = { + isa = PBXGroup; + children = ( + 000000000000000000000018 /* Diagnostics */, + ); + path = Features; + sourceTree = ""; + }; + 000000000000000000000018 /* Diagnostics */ = { + isa = PBXGroup; + children = ( + 000000000000000000000103 /* DiagnosticsView.swift */, + ); + path = Diagnostics; + sourceTree = ""; + }; + 000000000000000000000014 /* DashConnectivity */ = { + isa = PBXGroup; + children = ( + 000000000000000000000104 /* TripperWiFiManager.swift */, + 000000000000000000000105 /* LocalNetworkMonitor.swift */, + 000000000000000000000106 /* DashTransport.swift */, + ); + path = DashConnectivity; + sourceTree = ""; + }; + 000000000000000000000015 /* Diagnostics */ = { + isa = PBXGroup; + children = ( + 000000000000000000000107 /* DiagnosticLog.swift */, + ); + path = Diagnostics; + sourceTree = ""; + }; + 000000000000000000000016 /* Models */ = { + isa = PBXGroup; + children = ( + 000000000000000000000108 /* DashTestProfile.swift */, + ); + path = Models; + sourceTree = ""; + }; + 000000000000000000000017 /* Products */ = { + isa = PBXGroup; + children = ( + 000000000000000000000003 /* RideDash.app */, + ); + 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 */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = RideDash; + productName = RideDash; + productReference = 000000000000000000000003 /* RideDash.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 000000000000000000000001 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = 1; + LastSwiftUpdateCheck = 1600; + LastUpgradeCheck = 1600; + TargetAttributes = { + 000000000000000000000002 = { + 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 */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 000000000000000000000303 /* 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 */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase 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 = YES; + INFOPLIST_KEY_CFBundleDisplayName = RideDash; + INFOPLIST_KEY_NSLocalNetworkUsageDescription = "RideDash uses the local network to connect to a compatible motorcycle display for navigation and diagnostics."; + INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES; + INFOPLIST_KEY_UILaunchScreen_Generation = YES; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + MARKETING_VERSION = 0.1.0; + PRODUCT_BUNDLE_IDENTIFIER = dev.dagerott.RideDash; + PRODUCT_NAME = "$(TARGET_NAME)"; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator"; + SUPPORTS_MACCATALYST = NO; + SWIFT_EMIT_LOC_STRINGS = YES; + 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 = YES; + INFOPLIST_KEY_CFBundleDisplayName = RideDash; + INFOPLIST_KEY_NSLocalNetworkUsageDescription = "RideDash uses the local network to connect to a compatible motorcycle display for navigation and diagnostics."; + INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES; + INFOPLIST_KEY_UILaunchScreen_Generation = YES; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + MARKETING_VERSION = 0.1.0; + PRODUCT_BUNDLE_IDENTIFIER = dev.dagerott.RideDash; + PRODUCT_NAME = "$(TARGET_NAME)"; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator"; + SUPPORTS_MACCATALYST = NO; + 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; + }; +/* End XCConfigurationList section */ + }; + rootObject = 000000000000000000000001 /* Project object */; +} diff --git a/RideDash/App/RideDashApp.swift b/RideDash/App/RideDashApp.swift new file mode 100644 index 0000000..e4dc0bf --- /dev/null +++ b/RideDash/App/RideDashApp.swift @@ -0,0 +1,10 @@ +import SwiftUI + +@main +struct RideDashApp: App { + var body: some Scene { + WindowGroup { + RootView() + } + } +} diff --git a/RideDash/App/RootView.swift b/RideDash/App/RootView.swift new file mode 100644 index 0000000..3283271 --- /dev/null +++ b/RideDash/App/RootView.swift @@ -0,0 +1,13 @@ +import SwiftUI + +struct RootView: View { + var body: some View { + NavigationStack { + DiagnosticsView() + } + } +} + +#Preview { + RootView() +} diff --git a/RideDash/DashConnectivity/DashTransport.swift b/RideDash/DashConnectivity/DashTransport.swift new file mode 100644 index 0000000..578c741 --- /dev/null +++ b/RideDash/DashConnectivity/DashTransport.swift @@ -0,0 +1,89 @@ +import Foundation +import Network + +@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 route ready" + case .waiting(let reason): return "Waiting: \(reason)" + case .failed(let error): return "Failed: \(error)" + } + } + } + + @Published private(set) var state: State = .stopped + + private var connection: NWConnection? + private let queue = DispatchQueue(label: "dev.dagerott.RideDash.udp-transport") + + func start(host: String, port: UInt16) throws { + stop() + + guard !host.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + throw DashTransportError.invalidHost + } + guard let endpointPort = NWEndpoint.Port(rawValue: port) else { + throw DashTransportError.invalidPort + } + + state = .preparing + let connection = NWConnection( + host: NWEndpoint.Host(host), + port: endpointPort, + using: .udp + ) + self.connection = connection + + connection.stateUpdateHandler = { [weak self] newState in + Task { @MainActor in + guard let self else { return } + switch newState { + case .setup: + self.state = .preparing + case .preparing: + self.state = .preparing + case .ready: + self.state = .ready + case .waiting(let error): + self.state = .waiting(error.localizedDescription) + case .failed(let error): + self.state = .failed(error.localizedDescription) + case .cancelled: + self.state = .stopped + @unknown default: + self.state = .waiting("Unknown Network.framework state") + } + } + } + + connection.start(queue: queue) + } + + func stop() { + connection?.cancel() + connection = nil + state = .stopped + } +} + +enum DashTransportError: LocalizedError { + case invalidHost + case invalidPort + + var errorDescription: String? { + switch self { + case .invalidHost: return "Dash host is empty." + case .invalidPort: return "Dash UDP port is invalid." + } + } +} diff --git a/RideDash/DashConnectivity/LocalNetworkMonitor.swift b/RideDash/DashConnectivity/LocalNetworkMonitor.swift new file mode 100644 index 0000000..adf7329 --- /dev/null +++ b/RideDash/DashConnectivity/LocalNetworkMonitor.swift @@ -0,0 +1,55 @@ +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..1f09bf7 --- /dev/null +++ b/RideDash/DashConnectivity/TripperWiFiManager.swift @@ -0,0 +1,83 @@ +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 + ) + } + configuration.joinOnce = true + + do { + try await withCheckedThrowingContinuation { continuation in + NEHotspotConfigurationManager.shared.apply(configuration) { error in + 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/Diagnostics/DiagnosticLog.swift b/RideDash/Diagnostics/DiagnosticLog.swift new file mode 100644 index 0000000..9a5124d --- /dev/null +++ b/RideDash/Diagnostics/DiagnosticLog.swift @@ -0,0 +1,66 @@ +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..1d52f88 --- /dev/null +++ b/RideDash/Features/Diagnostics/DiagnosticsView.swift @@ -0,0 +1,178 @@ +import SwiftUI + +struct DiagnosticsView: View { + @StateObject private var wiFiManager = TripperWiFiManager() + @StateObject private var networkMonitor = LocalNetworkMonitor() + @StateObject private var transport = DashTransport() + @StateObject private var log = DiagnosticLog() + + @AppStorage("dash.test.bikeModel") private var bikeModel = "Guerrilla 450" + @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 = 5000 + + @State private var passphrase = "" + + 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 + wiFiSection + networkSection + transportSection + logSection + } + .navigationTitle("Dash Diagnostics") + .onAppear { + networkMonitor.start() + log.append("Diagnostics screen opened", category: "app") + } + .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") + } + } + + private var hardwareSection: some View { + Section("Hardware test profile") { + TextField("Bike model", text: $bikeModel) + TextField("Dash firmware", text: $dashFirmware) + .textInputAutocapitalization(.never) + LabeledContent("Phone", value: profile.iPhoneModel) + LabeledContent("iOS", value: profile.iOSVersion) + } + } + + private var wiFiSection: some View { + Section { + TextField("Dash 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 dash 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("RideDash uses Apple's Hotspot Configuration API. iOS controls the user approval flow. The password is kept only in this screen state and is never written to the diagnostic log.") + } + } + + 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("Dash 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) + } header: { + Text("UDP diagnostic route") + } footer: { + Text("A UDP connection reaching Ready only proves iOS has a route/socket. It does not prove the motorcycle dash responded. Phase 2 will add receive loops and validated, non-destructive protocol probes.") + } + } + + 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 deliberately redacts most of the SSID and does not include the Wi-Fi password, cryptographic secrets, or route history.") + } + } +} + +#Preview { + NavigationStack { + DiagnosticsView() + } +} diff --git a/RideDash/Models/DashTestProfile.swift b/RideDash/Models/DashTestProfile.swift new file mode 100644 index 0000000..cd85307 --- /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: "Guerrilla 450", + dashFirmware: "", + dashSSID: "", + dashHost: "192.168.1.1", + iPhoneModel: UIDevice.current.model, + iOSVersion: UIDevice.current.systemVersion + ) + } +} 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 + + + From 8669f3d1b4c78ceaf077186438dfbcfed44465b7 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 16:35:38 +0530 Subject: [PATCH 002/112] ci: add iOS simulator build --- .github/workflows/ios-build.yml | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 .github/workflows/ios-build.yml diff --git a/.github/workflows/ios-build.yml b/.github/workflows/ios-build.yml new file mode 100644 index 0000000..9935c15 --- /dev/null +++ b/.github/workflows/ios-build.yml @@ -0,0 +1,31 @@ +name: iOS Build + +on: + push: + branches: + - main + - phase-1-connectivity-diagnostics + pull_request: + branches: + - main + +jobs: + build: + runs-on: macos-15 + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Show Xcode version + run: xcodebuild -version + + - name: Build RideDash for iOS Simulator + run: | + set -o pipefail + xcodebuild \ + -project RideDash.xcodeproj \ + -target RideDash \ + -configuration Debug \ + -sdk iphonesimulator \ + CODE_SIGNING_ALLOWED=NO \ + build | xcpretty From 3b50178769f14e6b70e013362c49be587955cb4c Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 16:36:35 +0530 Subject: [PATCH 003/112] fix: import Combine in Wi-Fi manager --- RideDash/DashConnectivity/TripperWiFiManager.swift | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/RideDash/DashConnectivity/TripperWiFiManager.swift b/RideDash/DashConnectivity/TripperWiFiManager.swift index 1f09bf7..1758f1b 100644 --- a/RideDash/DashConnectivity/TripperWiFiManager.swift +++ b/RideDash/DashConnectivity/TripperWiFiManager.swift @@ -1,3 +1,4 @@ +import Combine import Foundation import NetworkExtension @@ -47,7 +48,7 @@ final class TripperWiFiManager: ObservableObject, DashWiFiJoining { configuration.joinOnce = true do { - try await withCheckedThrowingContinuation { continuation in + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in NEHotspotConfigurationManager.shared.apply(configuration) { error in if let error { continuation.resume(throwing: error) From 9ed297acd646f0319e7d8417b3fc848a184c7ba7 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 16:36:43 +0530 Subject: [PATCH 004/112] fix: import Combine in network monitor --- RideDash/DashConnectivity/LocalNetworkMonitor.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/RideDash/DashConnectivity/LocalNetworkMonitor.swift b/RideDash/DashConnectivity/LocalNetworkMonitor.swift index adf7329..950cf1d 100644 --- a/RideDash/DashConnectivity/LocalNetworkMonitor.swift +++ b/RideDash/DashConnectivity/LocalNetworkMonitor.swift @@ -1,3 +1,4 @@ +import Combine import Foundation import Network From 2564a0edebfeed5a1ffd23186b32f120d839711d Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 16:36:53 +0530 Subject: [PATCH 005/112] fix: import Combine in UDP transport --- RideDash/DashConnectivity/DashTransport.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/RideDash/DashConnectivity/DashTransport.swift b/RideDash/DashConnectivity/DashTransport.swift index 578c741..e4b532a 100644 --- a/RideDash/DashConnectivity/DashTransport.swift +++ b/RideDash/DashConnectivity/DashTransport.swift @@ -1,3 +1,4 @@ +import Combine import Foundation import Network From 4d01494c5190b7a55c278868f734734866d56b77 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 16:37:03 +0530 Subject: [PATCH 006/112] fix: import Combine in diagnostic log --- RideDash/Diagnostics/DiagnosticLog.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/RideDash/Diagnostics/DiagnosticLog.swift b/RideDash/Diagnostics/DiagnosticLog.swift index 9a5124d..56dc1cd 100644 --- a/RideDash/Diagnostics/DiagnosticLog.swift +++ b/RideDash/Diagnostics/DiagnosticLog.swift @@ -1,3 +1,4 @@ +import Combine import Foundation @MainActor From 85b486e8e703982ca9372ac71651bbe4c59b09aa Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 16:37:12 +0530 Subject: [PATCH 007/112] ci: remove optional xcpretty dependency --- .github/workflows/ios-build.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/workflows/ios-build.yml b/.github/workflows/ios-build.yml index 9935c15..b9e9437 100644 --- a/.github/workflows/ios-build.yml +++ b/.github/workflows/ios-build.yml @@ -21,11 +21,10 @@ jobs: - name: Build RideDash for iOS Simulator run: | - set -o pipefail xcodebuild \ -project RideDash.xcodeproj \ -target RideDash \ -configuration Debug \ -sdk iphonesimulator \ CODE_SIGNING_ALLOWED=NO \ - build | xcpretty + build From e8e1b62fb011bd8423769cd36eb87eda5cb3d131 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 16:42:59 +0530 Subject: [PATCH 008/112] chore: remove CI workflow for manual device testing --- .github/workflows/ios-build.yml | 30 ------------------------------ 1 file changed, 30 deletions(-) delete mode 100644 .github/workflows/ios-build.yml diff --git a/.github/workflows/ios-build.yml b/.github/workflows/ios-build.yml deleted file mode 100644 index b9e9437..0000000 --- a/.github/workflows/ios-build.yml +++ /dev/null @@ -1,30 +0,0 @@ -name: iOS Build - -on: - push: - branches: - - main - - phase-1-connectivity-diagnostics - pull_request: - branches: - - main - -jobs: - build: - runs-on: macos-15 - steps: - - name: Checkout - uses: actions/checkout@v4 - - - name: Show Xcode version - run: xcodebuild -version - - - name: Build RideDash for iOS Simulator - run: | - xcodebuild \ - -project RideDash.xcodeproj \ - -target RideDash \ - -configuration Debug \ - -sdk iphonesimulator \ - CODE_SIGNING_ALLOWED=NO \ - build From 42fbc8f01b9735226e572f1c0445ee0907d33bab Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 16:46:46 +0530 Subject: [PATCH 009/112] feat: add K1G protocol codec and RSA session authentication --- RideDash/DashProtocol/DashProtocol.swift | 353 +++++++++++++++++++++++ 1 file changed, 353 insertions(+) create mode 100644 RideDash/DashProtocol/DashProtocol.swift diff --git a/RideDash/DashProtocol/DashProtocol.swift b/RideDash/DashProtocol/DashProtocol.swift new file mode 100644 index 0000000..64cf0e9 --- /dev/null +++ b/RideDash/DashProtocol/DashProtocol.swift @@ -0,0 +1,353 @@ +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 { + // Public interoperability reference packets. Sequence byte is patched before send. + 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" + + // Initial app-like burst. nil marks the dynamic hostname announce slot. + static let initialBurst: [String?] = [ + requestAuthHex, + nil, + "0018000200000000020100054B31472002060600030E3334", + "0016000200000000020100054B314720030557000155", + "0016000200000000020100054B3147200405560001AA", + "0016000200000000020100054B3147200506050001AA", + "0016000200000000020100054B3147200605170001AA", + "001D000200000000020100054B314720080A020008AA55000000000000", + "0044000A00000000020100054B3147200906080001FF060300015506040001A2060F0001AA0601000101054C000113052D00020000051B0001190521000132054D000132" + ] + + // Reference route-card packet used only as a template. buildRouteCard replaces title and length. + 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] // K1G + 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() + let lengthField = UInt8(clamping: raw.count + 1) + body.append(contentsOf: [0x01, 0x06, 0x0B, 0x00, lengthField]) + 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() + output.append(template.prefix(oldTitleStart)) + var 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) where Array(haystack[i..<(i + needle.count)]) == 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 [] } + var events: [DashProtocolEvent] = [] + for segment in envelope.segments { + switch (segment.type, segment.subtype) { + case (0x07, 0x00): + events.append(.rsaModulus(segment.payload)) + case (0x07, 0x03): + events.append(.rsaExponent(segment.payload)) + case (0x07, 0x01): + let status = segment.payload.first ?? 0 + events.append(status == 0x01 ? .authAccepted : .authRejected(status)) + case (0x09, 0x00): + if let byte = segment.payload.first, let button = DashButton(rawValue: byte) { + events.append(.button(button)) + } else { + events.append(.segment(segment)) + } + default: + events.append(.segment(segment)) + } + } + return events + } +} + +// 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) + } + + /// Public interoperability behavior: payload = UTF8(SSID) || 32-byte AES key, + /// encrypted with the dash-provided RSA-1024 key using PKCS#1 v1.5 padding. + 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 { + throw error?.takeRetainedValue() ?? DashProtocolError.publicKeyCreationFailed as CFError + } + 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 { + throw error?.takeRetainedValue() ?? DashProtocolError.rsaEncryptionFailed as CFError + } + return encrypted as Data + } +} + +private enum DER { + static func rsaPublicKey(modulus: Data, exponent: Data) -> Data { + let n = integer(modulus) + let e = integer(exponent) + return sequence(n + e) + } + + private static func integer(_ raw: Data) -> Data { + var value = raw.drop { $0 == 0 } + if value.isEmpty { value = Data([0]) } + var body = Data(value) + 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) + } +} + +// MARK: - Errors + +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." + } + } +} From aa8221c9a6a168fcb067fc01ea0950b8027e61e3 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 16:47:15 +0530 Subject: [PATCH 010/112] feat: implement control input and video UDP transport --- RideDash/DashConnectivity/DashTransport.swift | 203 ++++++++++++++++-- 1 file changed, 180 insertions(+), 23 deletions(-) diff --git a/RideDash/DashConnectivity/DashTransport.swift b/RideDash/DashConnectivity/DashTransport.swift index e4b532a..067cf10 100644 --- a/RideDash/DashConnectivity/DashTransport.swift +++ b/RideDash/DashConnectivity/DashTransport.swift @@ -2,6 +2,18 @@ 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 { @@ -15,7 +27,7 @@ final class DashTransport: ObservableObject { switch self { case .stopped: return "Stopped" case .preparing: return "Preparing" - case .ready: return "UDP route ready" + case .ready: return "UDP transport ready" case .waiting(let reason): return "Waiting: \(reason)" case .failed(let error): return "Failed: \(error)" } @@ -23,68 +35,213 @@ final class DashTransport: ObservableObject { } @Published private(set) var state: State = .stopped + @Published private(set) var receivedPackets: Int = 0 + @Published private(set) var sentPackets: Int = 0 + @Published private(set) var lastError: String? - private var connection: NWConnection? - private let queue = DispatchQueue(label: "dev.dagerott.RideDash.udp-transport") + var onDatagram: (@Sendable (DashDatagram) -> Void)? - func start(host: String, port: UInt16) throws { - stop() + 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 profile: DashProtocolProfile? - guard !host.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + func start(profile: DashProtocolProfile) throws { + stop() + guard !profile.host.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { throw DashTransportError.invalidHost } - guard let endpointPort = NWEndpoint.Port(rawValue: port) else { + 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 } + self.profile = profile state = .preparing - let connection = NWConnection( - host: NWEndpoint.Host(host), - port: endpointPort, + lastError = nil + + let control = NWConnection( + host: NWEndpoint.Host(profile.broadcastHost), + port: controlPort, using: .udp ) - self.connection = connection + controlConnection = control + observe(connection: control, label: "control") + control.start(queue: queue) - connection.stateUpdateHandler = { [weak self] newState in + let video = NWConnection( + host: NWEndpoint.Host(profile.host), + port: videoPort, + using: .udp + ) + videoConnection = video + video.stateUpdateHandler = { [weak self] state in + guard case .failed(let error) = state 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 guard let self else { return } switch newState { - case .setup: - self.state = .preparing - case .preparing: + case .ready: + if self.controlConnection?.state == .ready { self.state = .ready } + case .waiting(let error): + self.state = .waiting("Input listener: \(error.localizedDescription)") + case .failed(let error): + self.state = .failed("Input listener: \(error.localizedDescription)") + self.lastError = error.localizedDescription + default: + break + } + } + } + listener.newConnectionHandler = { [weak self] connection in + guard let self else { return } + self.acceptInput(connection) + } + listener.start(queue: queue) + } + + /// Backward-compatible diagnostic route used by DiagnosticsView. + func start(host: String, port: UInt16) throws { + var profile = DashProtocolProfile.publicReference + profile.host = host + profile.broadcastHost = host + profile.videoPort = port + profile.controlPort = 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() + profile = nil + 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 + self?.sentPackets += 1 + self?.emit(.init( + timestamp: .now, + direction: .outbound, + channel: channel, + endpoint: self?.endpointDescription(connection.endpoint) ?? "unknown", + data: data + )) + } + continuation.resume() + }) + } + } + + private func observe(connection: NWConnection, label: String) { + connection.stateUpdateHandler = { [weak self, weak connection] newState in + Task { @MainActor in + guard let self else { return } + switch newState { + case .setup, .preparing: self.state = .preparing case .ready: - self.state = .ready + if self.inputListener?.state == .ready { self.state = .ready } case .waiting(let error): - self.state = .waiting(error.localizedDescription) + self.state = .waiting("\(label): \(error.localizedDescription)") case .failed(let error): - self.state = .failed(error.localizedDescription) + self.state = .failed("\(label): \(error.localizedDescription)") + self.lastError = error.localizedDescription case .cancelled: - self.state = .stopped + if connection === self.controlConnection { self.state = .stopped } @unknown default: self.state = .waiting("Unknown Network.framework state") } } } + } + private func acceptInput(_ connection: NWConnection) { + let id = ObjectIdentifier(connection) + inputConnections[id] = connection + connection.stateUpdateHandler = { [weak self, weak connection] state in + guard let self, let connection else { return } + if case .ready = state { self.receiveNext(on: connection) } + if case .failed = state { self.inputConnections.removeValue(forKey: id) } + if case .cancelled = state { self.inputConnections.removeValue(forKey: id) } + } connection.start(queue: queue) } - func stop() { - connection?.cancel() - connection = nil - state = .stopped + private func receiveNext(on connection: NWConnection) { + connection.receiveMessage { [weak self, weak connection] data, _, _, error in + guard let self, let connection else { return } + if let data, !data.isEmpty { + Task { @MainActor in + 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 is empty." case .invalidPort: return "Dash UDP port is invalid." + case .notStarted: return "Dash UDP transport has not been started." } } } From 9dedd6307e6951ae16af94c9724bc113b078114a Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 16:47:56 +0530 Subject: [PATCH 011/112] feat: add dash session state machine and projection control plane --- RideDash/App/DashSessionCoordinator.swift | 321 ++++++++++++++++++++++ 1 file changed, 321 insertions(+) create mode 100644 RideDash/App/DashSessionCoordinator.swift diff --git a/RideDash/App/DashSessionCoordinator.swift b/RideDash/App/DashSessionCoordinator.swift new file mode 100644 index 0000000..6a12ac1 --- /dev/null +++ b/RideDash/App/DashSessionCoordinator.swift @@ -0,0 +1,321 @@ +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 var routeTitle: String = "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 authTimeoutTask: Task? + private var projectionHeartbeatTask: Task? + private var routeHeartbeatTask: Task? + private var navEntered = false + + 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) } + } + } + + func connect( + ssid: String, + hostname: String, + profile: DashProtocolProfile = .publicReference, + authTimeout: Duration = .seconds(8) + ) async { + disconnect() + self.ssid = ssid + self.hostname = hostname.isEmpty ? "iPhone" : hostname + self.profile = profile + sequence = 0 + modulus = nil + exponent = nil + authenticatedSession = nil + navEntered = false + + do { + state = .startingTransport + try transport.start(profile: profile) + log.append("Control/input/video UDP transport requested", category: "session") + + // Network.framework is asynchronous. A short preparation window prevents + // the first burst from racing listener setup on normal device hardware. + try await Task.sleep(for: .milliseconds(250)) + try Task.checkCancellation() + + state = .requestingAuthentication + try await sendInitialBurst() + state = .awaitingPublicKey + log.append("Initial K1G burst sent; awaiting RSA public key", category: "auth") + + authTimeoutTask?.cancel() + authTimeoutTask = Task { [weak self] in + try? await Task.sleep(for: authTimeout) + guard !Task.isCancelled else { return } + await MainActor.run { + guard let self else { return } + if self.authenticatedSession == nil { + self.state = .failed("Authentication timed out") + self.log.append("Authentication timeout", category: "auth", level: .error) + } + } + } + } catch { + state = .failed(error.localizedDescription) + log.append(error.localizedDescription, category: "session", level: .error) + } + } + + func enterNavigation(title: String? = nil) async throws { + guard authenticatedSession != nil else { throw DashSessionError.notAuthenticated } + if let title, !title.isEmpty { routeTitle = title } + + 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() + log.append("Navigation control plane entered", category: "session") + } + + func beginProjectionHeartbeat() { + guard navEntered 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() + projectionHeartbeatTask = nil + guard navEntered else { return } + state = .stopping + do { + try await sendHex(K1GCodec.projectionStopHex) + try await sendHex(K1GCodec.projectionOffHex) + state = .authenticated + log.append("Projection-off sequence sent", category: "projection") + } catch { + state = .failed(error.localizedDescription) + } + navEntered = false + } + + func disconnect() { + authTimeoutTask?.cancel() + projectionHeartbeatTask?.cancel() + routeHeartbeatTask?.cancel() + authTimeoutTask = nil + projectionHeartbeatTask = nil + routeHeartbeatTask = nil + transport.stop() + navEntered = false + authenticatedSession = nil + modulus = nil + exponent = nil + state = .disconnected + } + + // MARK: - RX + + private func handle(_ datagram: DashDatagram) { + if datagram.direction == .inbound { + 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() + state = .authenticated + log.append("Dash authentication accepted", category: "auth") + onAuthenticated?() + case .authRejected(let status): + authenticatedSession = nil + modulus = nil + exponent = nil + state = .requestingAuthentication + log.append("Dash authentication rejected status=0x\(String(format: "%02X", status))", category: "auth", level: .error) + Task { [weak self] in + guard let self else { return } + try? await self.sendHex(K1GCodec.requestAuthHex) + self.state = .awaitingPublicKey + } + case .button(let button): + lastButton = button + log.append("Dash input: \(String(describing: button))", category: "input") + onButton?(button) + if profile.respondToInput { + Task { [weak self] in + guard let self else { return } + if let ack = try? K1GCodec.buttonAck(button.rawValue) { + 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 authenticatedSession == nil, + 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 + ) + let packet = try K1GCodec.buildSessionKeyPacket(ciphertext: ciphertext) + try await self.sendRaw(packet) + self.authenticatedSession = DashAuthenticatedSession(aesKey: aesKey) + self.log.append("Encrypted AES session key sent", category: "auth") + } catch { + self.state = .failed(error.localizedDescription) + self.log.append(error.localizedDescription, category: "auth", level: .error) + } + } + } + + // MARK: - TX + + private func sendInitialBurst() async throws { + for entry in K1GCodec.initialBurst { + let packet: Data + if let entry { + packet = try HexCodec.data(from: entry) + } else { + packet = 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 + try await transport.sendControl(patched) + } + + 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)) + } + } + } +} + +enum DashSessionError: LocalizedError { + case notAuthenticated + + var errorDescription: String? { + switch self { + case .notAuthenticated: return "Authenticate with the dash before entering navigation mode." + } + } +} From 147e121d2aaf22b4a2534ad20e19acc1dbd5bfe1 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 16:49:05 +0530 Subject: [PATCH 012/112] feat: add dash renderer VideoToolbox encoder and RTP streamer --- RideDash/ProjectionCore/ProjectionCore.swift | 485 +++++++++++++++++++ 1 file changed, 485 insertions(+) create mode 100644 RideDash/ProjectionCore/ProjectionCore.swift diff --git a/RideDash/ProjectionCore/ProjectionCore.swift b/RideDash/ProjectionCore/ProjectionCore.swift new file mode 100644 index 0000000..411caa6 --- /dev/null +++ b/RideDash/ProjectionCore/ProjectionCore.swift @@ -0,0 +1,485 @@ +import AVFoundation +import CoreGraphics +import CoreMedia +import CoreVideo +import Foundation +import UIKit +import VideoToolbox + +struct ProjectionUIState: Sendable, Hashable { + var destination: String = "RideDash" + var maneuver: String = "Continue" + var distanceToManeuver: String = "--" + var eta: String = "--" + var remainingDistance: String = "--" + var speedKph: Double = 0 + var gpsAccuracy: Double? = nil + var isCalibrationGrid = false + var statusMessage: String? = nil +} + +// MARK: - Frame 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 pixelBuffer: CVPixelBuffer? + let attributes: [CFString: Any] = [ + kCVPixelBufferCGImageCompatibilityKey: true, + kCVPixelBufferCGBitmapContextCompatibilityKey: true, + kCVPixelBufferIOSurfacePropertiesKey: [:] + ] + let status = CVPixelBufferCreate( + kCFAllocatorDefault, + width, + height, + kCVPixelFormatType_32BGRA, + attributes as CFDictionary, + &pixelBuffer + ) + guard status == kCVReturnSuccess, let pixelBuffer else { + throw ProjectionError.pixelBufferCreationFailed(status) + } + + CVPixelBufferLockBaseAddress(pixelBuffer, []) + defer { CVPixelBufferUnlockBaseAddress(pixelBuffer, []) } + guard let baseAddress = CVPixelBufferGetBaseAddress(pixelBuffer) else { + throw ProjectionError.pixelBufferMissingBaseAddress + } + + let colorSpace = CGColorSpaceCreateDeviceRGB() + guard let context = CGContext( + data: baseAddress, + width: width, + height: height, + bitsPerComponent: 8, + bytesPerRow: CVPixelBufferGetBytesPerRow(pixelBuffer), + space: colorSpace, + bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue + ) else { + throw ProjectionError.contextCreationFailed + } + + // CoreGraphics coordinates are flipped relative to UIKit text APIs. + context.setFillColor(UIColor.black.cgColor) + context.fill(CGRect(x: 0, y: 0, width: width, height: height)) + UIGraphicsPushContext(context) + defer { UIGraphicsPopContext() } + + if state.isCalibrationGrid { + drawCalibration(in: context) + } else { + drawNavigation(state, in: context) + } + return pixelBuffer + } + + private func drawCalibration(in context: CGContext) { + let rect = CGRect(x: 0, y: 0, width: width, height: height) + context.setStrokeColor(UIColor.white.withAlphaComponent(0.35).cgColor) + context.setLineWidth(1) + stride(from: 0, through: width, by: 25).forEach { x in + context.move(to: CGPoint(x: x, y: 0)) + context.addLine(to: CGPoint(x: x, y: height)) + } + stride(from: 0, through: height, by: 25).forEach { y in + context.move(to: CGPoint(x: 0, y: y)) + context.addLine(to: CGPoint(x: width, y: y)) + } + context.strokePath() + + context.setStrokeColor(UIColor.systemOrange.cgColor) + context.setLineWidth(3) + context.strokeEllipse(in: rect.insetBy(dx: 7, dy: 7)) + context.move(to: CGPoint(x: width / 2, y: 0)) + context.addLine(to: CGPoint(x: width / 2, y: height)) + context.move(to: CGPoint(x: 0, y: height / 2)) + context.addLine(to: CGPoint(x: width, y: height / 2)) + context.strokePath() + + drawText("526 × 300 CALIBRATION", frame: CGRect(x: 80, y: 125, width: 366, height: 40), size: 24, weight: .bold, alignment: .center) + } + + private func drawNavigation(_ state: ProjectionUIState, in context: CGContext) { + let safe = CGRect(x: 34, y: 22, width: width - 68, height: height - 44) + + // Destination header. + 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) + + // Maneuver card. + let card = CGRect(x: safe.minX + 34, y: safe.minY + 40, width: safe.width - 68, height: 104) + let path = UIBezierPath(roundedRect: card, cornerRadius: 24) + UIColor(white: 0.10, alpha: 1).setFill() + path.fill() + drawText(state.maneuver, frame: CGRect(x: card.minX + 16, y: card.minY + 13, width: card.width - 32, height: 42), size: 32, 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) + + // Bottom glance row. + 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: "\(Int(state.speedKph.rounded()))", x: safe.maxX - 127, y: safe.maxY - 70, width: 105) + + if let status = state.statusMessage { + drawText(status, frame: CGRect(x: 90, y: height - 25, width: width - 180, height: 18), 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( + _ text: String, + frame: CGRect, + size: CGFloat, + weight: UIFont.Weight, + alignment: NSTextAlignment, + color: UIColor = .white + ) { + let paragraph = NSMutableParagraphStyle() + paragraph.alignment = alignment + paragraph.lineBreakMode = .byTruncatingTail + (text as NSString).draw( + in: frame, + withAttributes: [ + .font: UIFont.systemFont(ofSize: size, weight: weight), + .foregroundColor: color, + .paragraphStyle: paragraph + ] + ) + } +} + +// MARK: - H.264 + +struct H264NALUnit: Sendable, Hashable { + let bytes: Data + let isParameterSet: Bool +} + +final class H264Encoder { + var onNALUnits: (@Sendable ([H264NALUnit], CMTime) -> Void)? + + private let width: Int32 + private let height: Int32 + private let fps: Int + private let bitrate: Int + private var session: VTCompressionSession? + + init(width: Int, height: Int, fps: Int, bitrateKbps: Int) throws { + self.width = Int32(width) + self.height = Int32(height) + self.fps = max(1, fps) + self.bitrate = max(64, bitrateKbps) * 1_000 + try configure() + } + + deinit { + if let session { + VTCompressionSessionCompleteFrames(session, untilPresentationTimeStamp: .invalid) + VTCompressionSessionInvalidate(session) + } + } + + func encode(_ pixelBuffer: CVPixelBuffer, pts: CMTime) throws { + guard let session else { throw ProjectionError.encoderNotReady } + var flags = VTEncodeInfoFlags() + let status = VTCompressionSessionEncodeFrame( + session, + imageBuffer: pixelBuffer, + 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() throws { + var created: VTCompressionSession? + let refcon = Unmanaged.passUnretained(self).toOpaque() + let status = VTCompressionSessionCreate( + allocator: kCFAllocatorDefault, + width: width, + height: height, + codecType: kCMVideoCodecType_H264, + encoderSpecification: nil, + imageBufferAttributes: nil, + compressedDataAllocator: nil, + outputCallback: Self.outputCallback, + refcon: refcon, + compressionSessionOut: &created + ) + guard status == noErr, let created else { throw ProjectionError.videoToolbox(status) } + session = created + + try set(kVTCompressionPropertyKey_RealTime, value: kCFBooleanTrue) + try set(kVTCompressionPropertyKey_ProfileLevel, value: kVTProfileLevel_H264_Baseline_AutoLevel) + try set(kVTCompressionPropertyKey_AllowFrameReordering, value: kCFBooleanFalse) + try set(kVTCompressionPropertyKey_AverageBitRate, value: bitrate as CFNumber) + try set(kVTCompressionPropertyKey_ExpectedFrameRate, value: fps as CFNumber) + try set(kVTCompressionPropertyKey_MaxKeyFrameInterval, value: (fps * 2) as CFNumber) + let dataRate: [Int] = [bitrate / 8, 1] + try set(kVTCompressionPropertyKey_DataRateLimits, value: dataRate as CFArray) + 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] = [] + let attachments = CMSampleBufferGetSampleAttachmentsArray(sampleBuffer, createIfNecessary: false) + let isKeyframe: Bool = { + guard let attachments, + CFArrayGetCount(attachments) > 0, + let raw = CFArrayGetValueAtIndex(attachments, 0) else { return false } + let dictionary = unsafeBitCast(raw, to: CFDictionary.self) as NSDictionary + return dictionary[kCMSampleAttachmentKey_NotSync] == nil + }() + + if isKeyframe, let format = CMSampleBufferGetFormatDescription(sampleBuffer) { + for index in 0..<2 { + var pointer: UnsafePointer? + var size = 0 + var count = 0 + var headerLength: Int32 = 0 + let result = CMVideoFormatDescriptionGetH264ParameterSetAtIndex( + format, + parameterSetIndex: index, + parameterSetPointerOut: &pointer, + parameterSetSizeOut: &size, + parameterSetCountOut: &count, + nalUnitHeaderLengthOut: &headerLength + ) + if result == noErr, let pointer { + units.append(.init(bytes: Data(bytes: pointer, count: size), isParameterSet: true)) + } + } + } + + guard let blockBuffer = CMSampleBufferGetDataBuffer(sampleBuffer) else { return } + var totalLength = 0 + var lengthAtOffset = 0 + var pointer: UnsafeMutablePointer? + let status = CMBlockBufferGetDataPointer( + blockBuffer, + atOffset: 0, + lengthAtOffsetOut: &lengthAtOffset, + totalLengthOut: &totalLength, + dataPointerOut: &pointer + ) + guard status == kCMBlockBufferNoErr, let pointer else { return } + + let bytes = UnsafeRawPointer(pointer).assumingMemoryBound(to: UInt8.self) + var offset = 0 + while offset + 4 <= totalLength { + let nalLength = Int(bytes[offset]) << 24 | + Int(bytes[offset + 1]) << 16 | + Int(bytes[offset + 2]) << 8 | + Int(bytes[offset + 3]) + offset += 4 + guard nalLength > 0, offset + nalLength <= totalLength else { break } + units.append(.init(bytes: Data(bytes: bytes + offset, count: nalLength), isParameterSet: false)) + offset += nalLength + } + + if !units.isEmpty { + onNALUnits?(units, CMSampleBufferGetPresentationTimeStamp(sampleBuffer)) + } + } +} + +// MARK: - RTP packetizer + +final class H264RTPPacketizer { + private(set) var sequence: UInt16 = UInt16.random(in: 0...UInt16.max) + private(set) var timestamp: UInt32 = UInt32.random(in: 0...UInt32.max) + private let ssrc = UInt32.random(in: 1...UInt32.max) + private let payloadType: UInt8 = 96 + private let maxPayload: Int + private let timestampStep: UInt32 + + init(fps: Int, maxPayload: Int = 1_180) { + self.maxPayload = max(300, maxPayload) + self.timestampStep = UInt32(90_000 / max(1, fps)) + } + + func packetize(_ units: [H264NALUnit]) -> [Data] { + var packets: [Data] = [] + for (unitIndex, unit) in units.enumerated() { + let isLastUnit = unitIndex == units.count - 1 + let bytes = unit.bytes + guard let first = bytes.first else { continue } + if bytes.count <= maxPayload { + packets.append(makePacket(payload: bytes, marker: isLastUnit)) + } else { + let nri = first & 0x60 + let forbidden = first & 0x80 + let nalType = first & 0x1F + let fuIndicator = forbidden | nri | 28 + let body = bytes.dropFirst() + let fragmentSize = maxPayload - 2 + var offset = 0 + while offset < body.count { + let end = min(body.count, offset + fragmentSize) + 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[offset.. Data { + var packet = Data(capacity: 12 + payload.count) + packet.append(0x80) // RTP v2 + packet.append((marker ? 0x80 : 0) | payloadType) + appendBE(sequence, to: &packet) + appendBE(timestamp, to: &packet) + appendBE(ssrc, to: &packet) + packet.append(payload) + sequence &+= 1 + return packet + } + + private func appendBE(_ value: T, to data: inout Data) { + var be = value.bigEndian + withUnsafeBytes(of: &be) { data.append(contentsOf: $0) } + } +} + +// MARK: - End-to-end streamer + +@MainActor +final class ProjectionStreamer: ObservableObject { + enum State: Equatable { case stopped, starting, streaming, 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 let renderer: DashFrameRenderer + + init(renderer: DashFrameRenderer = DashFrameRenderer()) { + self.renderer = renderer + } + + func start( + coordinator: DashSessionCoordinator, + profile: DashProtocolProfile, + stateProvider: @escaping @MainActor () -> ProjectionUIState + ) throws { + stop() + state = .starting + 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 byteCount = units.reduce(0) { $0 + $1.bytes.count } + Task { @MainActor in + self.encodedBytes += byteCount + 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 frameDuration = 1.0 / Double(max(1, profile.fps)) + renderTask = Task { [weak self] in + var frame: Int64 = 0 + while !Task.isCancelled { + guard let self else { return } + do { + let buffer = try self.renderer.render(stateProvider()) + let pts = CMTime(value: frame, timescale: CMTimeScale(max(1, profile.fps))) + try encoder.encode(buffer, pts: pts) + self.renderedFrames += 1 + frame += 1 + } catch { + self.state = .failed(error.localizedDescription) + coordinator.log.append(error.localizedDescription, category: "encoder", level: .error) + return + } + try? await Task.sleep(for: .seconds(frameDuration)) + } + } + } + + 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 frame graphics context." + case .encoderNotReady: return "H.264 encoder is not ready." + case .videoToolbox(let status): return "VideoToolbox returned status \(status)." + } + } +} From 6a3576d0b5cbf33e1ff81d409fca77c4840fe009 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 16:49:46 +0530 Subject: [PATCH 013/112] feat: add CoreLocation MapKit navigation engine --- RideDash/NavigationCore/NavigationCore.swift | 314 +++++++++++++++++++ 1 file changed, 314 insertions(+) create mode 100644 RideDash/NavigationCore/NavigationCore.swift diff --git a/RideDash/NavigationCore/NavigationCore.swift b/RideDash/NavigationCore/NavigationCore.swift new file mode 100644 index 0000000..28e3fb9 --- /dev/null +++ b/RideDash/NavigationCore/NavigationCore.swift @@ -0,0 +1,314 @@ +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) { + // This is only useful when the app target has the legitimate location background mode. + // It does not guarantee indefinite video/network execution while the phone is locked. + 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 = ["q", "query", "destination", "daddr", "ll"] + if let value = components?.queryItems?.first(where: { keys.contains($0.name.lowercased()) })?.value { + 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 errorMessage: String? + @Published private(set) var projectionState = ProjectionUIState() + + let locationService: NavigationLocationService + private var cancellables: Set = [] + + 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 request = MKDirections.Request() + request.source = MKMapItem(placemark: MKPlacemark(coordinate: originLocation.coordinate)) + request.destination = MKMapItem(placemark: MKPlacemark(coordinate: resolved.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 } + self.route = route + activeStepIndex = firstUsableStep(in: route) + rebuildProjectionState(location: originLocation) + } catch { + errorMessage = error.localizedDescription + } + } + + func clearRoute() { + route = nil + destination = nil + activeStepIndex = 0 + 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) { + switch button { + case .left: + activeStepIndex = max(firstUsableStep(in: route), activeStepIndex - 1) + case .right: + if let route { activeStepIndex = min(route.steps.count - 1, activeStepIndex + 1) } + case .down, .click: + // Recenter/return to live guidance rather than changing vehicle state. + if let route, 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 { + let suggested = nearestUpcomingStep(in: route, to: location) + if suggested >= activeStepIndex { activeStepIndex = suggested } + } + rebuildProjectionState(location: location) + } + + private func rebuildProjectionState(location: CLLocation?) { + guard let route, let destination else { + projectionState = ProjectionUIState( + destination: destination?.name ?? "RideDash", + speedKph: max(0, (location?.speed ?? 0) * 3.6), + gpsAccuracy: location?.horizontalAccuracy + ) + return + } + + let index = min(max(0, activeStepIndex), max(0, route.steps.count - 1)) + let step = route.steps.isEmpty ? nil : route.steps[index] + let instruction = step?.instructions.isEmpty == false ? step!.instructions : "Continue" + let distance = step.map { Self.formatDistance($0.distance) } ?? "--" + let etaDate = Date().addingTimeInterval(route.expectedTravelTime) + let etaFormatter = DateFormatter() + etaFormatter.dateFormat = "HH:mm" + + projectionState = ProjectionUIState( + destination: destination.name, + maneuver: instruction, + distanceToManeuver: distance, + eta: etaFormatter.string(from: etaDate), + remainingDistance: Self.formatDistance(route.distance), + speedKph: max(0, (location?.speed ?? 0) * 3.6), + gpsAccuracy: location?.horizontalAccuracy, + isCalibrationGrid: false, + statusMessage: (location?.horizontalAccuracy ?? 0) > 50 ? "GPS accuracy degraded" : nil + ) + } + + private func firstUsableStep(in route: MKRoute?) -> Int { + guard let route 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 } + var bestIndex = activeStepIndex + var bestDistance = CLLocationDistance.greatestFiniteMagnitude + for index in activeStepIndex.. 0 else { continue } + let coordinate = points[max(0, step.polyline.pointCount - 1)].coordinate + let end = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude) + let distance = location.distance(from: end) + if distance < bestDistance { + bestDistance = distance + bestIndex = index + } + if distance < 30, index + 1 < route.steps.count { return index + 1 } + } + return bestIndex + } + + private static func formatDistance(_ meters: CLLocationDistance) -> String { + if meters < 1_000 { return "\(Int(max(0, meters).rounded())) m" } + return String(format: "%.1f km", meters / 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." + } + } +} From 0e8f344baecd85fc0aaa2a1f904059c50f4173cd Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 16:51:19 +0530 Subject: [PATCH 014/112] feat: add RideDash product screens and SwiftData models --- .../Features/Product/ProductFeatures.swift | 831 ++++++++++++++++++ 1 file changed, 831 insertions(+) create mode 100644 RideDash/Features/Product/ProductFeatures.swift diff --git a/RideDash/Features/Product/ProductFeatures.swift b/RideDash/Features/Product/ProductFeatures.swift new file mode 100644 index 0000000..71f5bbd --- /dev/null +++ b/RideDash/Features/Product/ProductFeatures.swift @@ -0,0 +1,831 @@ +import MapKit +import SwiftData +import SwiftUI + +// MARK: - Persistence 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 + ) { + self.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 = "") { + self.id = UUID() + self.date = date + self.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) { + self.id = UUID() + self.date = date + self.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) { + self.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 = "") { + self.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] + + private var activeVehicle: Vehicle? { vehicles.first(where: \ .isActive) ?? vehicles.first } + + var body: some View { + List { + Section { + HStack { + VStack(alignment: .leading, spacing: 4) { + Text("Display") + .font(.caption) + .foregroundStyle(.secondary) + Text(session.state.label) + .font(.headline) + } + Spacer() + Circle() + .fill(sessionIndicator) + .frame(width: 12, height: 12) + } + } + + if let vehicle = activeVehicle { + Section("Active vehicle") { + LabeledContent(vehicle.name, value: "\(vehicle.odometerKm, specifier: "%.0f") km") + if !vehicle.registrationNumber.isEmpty { + LabeledContent("Registration", value: vehicle.registrationNumber) + } + } + } + + Section("Current navigation") { + LabeledContent("Destination", value: navigation.destination?.name ?? "Not set") + LabeledContent("Instruction", value: navigation.projectionState.maneuver) + LabeledContent("Next turn", value: navigation.projectionState.distanceToManeuver) + } + + Section("This month") { + let calendar = Calendar.current + let total = expenses + .filter { calendar.isDate($0.date, equalTo: .now, toGranularity: .month) } + .reduce(0) { $0 + $1.amount } + LabeledContent("Expenses", value: total.formatted(.currency(code: currencyCode))) + } + } + .navigationTitle("RideDash") + } + + private var currencyCode: String { UserDefaults.standard.string(forKey: "settings.currency") ?? "INR" } + + private var sessionIndicator: Color { + switch session.state { + case .projecting, .navigationReady, .authenticated: return .green + case .failed: return .red + case .disconnected: return .secondary + default: return .orange + } + } +} + +// MARK: - Navigation screen + +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 { + MapUserLocationButton() + MapCompass() + } + .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 { 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) { + Text(navigation.projectionState.maneuver).font(.headline).lineLimit(1) + Text("\(navigation.projectionState.distanceToManeuver) · ETA \(navigation.projectionState.eta)") + .font(.caption).foregroundStyle(.secondary) + } + Spacer() + Button("Apple Maps") { navigation.openInAppleMaps() } + .buttonStyle(.bordered) + } + } + + if session.state == .authenticated || session.state == .navigationReady || session.state == .projecting { + HStack { + Button("Enter Dash Nav") { + Task { try? await session.enterNavigation(title: navigation.destination?.name ?? "Navigation") } + } + .buttonStyle(.bordered) + + Button(streamer.state == .streaming ? "Streaming" : "Start Projection") { + startProjection(calibration: false) + } + .buttonStyle(.borderedProminent) + .disabled(session.state != .navigationReady && session.state != .projecting) + + Button("Stop", role: .destructive) { + streamer.stop() + Task { await session.stopProjection() } + } + .buttonStyle(.bordered) + } + } + } + .padding() + .background(.regularMaterial) + } + .navigationTitle("Navigation") + .navigationBarTitleDisplayMode(.inline) + .onAppear { navigation.startLocation() } + } + + private func startProjection(calibration: Bool) { + var profile = DashProtocolProfile.publicReference + profile.host = dashHost + profile.broadcastHost = broadcastHost + profile.fps = fps + profile.bitrateKbps = bitrate + do { + try streamer.start(coordinator: session, profile: profile) { + if calibration { + var state = navigation.projectionState + state.isCalibrationGrid = true + return state + } + return navigation.projectionState + } + } catch { + session.log.append(error.localizedDescription, category: "projection", level: .error) + } + } +} + +// MARK: - Display connection + +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 calibration = 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.isEmpty) + LabeledContent("Wi-Fi", value: wifi.status.description) + } + + Section("Protocol profile") { + TextField("Dash host", text: $host) + TextField("Broadcast", text: $broadcastHost) + Stepper("Control UDP \(controlPort)", value: $controlPort, in: 1...65535) + Stepper("Input UDP \(inputPort)", value: $inputPort, in: 1...65535) + Stepper("Video UDP \(videoPort)", value: $videoPort, in: 1...65535) + 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) + LabeledContent("State", value: session.state.label) + LabeledContent("RX", value: "\(session.transport.receivedPackets)") + LabeledContent("TX", value: "\(session.transport.sentPackets)") + + 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: $calibration) + Button("Start H.264/RTP Projection") { + do { + try streamer.start(coordinator: session, profile: profile) { + var state = navigation.projectionState + state.isCalibrationGrid = calibration + return state + } + } catch { + session.log.append(error.localizedDescription, category: "projection", level: .error) + } + } + .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("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 + ) + } +} + +// MARK: - Vehicles + +struct VehiclesView: View { + @Environment(\.modelContext) private var context + @Query(sort: \Vehicle.name) private var vehicles: [Vehicle] + @State private var showAdd = 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) { + 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 { indexes in indexes.forEach { context.delete(vehicles[$0]) } } + } + .navigationTitle("Vehicles") + .toolbar { Button { showAdd = true } label: { Image(systemName: "plus") } } + .sheet(isPresented: $showAdd) { 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: .whitespaces).isEmpty) + } + } + } + } +} + +struct VehicleDetailView: View { + @Bindable var vehicle: Vehicle + var body: some View { + Form { + 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", date: $vehicle.insuranceExpiry) + OptionalDateEditor(title: "PUC", date: $vehicle.pucExpiry) + OptionalDateEditor(title: "Last service", date: $vehicle.lastServiceDate) + } + Toggle("Active vehicle", isOn: $vehicle.isActive) + } + .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 fuel: [FuelLog] + @Query(sort: \MaintenanceRecord.date, order: .reverse) private var maintenance: [MaintenanceRecord] + @State private var showFuel = false + @State private var showMaintenance = false + + var body: some View { + List { + Section("Overview") { + LabeledContent("Fuel logs", value: "\(fuel.count)") + LabeledContent("Maintenance", value: "\(maintenance.count)") + LabeledContent("Calculated mileage", value: mileage.map { String(format: "%.1f km/L", $0) } ?? "Need 2 full-tank fills") + } + Section("Quick actions") { + Button("Log fuel") { showFuel = true } + Button("Log maintenance") { showMaintenance = true } + } + Section("Recent fuel") { + ForEach(fuel.prefix(10)) { entry in + LabeledContent("\(entry.litres, specifier: "%.1f") L", value: "\(entry.odometerKm, specifier: "%.0f") km") + } + .onDelete { indexes in indexes.forEach { context.delete(fuel[$0]) } } + } + Section("Recent maintenance") { + ForEach(maintenance.prefix(10)) { entry in + VStack(alignment: .leading) { + Text(entry.kind.rawValue).font(.headline) + Text("\(entry.odometerKm, specifier: "%.0f") km · \(entry.date.formatted(date: .abbreviated, time: .omitted))") + .font(.caption).foregroundStyle(.secondary) + } + } + } + } + .navigationTitle("Garage") + .sheet(isPresented: $showFuel) { AddFuelView() } + .sheet(isPresented: $showMaintenance) { AddMaintenanceView() } + } + + private var mileage: Double? { + let full = fuel.filter(\.fullTank).sorted { $0.odometerKm < $1.odometerKm } + guard full.count >= 2, let last = full.last else { return nil } + let previous = full[full.count - 2] + let distance = last.odometerKm - previous.odometerKm + guard distance > 0, last.litres > 0 else { return nil } + return distance / last.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 = "" + + var body: some View { + NavigationStack { + Form { + 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) + } + .navigationTitle("Maintenance") + .toolbar { + ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } } + ToolbarItem(placement: .confirmationAction) { + Button("Save") { context.insert(MaintenanceRecord(kind: kind, odometerKm: odometer, notes: notes)); dismiss() } + } + } + } + } +} + +// MARK: - Expenses + +struct ExpensesView: View { + @Environment(\.modelContext) private var context + @Query(sort: \Expense.date, order: .reverse) private var expenses: [Expense] + @State private var category: ExpenseCategory? + @State private var showAdd = false + @AppStorage("settings.currency") private var currency = "INR" + + private var filtered: [Expense] { category.map { chosen in expenses.filter { $0.category == chosen } } ?? expenses } + + var body: some View { + List { + Section { + LabeledContent("Total", value: filtered.reduce(0) { $0 + $1.amount }.formatted(.currency(code: currency))) + Picker("Filter", selection: $category) { + Text("All").tag(ExpenseCategory?.none) + ForEach(ExpenseCategory.allCases) { Text($0.rawValue).tag(Optional($0)) } + } + } + ForEach(filtered) { expense in + HStack { + VStack(alignment: .leading) { + 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 { indexes in indexes.forEach { context.delete(filtered[$0]) } } + } + .navigationTitle("Expenses") + .toolbar { + ToolbarItemGroup(placement: .topBarTrailing) { + ShareLink(item: CSVExporter.expenses(expenses)) { Image(systemName: "square.and.arrow.up") } + Button { showAdd = true } label: { Image(systemName: "plus") } + } + } + .sheet(isPresented: $showAdd) { 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 { + var lines = ["Date,Category,Amount,OdometerKm,Notes"] + let formatter = ISO8601DateFormatter() + for item in expenses { + lines.append([ + formatter.string(from: item.date), + escape(item.category.rawValue), + String(item.amount), + item.odometerKm.map(String.init) ?? "", + escape(item.notes) + ].joined(separator: ",")) + } + return lines.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 showAdd = false + + var body: some View { + List { + if rides.isEmpty { ContentUnavailableView("No rides", systemImage: "road.lanes", description: Text("Completed projected rides can be saved here.")) } + ForEach(rides) { ride in + VStack(alignment: .leading) { + 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 { indexes in indexes.forEach { context.delete(rides[$0]) } } + } + .navigationTitle("Rides") + .toolbar { Button { showAdd = true } label: { Image(systemName: "plus") } } + .sheet(isPresented: $showAdd) { 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" + @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("iOS behavior") { + Toggle("Request background navigation location", isOn: Binding( + get: { UserDefaults.standard.bool(forKey: "settings.backgroundLocation") }, + set: { value in + UserDefaults.standard.set(value, forKey: "settings.backgroundLocation") + navigation.locationService.setBackgroundNavigationEnabled(value) + } + )) + Text("Background location is legitimate for active navigation but does not guarantee that iOS will keep H.264/UDP projection alive after device lock.") + .font(.caption).foregroundStyle(.secondary) + } + Section("About") { + Text("RideDash is an independent ride/navigation companion designed around compatible Wi-Fi motorcycle displays. It does not implement ECU, brake, ABS, throttle, immobilizer, or other safety-critical vehicle control.") + .font(.caption) + } + } + .navigationTitle("Settings") + } +} From a82d79a432689b3ecff3ae757a17f9152f234110 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 16:51:36 +0530 Subject: [PATCH 015/112] feat: add complete RideDash tab navigation --- RideDash/App/RootView.swift | 48 +++++++++++++++++++++++++++++++++++-- 1 file changed, 46 insertions(+), 2 deletions(-) diff --git a/RideDash/App/RootView.swift b/RideDash/App/RootView.swift index 3283271..456453f 100644 --- a/RideDash/App/RootView.swift +++ b/RideDash/App/RootView.swift @@ -1,13 +1,57 @@ import SwiftUI struct RootView: View { + enum Tab: Hashable { case home, navigation, garage, expenses, rides, settings } + + @StateObject private var session = DashSessionCoordinator() + @StateObject private var navigation = NavigationViewModel() + @StateObject private var streamer = ProjectionStreamer() + @State private var selectedTab: Tab = .home + var body: some View { - NavigationStack { - DiagnosticsView() + 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() + } + .onOpenURL { url in + navigation.importURL(url) + selectedTab = .navigation } } } #Preview { RootView() + .modelContainer(for: [Vehicle.self, Expense.self, FuelLog.self, MaintenanceRecord.self, RideRecord.self], inMemory: true) } From a32412a7eac339edc200a735ef000468b2cc4748 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 16:51:43 +0530 Subject: [PATCH 016/112] feat: configure local SwiftData store --- RideDash/App/RideDashApp.swift | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/RideDash/App/RideDashApp.swift b/RideDash/App/RideDashApp.swift index e4dc0bf..6934678 100644 --- a/RideDash/App/RideDashApp.swift +++ b/RideDash/App/RideDashApp.swift @@ -1,3 +1,4 @@ +import SwiftData import SwiftUI @main @@ -6,5 +7,12 @@ struct RideDashApp: App { WindowGroup { RootView() } + .modelContainer(for: [ + Vehicle.self, + Expense.self, + FuelLog.self, + MaintenanceRecord.self, + RideRecord.self + ]) } } From 7cf597538a60717cba7910c7923fac861ea1e414 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 16:52:10 +0530 Subject: [PATCH 017/112] chore: add iOS permissions deep link and background location metadata --- RideDash/Info.plist | 51 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 RideDash/Info.plist 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 + + + From f2873bb15a1bf4072ff5189299d116ced4ba12e9 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 16:53:09 +0530 Subject: [PATCH 018/112] chore: wire complete RideDash sources into Xcode target --- RideDash.xcodeproj/project.pbxproj | 74 +++++++++++++++++++++++++----- 1 file changed, 62 insertions(+), 12 deletions(-) diff --git a/RideDash.xcodeproj/project.pbxproj b/RideDash.xcodeproj/project.pbxproj index b21fab7..099a5ef 100644 --- a/RideDash.xcodeproj/project.pbxproj +++ b/RideDash.xcodeproj/project.pbxproj @@ -15,6 +15,11 @@ 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 */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ @@ -28,6 +33,12 @@ 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 = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -55,8 +66,12 @@ 000000000000000000000012 /* App */, 000000000000000000000013 /* Features */, 000000000000000000000014 /* DashConnectivity */, + 000000000000000000000020 /* DashProtocol */, + 000000000000000000000021 /* ProjectionCore */, + 000000000000000000000022 /* NavigationCore */, 000000000000000000000015 /* Diagnostics */, 000000000000000000000016 /* Models */, + 000000000000000000000115 /* Info.plist */, 000000000000000000000109 /* RideDash.entitlements */, ); path = RideDash; @@ -67,6 +82,7 @@ children = ( 000000000000000000000101 /* RideDashApp.swift */, 000000000000000000000102 /* RootView.swift */, + 000000000000000000000110 /* DashSessionCoordinator.swift */, ); path = App; sourceTree = ""; @@ -75,6 +91,7 @@ isa = PBXGroup; children = ( 000000000000000000000018 /* Diagnostics */, + 000000000000000000000019 /* Product */, ); path = Features; sourceTree = ""; @@ -87,6 +104,14 @@ path = Diagnostics; sourceTree = ""; }; + 000000000000000000000019 /* Product */ = { + isa = PBXGroup; + children = ( + 000000000000000000000114 /* ProductFeatures.swift */, + ); + path = Product; + sourceTree = ""; + }; 000000000000000000000014 /* DashConnectivity */ = { isa = PBXGroup; children = ( @@ -97,6 +122,30 @@ 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 = ( @@ -197,6 +246,11 @@ 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; }; @@ -246,19 +300,17 @@ CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; DEVELOPMENT_TEAM = ""; - GENERATE_INFOPLIST_FILE = YES; - INFOPLIST_KEY_CFBundleDisplayName = RideDash; - INFOPLIST_KEY_NSLocalNetworkUsageDescription = "RideDash uses the local network to connect to a compatible motorcycle display for navigation and diagnostics."; - INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES; - INFOPLIST_KEY_UILaunchScreen_Generation = YES; + 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.1.0; + 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"; }; @@ -271,19 +323,17 @@ CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; DEVELOPMENT_TEAM = ""; - GENERATE_INFOPLIST_FILE = YES; - INFOPLIST_KEY_CFBundleDisplayName = RideDash; - INFOPLIST_KEY_NSLocalNetworkUsageDescription = "RideDash uses the local network to connect to a compatible motorcycle display for navigation and diagnostics."; - INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES; - INFOPLIST_KEY_UILaunchScreen_Generation = YES; + 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.1.0; + 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"; }; From 76baffb864431f91043471e5496542cf6393a7aa Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 16:54:35 +0530 Subject: [PATCH 019/112] fix: harden RSA key construction and DER encoding --- RideDash/DashProtocol/DashProtocol.swift | 73 +++++++++--------------- 1 file changed, 26 insertions(+), 47 deletions(-) diff --git a/RideDash/DashProtocol/DashProtocol.swift b/RideDash/DashProtocol/DashProtocol.swift index 64cf0e9..16a652e 100644 --- a/RideDash/DashProtocol/DashProtocol.swift +++ b/RideDash/DashProtocol/DashProtocol.swift @@ -67,7 +67,6 @@ struct K1GEnvelope: Hashable, Sendable { } enum K1GCodec { - // Public interoperability reference packets. Sequence byte is patched before send. static let requestAuthHex = "0016000200000000020100054B314720000804000101" static let sessionKeyPrefixHex = "0095000200000000020100054B3147200008000080" static let navContextHex = "0016000200000000020100054B31472000052E00011E" @@ -79,7 +78,6 @@ enum K1GCodec { static let projectionOffHex = "0016000200000000020100054B3147200006050001AA" static let buttonAckPrefixHex = "0016000200000000020100054B3147200006800001" - // Initial app-like burst. nil marks the dynamic hostname announce slot. static let initialBurst: [String?] = [ requestAuthHex, nil, @@ -92,7 +90,6 @@ enum K1GCodec { "0044000A00000000020100054B3147200906080001FF060300015506040001A2060F0001AA0601000101054C000113052D00020000051B0001190521000132054D000132" ] - // Reference route-card packet used only as a template. buildRouteCard replaces title and length. private static let navTemplateHex = "007E001100000000020100054B31472025050100145461696C6C65206465204D617320647520477200" + "050200013C050300013405050002000A05060001300507000130050800043033303305540001300509" + @@ -112,23 +109,18 @@ enum K1GCodec { let subtype = data[offset + 1] let length = Int(data[offset + 2]) << 8 | Int(data[offset + 3]) offset += 4 - guard offset <= data.count else { break } let end = min(data.count, offset + length) - let payload = Data(data[offset.. Data { var bytes = [UInt8](packet) - let marker: [UInt8] = [0x4B, 0x31, 0x47, 0x20] // K1G + let marker: [UInt8] = [0x4B, 0x31, 0x47, 0x20] guard let markerIndex = find(marker, in: bytes), markerIndex + 4 < bytes.count else { throw DashProtocolError.missingK1GMarker } @@ -139,8 +131,7 @@ enum K1GCodec { static func hostnameAnnounce(_ hostname: String) -> Data { let raw = Data(hostname.utf8.prefix(200)) var body = (try? HexCodec.data(from: "0021000200000000020100054B314720")) ?? Data() - let lengthField = UInt8(clamping: raw.count + 1) - body.append(contentsOf: [0x01, 0x06, 0x0B, 0x00, lengthField]) + 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) @@ -163,11 +154,10 @@ enum K1GCodec { 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() - output.append(template.prefix(oldTitleStart)) - var lengthBytes = withUnsafeBytes(of: UInt16(clamping: titleData.count).bigEndian) { Data($0) } + + var output = Data(template.prefix(oldTitleStart)) + let lengthBytes = withUnsafeBytes(of: UInt16(clamping: titleData.count).bigEndian) { Data($0) } output.replaceSubrange(titleTLVOffset + 2.. Int? { guard !needle.isEmpty, haystack.count >= needle.count else { return nil } - for i in 0...(haystack.count - needle.count) where Array(haystack[i..<(i + needle.count)]) == needle { - return i + for i in 0...(haystack.count - needle.count) { + if haystack[i..<(i + needle.count)].elementsEqual(needle) { return i } } return nil } @@ -225,27 +215,19 @@ enum DashProtocolEvent: Hashable, Sendable { enum DashEventDecoder { static func events(from datagram: Data) -> [DashProtocolEvent] { guard let envelope = K1GCodec.decode(datagram) else { return [] } - var events: [DashProtocolEvent] = [] - for segment in envelope.segments { + return envelope.segments.map { segment in switch (segment.type, segment.subtype) { - case (0x07, 0x00): - events.append(.rsaModulus(segment.payload)) - case (0x07, 0x03): - events.append(.rsaExponent(segment.payload)) + case (0x07, 0x00): return .rsaModulus(segment.payload) + case (0x07, 0x03): return .rsaExponent(segment.payload) case (0x07, 0x01): let status = segment.payload.first ?? 0 - events.append(status == 0x01 ? .authAccepted : .authRejected(status)) + return status == 0x01 ? .authAccepted : .authRejected(status) case (0x09, 0x00): - if let byte = segment.payload.first, let button = DashButton(rawValue: byte) { - events.append(.button(button)) - } else { - events.append(.segment(segment)) - } - default: - events.append(.segment(segment)) + if let value = segment.payload.first, let button = DashButton(rawValue: value) { return .button(button) } + return .segment(segment) + default: return .segment(segment) } } - return events } } @@ -263,8 +245,6 @@ enum DashAuthenticator { return Data(bytes) } - /// Public interoperability behavior: payload = UTF8(SSID) || 32-byte AES key, - /// encrypted with the dash-provided RSA-1024 key using PKCS#1 v1.5 padding. static func encryptedSessionPayload( ssid: String, modulus: Data, @@ -278,16 +258,20 @@ enum DashAuthenticator { kSecAttrKeyClass: kSecAttrKeyClassPublic, kSecAttrKeySizeInBits: modulus.count * 8 ] + var error: Unmanaged? guard let key = SecKeyCreateWithData(publicKeyDER as CFData, attributes as CFDictionary, &error) else { - throw error?.takeRetainedValue() ?? DashProtocolError.publicKeyCreationFailed as CFError + 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 { - throw error?.takeRetainedValue() ?? DashProtocolError.rsaEncryptionFailed as CFError + if let error { throw error.takeRetainedValue() } + throw DashProtocolError.rsaEncryptionFailed } return encrypted as Data } @@ -295,15 +279,12 @@ enum DashAuthenticator { private enum DER { static func rsaPublicKey(modulus: Data, exponent: Data) -> Data { - let n = integer(modulus) - let e = integer(exponent) - return sequence(n + e) + sequence(integer(modulus) + integer(exponent)) } private static func integer(_ raw: Data) -> Data { - var value = raw.drop { $0 == 0 } - if value.isEmpty { value = Data([0]) } - var body = Data(value) + 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 } @@ -324,8 +305,6 @@ private enum DER { } } -// MARK: - Errors - enum DashProtocolError: LocalizedError { case invalidHex case missingK1GMarker From 0a2e4272d90d3b5342fd702247619310f2f8a7d4 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 16:55:30 +0530 Subject: [PATCH 020/112] fix: harden renderer H264 output parsing and RTP fragmentation --- RideDash/ProjectionCore/ProjectionCore.swift | 130 +++++++++---------- 1 file changed, 60 insertions(+), 70 deletions(-) diff --git a/RideDash/ProjectionCore/ProjectionCore.swift b/RideDash/ProjectionCore/ProjectionCore.swift index 411caa6..7692b09 100644 --- a/RideDash/ProjectionCore/ProjectionCore.swift +++ b/RideDash/ProjectionCore/ProjectionCore.swift @@ -54,66 +54,66 @@ final class DashFrameRenderer { throw ProjectionError.pixelBufferMissingBaseAddress } - let colorSpace = CGColorSpaceCreateDeviceRGB() guard let context = CGContext( data: baseAddress, width: width, height: height, bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(pixelBuffer), - space: colorSpace, + space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue ) else { throw ProjectionError.contextCreationFailed } - // CoreGraphics coordinates are flipped relative to UIKit text APIs. context.setFillColor(UIColor.black.cgColor) - context.fill(CGRect(x: 0, y: 0, width: width, height: height)) + context.fill(CGRect(x: 0, y: 0, width: CGFloat(width), height: CGFloat(height))) UIGraphicsPushContext(context) defer { UIGraphicsPopContext() } if state.isCalibrationGrid { drawCalibration(in: context) } else { - drawNavigation(state, in: context) + drawNavigation(state) } return pixelBuffer } private func drawCalibration(in context: CGContext) { - let rect = CGRect(x: 0, y: 0, width: width, height: height) + let w = CGFloat(width) + let h = CGFloat(height) + let rect = CGRect(x: 0, y: 0, width: w, height: h) context.setStrokeColor(UIColor.white.withAlphaComponent(0.35).cgColor) context.setLineWidth(1) stride(from: 0, through: width, by: 25).forEach { x in - context.move(to: CGPoint(x: x, y: 0)) - context.addLine(to: CGPoint(x: x, y: height)) + 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: y)) - context.addLine(to: CGPoint(x: width, y: y)) + 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: rect.insetBy(dx: 7, dy: 7)) - context.move(to: CGPoint(x: width / 2, y: 0)) - context.addLine(to: CGPoint(x: width / 2, y: height)) - context.move(to: CGPoint(x: 0, y: height / 2)) - context.addLine(to: CGPoint(x: width, y: height / 2)) + 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: 80, y: 125, width: 366, height: 40), size: 24, weight: .bold, alignment: .center) } - private func drawNavigation(_ state: ProjectionUIState, in context: CGContext) { - let safe = CGRect(x: 34, y: 22, width: width - 68, height: height - 44) + 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) - // Destination header. 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) - // Maneuver card. let card = CGRect(x: safe.minX + 34, y: safe.minY + 40, width: safe.width - 68, height: 104) let path = UIBezierPath(roundedRect: card, cornerRadius: 24) UIColor(white: 0.10, alpha: 1).setFill() @@ -121,13 +121,12 @@ final class DashFrameRenderer { drawText(state.maneuver, frame: CGRect(x: card.minX + 16, y: card.minY + 13, width: card.width - 32, height: 42), size: 32, 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) - // Bottom glance row. 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: "\(Int(state.speedKph.rounded()))", x: safe.maxX - 127, y: safe.maxY - 70, width: 105) if let status = state.statusMessage { - drawText(status, frame: CGRect(x: 90, y: height - 25, width: width - 180, height: 18), size: 11, weight: .medium, alignment: .center, color: .systemYellow) + drawText(status, frame: CGRect(x: 90, y: h - 25, width: w - 180, height: 18), size: 11, weight: .medium, alignment: .center, color: .systemYellow) } } @@ -166,7 +165,7 @@ struct H264NALUnit: Sendable, Hashable { } final class H264Encoder { - var onNALUnits: (@Sendable ([H264NALUnit], CMTime) -> Void)? + var onNALUnits: (([H264NALUnit], CMTime) -> Void)? private let width: Int32 private let height: Int32 @@ -206,7 +205,6 @@ final class H264Encoder { private func configure() throws { var created: VTCompressionSession? - let refcon = Unmanaged.passUnretained(self).toOpaque() let status = VTCompressionSessionCreate( allocator: kCFAllocatorDefault, width: width, @@ -216,7 +214,7 @@ final class H264Encoder { imageBufferAttributes: nil, compressedDataAllocator: nil, outputCallback: Self.outputCallback, - refcon: refcon, + refcon: Unmanaged.passUnretained(self).toOpaque(), compressionSessionOut: &created ) guard status == noErr, let created else { throw ProjectionError.videoToolbox(status) } @@ -225,13 +223,13 @@ final class H264Encoder { try set(kVTCompressionPropertyKey_RealTime, value: kCFBooleanTrue) try set(kVTCompressionPropertyKey_ProfileLevel, value: kVTProfileLevel_H264_Baseline_AutoLevel) try set(kVTCompressionPropertyKey_AllowFrameReordering, value: kCFBooleanFalse) - try set(kVTCompressionPropertyKey_AverageBitRate, value: bitrate as CFNumber) - try set(kVTCompressionPropertyKey_ExpectedFrameRate, value: fps as CFNumber) - try set(kVTCompressionPropertyKey_MaxKeyFrameInterval, value: (fps * 2) as CFNumber) - let dataRate: [Int] = [bitrate / 8, 1] - try set(kVTCompressionPropertyKey_DataRateLimits, value: dataRate as CFArray) - let prepare = VTCompressionSessionPrepareToEncodeFrames(created) - guard prepare == noErr else { throw ProjectionError.videoToolbox(prepare) } + try set(kVTCompressionPropertyKey_AverageBitRate, value: NSNumber(value: bitrate)) + try set(kVTCompressionPropertyKey_ExpectedFrameRate, value: NSNumber(value: fps)) + try set(kVTCompressionPropertyKey_MaxKeyFrameInterval, value: NSNumber(value: fps * 2)) + let dataRateLimits = [NSNumber(value: bitrate / 8), NSNumber(value: 1)] as CFArray + try set(kVTCompressionPropertyKey_DataRateLimits, value: dataRateLimits) + let prepareStatus = VTCompressionSessionPrepareToEncodeFrames(created) + guard prepareStatus == noErr else { throw ProjectionError.videoToolbox(prepareStatus) } } private func set(_ key: CFString, value: CFTypeRef) throws { @@ -245,20 +243,15 @@ final class H264Encoder { let refcon, let sampleBuffer, CMSampleBufferDataIsReady(sampleBuffer) else { return } - let encoder = Unmanaged.fromOpaque(refcon).takeUnretainedValue() - encoder.consume(sampleBuffer) + Unmanaged.fromOpaque(refcon).takeUnretainedValue().consume(sampleBuffer) } private func consume(_ sampleBuffer: CMSampleBuffer) { var units: [H264NALUnit] = [] - let attachments = CMSampleBufferGetSampleAttachmentsArray(sampleBuffer, createIfNecessary: false) - let isKeyframe: Bool = { - guard let attachments, - CFArrayGetCount(attachments) > 0, - let raw = CFArrayGetValueAtIndex(attachments, 0) else { return false } - let dictionary = unsafeBitCast(raw, to: CFDictionary.self) as NSDictionary - return dictionary[kCMSampleAttachmentKey_NotSync] == nil - }() + + let attachments = CMSampleBufferGetSampleAttachmentsArray(sampleBuffer, createIfNecessary: false) as? [[CFString: Any]] + let notSync = attachments?.first?[kCMSampleAttachmentKey_NotSync] as? Bool ?? false + let isKeyframe = !notSync if isKeyframe, let format = CMSampleBufferGetFormatDescription(sampleBuffer) { for index in 0..<2 { @@ -302,7 +295,7 @@ final class H264Encoder { Int(bytes[offset + 3]) offset += 4 guard nalLength > 0, offset + nalLength <= totalLength else { break } - units.append(.init(bytes: Data(bytes: bytes + offset, count: nalLength), isParameterSet: false)) + units.append(.init(bytes: Data(bytes: bytes.advanced(by: offset), count: nalLength), isParameterSet: false)) offset += nalLength } @@ -333,26 +326,26 @@ final class H264RTPPacketizer { let isLastUnit = unitIndex == units.count - 1 let bytes = unit.bytes guard let first = bytes.first else { continue } + if bytes.count <= maxPayload { packets.append(makePacket(payload: bytes, marker: isLastUnit)) - } else { - let nri = first & 0x60 - let forbidden = first & 0x80 - let nalType = first & 0x1F - let fuIndicator = forbidden | nri | 28 - let body = bytes.dropFirst() - let fragmentSize = maxPayload - 2 - var offset = 0 - while offset < body.count { - let end = min(body.count, offset + fragmentSize) - 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[offset.. Data { var packet = Data(capacity: 12 + payload.count) - packet.append(0x80) // RTP v2 + packet.append(0x80) packet.append((marker ? 0x80 : 0) | payloadType) appendBE(sequence, to: &packet) appendBE(timestamp, to: &packet) @@ -372,8 +365,8 @@ final class H264RTPPacketizer { } private func appendBE(_ value: T, to data: inout Data) { - var be = value.bigEndian - withUnsafeBytes(of: &be) { data.append(contentsOf: $0) } + var bigEndian = value.bigEndian + withUnsafeBytes(of: &bigEndian) { data.append(contentsOf: $0) } } } @@ -391,11 +384,7 @@ final class ProjectionStreamer: ObservableObject { private var renderTask: Task? private var encoder: H264Encoder? private var packetizer: H264RTPPacketizer? - private let renderer: DashFrameRenderer - - init(renderer: DashFrameRenderer = DashFrameRenderer()) { - self.renderer = renderer - } + private var renderer = DashFrameRenderer() func start( coordinator: DashSessionCoordinator, @@ -404,6 +393,7 @@ final class ProjectionStreamer: ObservableObject { ) throws { stop() state = .starting + renderer = DashFrameRenderer(width: profile.renderWidth, height: profile.renderHeight) let encoder = try H264Encoder( width: profile.renderWidth, height: profile.renderHeight, @@ -436,14 +426,14 @@ final class ProjectionStreamer: ObservableObject { coordinator.beginProjectionHeartbeat() state = .streaming let frameDuration = 1.0 / Double(max(1, profile.fps)) - renderTask = Task { [weak self] in + renderTask = Task { [weak self, weak coordinator] in + guard let coordinator else { return } var frame: Int64 = 0 while !Task.isCancelled { guard let self else { return } do { let buffer = try self.renderer.render(stateProvider()) - let pts = CMTime(value: frame, timescale: CMTimeScale(max(1, profile.fps))) - try encoder.encode(buffer, pts: pts) + try encoder.encode(buffer, pts: CMTime(value: frame, timescale: CMTimeScale(max(1, profile.fps)))) self.renderedFrames += 1 frame += 1 } catch { From 945463cf9a908738863d8da31ed038ff5dcc055e Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 16:57:16 +0530 Subject: [PATCH 021/112] fix: make UDP readiness state explicit and deterministic --- RideDash/DashConnectivity/DashTransport.swift | 134 +++++++++++------- 1 file changed, 79 insertions(+), 55 deletions(-) diff --git a/RideDash/DashConnectivity/DashTransport.swift b/RideDash/DashConnectivity/DashTransport.swift index 067cf10..0c53ef8 100644 --- a/RideDash/DashConnectivity/DashTransport.swift +++ b/RideDash/DashConnectivity/DashTransport.swift @@ -35,8 +35,8 @@ final class DashTransport: ObservableObject { } @Published private(set) var state: State = .stopped - @Published private(set) var receivedPackets: Int = 0 - @Published private(set) var sentPackets: Int = 0 + @Published private(set) var receivedPackets = 0 + @Published private(set) var sentPackets = 0 @Published private(set) var lastError: String? var onDatagram: (@Sendable (DashDatagram) -> Void)? @@ -46,11 +46,13 @@ final class DashTransport: ObservableObject { private var videoConnection: NWConnection? private var inputListener: NWListener? private var inputConnections: [ObjectIdentifier: NWConnection] = [:] - private var profile: DashProtocolProfile? + private var controlReady = false + private var listenerReady = false func start(profile: DashProtocolProfile) throws { stop() - guard !profile.host.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + 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), @@ -59,9 +61,10 @@ final class DashTransport: ObservableObject { throw DashTransportError.invalidPort } - self.profile = profile state = .preparing lastError = nil + controlReady = false + listenerReady = false let control = NWConnection( host: NWEndpoint.Host(profile.broadcastHost), @@ -69,7 +72,9 @@ final class DashTransport: ObservableObject { using: .udp ) controlConnection = control - observe(connection: control, label: "control") + control.stateUpdateHandler = { [weak self] newState in + Task { @MainActor in self?.handleControlState(newState) } + } control.start(queue: queue) let video = NWConnection( @@ -78,9 +83,11 @@ final class DashTransport: ObservableObject { using: .udp ) videoConnection = video - video.stateUpdateHandler = { [weak self] state in - guard case .failed(let error) = state else { return } - Task { @MainActor in self?.lastError = "Video UDP: \(error.localizedDescription)" } + 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) @@ -89,35 +96,21 @@ final class DashTransport: ObservableObject { let listener = try NWListener(using: parameters, on: inputPort) inputListener = listener listener.stateUpdateHandler = { [weak self] newState in - Task { @MainActor in - guard let self else { return } - switch newState { - case .ready: - if self.controlConnection?.state == .ready { self.state = .ready } - case .waiting(let error): - self.state = .waiting("Input listener: \(error.localizedDescription)") - case .failed(let error): - self.state = .failed("Input listener: \(error.localizedDescription)") - self.lastError = error.localizedDescription - default: - break - } - } + Task { @MainActor in self?.handleListenerState(newState) } } listener.newConnectionHandler = { [weak self] connection in - guard let self else { return } - self.acceptInput(connection) + self?.acceptInput(connection) } listener.start(queue: queue) } - /// Backward-compatible diagnostic route used by DiagnosticsView. + /// 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.videoPort = port profile.controlPort = port + profile.videoPort = port try start(profile: profile) } @@ -130,7 +123,8 @@ final class DashTransport: ObservableObject { videoConnection = nil inputListener = nil inputConnections.removeAll() - profile = nil + controlReady = false + listenerReady = false state = .stopped } @@ -152,12 +146,13 @@ final class DashTransport: ObservableObject { return } Task { @MainActor in - self?.sentPackets += 1 - self?.emit(.init( + guard let self else { return } + self.sentPackets += 1 + self.emit(.init( timestamp: .now, direction: .outbound, channel: channel, - endpoint: self?.endpointDescription(connection.endpoint) ?? "unknown", + endpoint: self.endpointDescription(connection.endpoint), data: data )) } @@ -166,37 +161,66 @@ final class DashTransport: ObservableObject { } } - private func observe(connection: NWConnection, label: String) { - connection.stateUpdateHandler = { [weak self, weak connection] newState in - Task { @MainActor in - guard let self else { return } - switch newState { - case .setup, .preparing: - self.state = .preparing - case .ready: - if self.inputListener?.state == .ready { self.state = .ready } - case .waiting(let error): - self.state = .waiting("\(label): \(error.localizedDescription)") - case .failed(let error): - self.state = .failed("\(label): \(error.localizedDescription)") - self.lastError = error.localizedDescription - case .cancelled: - if connection === self.controlConnection { self.state = .stopped } - @unknown default: - self.state = .waiting("Unknown Network.framework state") - } + 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 + if inputListener == nil { state = .stopped } + @unknown default: + state = .waiting("Unknown control transport state") + } + } + + private func handleListenerState(_ newState: NWListener.State) { + switch newState { + case .setup, .waiting: + if case .waiting(let error) = newState { + 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 guard let self, let connection else { return } - if case .ready = state { self.receiveNext(on: connection) } - if case .failed = state { self.inputConnections.removeValue(forKey: id) } - if case .cancelled = state { self.inputConnections.removeValue(forKey: id) } + switch state { + case .ready: + self.receiveNext(on: connection) + case .failed, .cancelled: + self.inputConnections.removeValue(forKey: id) + default: + break + } } connection.start(queue: queue) } @@ -239,8 +263,8 @@ enum DashTransportError: LocalizedError { var errorDescription: String? { switch self { - case .invalidHost: return "Dash host is empty." - case .invalidPort: return "Dash UDP port is invalid." + 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." } } From cab3a0441481d1b8239f15770920d052fd6d09ab Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 16:57:57 +0530 Subject: [PATCH 022/112] fix: handle listener state patterns explicitly --- RideDash/DashConnectivity/DashTransport.swift | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/RideDash/DashConnectivity/DashTransport.swift b/RideDash/DashConnectivity/DashTransport.swift index 0c53ef8..61b6e28 100644 --- a/RideDash/DashConnectivity/DashTransport.swift +++ b/RideDash/DashConnectivity/DashTransport.swift @@ -178,7 +178,6 @@ final class DashTransport: ObservableObject { state = .failed("Control: \(error.localizedDescription)") case .cancelled: controlReady = false - if inputListener == nil { state = .stopped } @unknown default: state = .waiting("Unknown control transport state") } @@ -186,10 +185,11 @@ final class DashTransport: ObservableObject { private func handleListenerState(_ newState: NWListener.State) { switch newState { - case .setup, .waiting: - if case .waiting(let error) = newState { - state = .waiting("Input listener: \(error.localizedDescription)") - } + case .setup: + listenerReady = false + case .waiting(let error): + listenerReady = false + state = .waiting("Input listener: \(error.localizedDescription)") case .ready: listenerReady = true updateReadyState() From 3abc53f2d29ae408a45785aebabc3340e1a88200 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 16:58:29 +0530 Subject: [PATCH 023/112] fix: harden live route step tracking and shared destination parsing --- RideDash/NavigationCore/NavigationCore.swift | 59 +++++++++++--------- 1 file changed, 33 insertions(+), 26 deletions(-) diff --git a/RideDash/NavigationCore/NavigationCore.swift b/RideDash/NavigationCore/NavigationCore.swift index 28e3fb9..d685d16 100644 --- a/RideDash/NavigationCore/NavigationCore.swift +++ b/RideDash/NavigationCore/NavigationCore.swift @@ -39,8 +39,6 @@ final class NavigationLocationService: NSObject, ObservableObject, CLLocationMan } func setBackgroundNavigationEnabled(_ enabled: Bool) { - // This is only useful when the app target has the legitimate location background mode. - // It does not guarantee indefinite video/network execution while the phone is locked. manager.allowsBackgroundLocationUpdates = enabled manager.showsBackgroundLocationIndicator = enabled } @@ -69,7 +67,9 @@ struct ResolvedDestination: Identifiable, Hashable { 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 + lhs.name == rhs.name && + lhs.coordinate.latitude == rhs.coordinate.latitude && + lhs.coordinate.longitude == rhs.coordinate.longitude } func hash(into hasher: inout Hasher) { @@ -93,8 +93,9 @@ enum RouteResolver { return .init(name: url.host ?? "Shared destination", coordinate: coordinate) } let components = URLComponents(url: url, resolvingAgainstBaseURL: false) - let keys = ["q", "query", "destination", "daddr", "ll"] - if let value = components?.queryItems?.first(where: { keys.contains($0.name.lowercased()) })?.value { + 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) } @@ -117,10 +118,7 @@ enum RouteResolver { } 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 - ) + return .init(name: item.name ?? query, coordinate: item.placemark.coordinate) } private static func coordinate(from text: String) -> CLLocationCoordinate2D? { @@ -164,6 +162,7 @@ final class NavigationViewModel: ObservableObject { isCalculating = true errorMessage = nil defer { isCalculating = false } + do { let resolved = try await RouteResolver.resolve(destinationInput, near: locationService.location) destination = resolved @@ -176,6 +175,7 @@ final class NavigationViewModel: ObservableObject { request.destination = MKMapItem(placemark: MKPlacemark(coordinate: resolved.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 } self.route = route @@ -203,7 +203,9 @@ final class NavigationViewModel: ObservableObject { 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 { + if let value = components?.queryItems?.first(where: { + ["url", "q", "destination"].contains($0.name.lowercased()) + })?.value { destinationInput = value } } else { @@ -212,14 +214,15 @@ final class NavigationViewModel: ObservableObject { } 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: - if let route { activeStepIndex = min(route.steps.count - 1, activeStepIndex + 1) } + activeStepIndex = min(lastIndex, activeStepIndex + 1) case .down, .click: - // Recenter/return to live guidance rather than changing vehicle state. - if let route, let location = locationService.location { + if let location = locationService.location { activeStepIndex = nearestUpcomingStep(in: route, to: location) } } @@ -228,7 +231,7 @@ final class NavigationViewModel: ObservableObject { private func handleLocation(_ location: CLLocation?) { guard let location else { return } - if let route { + if let route, !route.steps.isEmpty { let suggested = nearestUpcomingStep(in: route, to: location) if suggested >= activeStepIndex { activeStepIndex = suggested } } @@ -245,9 +248,10 @@ final class NavigationViewModel: ObservableObject { return } - let index = min(max(0, activeStepIndex), max(0, route.steps.count - 1)) - let step = route.steps.isEmpty ? nil : route.steps[index] - let instruction = step?.instructions.isEmpty == false ? step!.instructions : "Continue" + 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 distance = step.map { Self.formatDistance($0.distance) } ?? "--" let etaDate = Date().addingTimeInterval(route.expectedTravelTime) let etaFormatter = DateFormatter() @@ -267,21 +271,23 @@ final class NavigationViewModel: ObservableObject { } private func firstUsableStep(in route: MKRoute?) -> Int { - guard let route else { return 0 } + 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 } - var bestIndex = activeStepIndex + let start = min(max(0, activeStepIndex), route.steps.count - 1) + var bestIndex = start var bestDistance = CLLocationDistance.greatestFiniteMagnitude - for index in activeStepIndex.. 0 else { continue } - let coordinate = points[max(0, step.polyline.pointCount - 1)].coordinate - let end = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude) - let distance = location.distance(from: end) + 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 @@ -292,8 +298,9 @@ final class NavigationViewModel: ObservableObject { } private static func formatDistance(_ meters: CLLocationDistance) -> String { - if meters < 1_000 { return "\(Int(max(0, meters).rounded())) m" } - return String(format: "%.1f km", meters / 1_000) + let safeMeters = max(0, meters) + if safeMeters < 1_000 { return "\(Int(safeMeters.rounded())) m" } + return String(format: "%.1f km", safeMeters / 1_000) } } From 4b90d13d50b64b3399d7ceb9ede255e26e16266e Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 16:58:37 +0530 Subject: [PATCH 024/112] refactor: replace generated product feature file with clean implementation --- .../Features/Product/ProductFeatures.swift | 831 ------------------ 1 file changed, 831 deletions(-) delete mode 100644 RideDash/Features/Product/ProductFeatures.swift diff --git a/RideDash/Features/Product/ProductFeatures.swift b/RideDash/Features/Product/ProductFeatures.swift deleted file mode 100644 index 71f5bbd..0000000 --- a/RideDash/Features/Product/ProductFeatures.swift +++ /dev/null @@ -1,831 +0,0 @@ -import MapKit -import SwiftData -import SwiftUI - -// MARK: - Persistence 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 - ) { - self.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 = "") { - self.id = UUID() - self.date = date - self.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) { - self.id = UUID() - self.date = date - self.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) { - self.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 = "") { - self.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] - - private var activeVehicle: Vehicle? { vehicles.first(where: \ .isActive) ?? vehicles.first } - - var body: some View { - List { - Section { - HStack { - VStack(alignment: .leading, spacing: 4) { - Text("Display") - .font(.caption) - .foregroundStyle(.secondary) - Text(session.state.label) - .font(.headline) - } - Spacer() - Circle() - .fill(sessionIndicator) - .frame(width: 12, height: 12) - } - } - - if let vehicle = activeVehicle { - Section("Active vehicle") { - LabeledContent(vehicle.name, value: "\(vehicle.odometerKm, specifier: "%.0f") km") - if !vehicle.registrationNumber.isEmpty { - LabeledContent("Registration", value: vehicle.registrationNumber) - } - } - } - - Section("Current navigation") { - LabeledContent("Destination", value: navigation.destination?.name ?? "Not set") - LabeledContent("Instruction", value: navigation.projectionState.maneuver) - LabeledContent("Next turn", value: navigation.projectionState.distanceToManeuver) - } - - Section("This month") { - let calendar = Calendar.current - let total = expenses - .filter { calendar.isDate($0.date, equalTo: .now, toGranularity: .month) } - .reduce(0) { $0 + $1.amount } - LabeledContent("Expenses", value: total.formatted(.currency(code: currencyCode))) - } - } - .navigationTitle("RideDash") - } - - private var currencyCode: String { UserDefaults.standard.string(forKey: "settings.currency") ?? "INR" } - - private var sessionIndicator: Color { - switch session.state { - case .projecting, .navigationReady, .authenticated: return .green - case .failed: return .red - case .disconnected: return .secondary - default: return .orange - } - } -} - -// MARK: - Navigation screen - -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 { - MapUserLocationButton() - MapCompass() - } - .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 { 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) { - Text(navigation.projectionState.maneuver).font(.headline).lineLimit(1) - Text("\(navigation.projectionState.distanceToManeuver) · ETA \(navigation.projectionState.eta)") - .font(.caption).foregroundStyle(.secondary) - } - Spacer() - Button("Apple Maps") { navigation.openInAppleMaps() } - .buttonStyle(.bordered) - } - } - - if session.state == .authenticated || session.state == .navigationReady || session.state == .projecting { - HStack { - Button("Enter Dash Nav") { - Task { try? await session.enterNavigation(title: navigation.destination?.name ?? "Navigation") } - } - .buttonStyle(.bordered) - - Button(streamer.state == .streaming ? "Streaming" : "Start Projection") { - startProjection(calibration: false) - } - .buttonStyle(.borderedProminent) - .disabled(session.state != .navigationReady && session.state != .projecting) - - Button("Stop", role: .destructive) { - streamer.stop() - Task { await session.stopProjection() } - } - .buttonStyle(.bordered) - } - } - } - .padding() - .background(.regularMaterial) - } - .navigationTitle("Navigation") - .navigationBarTitleDisplayMode(.inline) - .onAppear { navigation.startLocation() } - } - - private func startProjection(calibration: Bool) { - var profile = DashProtocolProfile.publicReference - profile.host = dashHost - profile.broadcastHost = broadcastHost - profile.fps = fps - profile.bitrateKbps = bitrate - do { - try streamer.start(coordinator: session, profile: profile) { - if calibration { - var state = navigation.projectionState - state.isCalibrationGrid = true - return state - } - return navigation.projectionState - } - } catch { - session.log.append(error.localizedDescription, category: "projection", level: .error) - } - } -} - -// MARK: - Display connection - -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 calibration = 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.isEmpty) - LabeledContent("Wi-Fi", value: wifi.status.description) - } - - Section("Protocol profile") { - TextField("Dash host", text: $host) - TextField("Broadcast", text: $broadcastHost) - Stepper("Control UDP \(controlPort)", value: $controlPort, in: 1...65535) - Stepper("Input UDP \(inputPort)", value: $inputPort, in: 1...65535) - Stepper("Video UDP \(videoPort)", value: $videoPort, in: 1...65535) - 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) - LabeledContent("State", value: session.state.label) - LabeledContent("RX", value: "\(session.transport.receivedPackets)") - LabeledContent("TX", value: "\(session.transport.sentPackets)") - - 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: $calibration) - Button("Start H.264/RTP Projection") { - do { - try streamer.start(coordinator: session, profile: profile) { - var state = navigation.projectionState - state.isCalibrationGrid = calibration - return state - } - } catch { - session.log.append(error.localizedDescription, category: "projection", level: .error) - } - } - .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("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 - ) - } -} - -// MARK: - Vehicles - -struct VehiclesView: View { - @Environment(\.modelContext) private var context - @Query(sort: \Vehicle.name) private var vehicles: [Vehicle] - @State private var showAdd = 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) { - 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 { indexes in indexes.forEach { context.delete(vehicles[$0]) } } - } - .navigationTitle("Vehicles") - .toolbar { Button { showAdd = true } label: { Image(systemName: "plus") } } - .sheet(isPresented: $showAdd) { 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: .whitespaces).isEmpty) - } - } - } - } -} - -struct VehicleDetailView: View { - @Bindable var vehicle: Vehicle - var body: some View { - Form { - 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", date: $vehicle.insuranceExpiry) - OptionalDateEditor(title: "PUC", date: $vehicle.pucExpiry) - OptionalDateEditor(title: "Last service", date: $vehicle.lastServiceDate) - } - Toggle("Active vehicle", isOn: $vehicle.isActive) - } - .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 fuel: [FuelLog] - @Query(sort: \MaintenanceRecord.date, order: .reverse) private var maintenance: [MaintenanceRecord] - @State private var showFuel = false - @State private var showMaintenance = false - - var body: some View { - List { - Section("Overview") { - LabeledContent("Fuel logs", value: "\(fuel.count)") - LabeledContent("Maintenance", value: "\(maintenance.count)") - LabeledContent("Calculated mileage", value: mileage.map { String(format: "%.1f km/L", $0) } ?? "Need 2 full-tank fills") - } - Section("Quick actions") { - Button("Log fuel") { showFuel = true } - Button("Log maintenance") { showMaintenance = true } - } - Section("Recent fuel") { - ForEach(fuel.prefix(10)) { entry in - LabeledContent("\(entry.litres, specifier: "%.1f") L", value: "\(entry.odometerKm, specifier: "%.0f") km") - } - .onDelete { indexes in indexes.forEach { context.delete(fuel[$0]) } } - } - Section("Recent maintenance") { - ForEach(maintenance.prefix(10)) { entry in - VStack(alignment: .leading) { - Text(entry.kind.rawValue).font(.headline) - Text("\(entry.odometerKm, specifier: "%.0f") km · \(entry.date.formatted(date: .abbreviated, time: .omitted))") - .font(.caption).foregroundStyle(.secondary) - } - } - } - } - .navigationTitle("Garage") - .sheet(isPresented: $showFuel) { AddFuelView() } - .sheet(isPresented: $showMaintenance) { AddMaintenanceView() } - } - - private var mileage: Double? { - let full = fuel.filter(\.fullTank).sorted { $0.odometerKm < $1.odometerKm } - guard full.count >= 2, let last = full.last else { return nil } - let previous = full[full.count - 2] - let distance = last.odometerKm - previous.odometerKm - guard distance > 0, last.litres > 0 else { return nil } - return distance / last.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 = "" - - var body: some View { - NavigationStack { - Form { - 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) - } - .navigationTitle("Maintenance") - .toolbar { - ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } } - ToolbarItem(placement: .confirmationAction) { - Button("Save") { context.insert(MaintenanceRecord(kind: kind, odometerKm: odometer, notes: notes)); dismiss() } - } - } - } - } -} - -// MARK: - Expenses - -struct ExpensesView: View { - @Environment(\.modelContext) private var context - @Query(sort: \Expense.date, order: .reverse) private var expenses: [Expense] - @State private var category: ExpenseCategory? - @State private var showAdd = false - @AppStorage("settings.currency") private var currency = "INR" - - private var filtered: [Expense] { category.map { chosen in expenses.filter { $0.category == chosen } } ?? expenses } - - var body: some View { - List { - Section { - LabeledContent("Total", value: filtered.reduce(0) { $0 + $1.amount }.formatted(.currency(code: currency))) - Picker("Filter", selection: $category) { - Text("All").tag(ExpenseCategory?.none) - ForEach(ExpenseCategory.allCases) { Text($0.rawValue).tag(Optional($0)) } - } - } - ForEach(filtered) { expense in - HStack { - VStack(alignment: .leading) { - 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 { indexes in indexes.forEach { context.delete(filtered[$0]) } } - } - .navigationTitle("Expenses") - .toolbar { - ToolbarItemGroup(placement: .topBarTrailing) { - ShareLink(item: CSVExporter.expenses(expenses)) { Image(systemName: "square.and.arrow.up") } - Button { showAdd = true } label: { Image(systemName: "plus") } - } - } - .sheet(isPresented: $showAdd) { 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 { - var lines = ["Date,Category,Amount,OdometerKm,Notes"] - let formatter = ISO8601DateFormatter() - for item in expenses { - lines.append([ - formatter.string(from: item.date), - escape(item.category.rawValue), - String(item.amount), - item.odometerKm.map(String.init) ?? "", - escape(item.notes) - ].joined(separator: ",")) - } - return lines.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 showAdd = false - - var body: some View { - List { - if rides.isEmpty { ContentUnavailableView("No rides", systemImage: "road.lanes", description: Text("Completed projected rides can be saved here.")) } - ForEach(rides) { ride in - VStack(alignment: .leading) { - 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 { indexes in indexes.forEach { context.delete(rides[$0]) } } - } - .navigationTitle("Rides") - .toolbar { Button { showAdd = true } label: { Image(systemName: "plus") } } - .sheet(isPresented: $showAdd) { 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" - @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("iOS behavior") { - Toggle("Request background navigation location", isOn: Binding( - get: { UserDefaults.standard.bool(forKey: "settings.backgroundLocation") }, - set: { value in - UserDefaults.standard.set(value, forKey: "settings.backgroundLocation") - navigation.locationService.setBackgroundNavigationEnabled(value) - } - )) - Text("Background location is legitimate for active navigation but does not guarantee that iOS will keep H.264/UDP projection alive after device lock.") - .font(.caption).foregroundStyle(.secondary) - } - Section("About") { - Text("RideDash is an independent ride/navigation companion designed around compatible Wi-Fi motorcycle displays. It does not implement ECU, brake, ABS, throttle, immobilizer, or other safety-critical vehicle control.") - .font(.caption) - } - } - .navigationTitle("Settings") - } -} From 79173df76cceb14e7992a0965dbe60c4f42f8367 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 16:59:51 +0530 Subject: [PATCH 025/112] feat: add clean local-first RideDash product experience --- .../Features/Product/ProductFeatures.swift | 991 ++++++++++++++++++ 1 file changed, 991 insertions(+) create mode 100644 RideDash/Features/Product/ProductFeatures.swift diff --git a/RideDash/Features/Product/ProductFeatures.swift b/RideDash/Features/Product/ProductFeatures.swift new file mode 100644 index 0000000..1b2088a --- /dev/null +++ b/RideDash/Features/Product/ProductFeatures.swift @@ -0,0 +1,991 @@ +import MapKit +import SwiftData +import SwiftUI +import UIKit + +// 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) + } + } + + 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) + } + + 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 { + 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) + } + 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) + LabeledContent("State", value: session.state.label) + LabeledContent("RX packets", value: "\(session.transport.receivedPackets)") + LabeledContent("TX packets", value: "\(session.transport.sentPackets)") + 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) + } + } + } + } + .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 = "" + + var body: some View { + NavigationStack { + Form { + 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) + } + .navigationTitle("Maintenance") + .toolbar { + ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } } + ToolbarItem(placement: .confirmationAction) { + Button("Save") { + context.insert(MaintenanceRecord(kind: kind, odometerKm: odometer, notes: notes)) + dismiss() + } + } + } + } + } +} + +// 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("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") + } +} From 0e79c83fa1c4f8561f4cf0b3a3ddae96f521c25b Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:00:36 +0530 Subject: [PATCH 026/112] fix: harden authentication gating and session lifecycle --- RideDash/App/DashSessionCoordinator.swift | 181 +++++++++++++++------- 1 file changed, 121 insertions(+), 60 deletions(-) diff --git a/RideDash/App/DashSessionCoordinator.swift b/RideDash/App/DashSessionCoordinator.swift index 6a12ac1..3088afa 100644 --- a/RideDash/App/DashSessionCoordinator.swift +++ b/RideDash/App/DashSessionCoordinator.swift @@ -36,7 +36,7 @@ final class DashSessionCoordinator: ObservableObject { @Published private(set) var state: State = .disconnected @Published private(set) var lastButton: DashButton? @Published private(set) var authenticatedSession: DashAuthenticatedSession? - @Published var routeTitle: String = "Navigation" + @Published var routeTitle = "Navigation" let transport: DashTransport let log: DiagnosticLog @@ -50,10 +50,13 @@ final class DashSessionCoordinator: ObservableObject { 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 authTimeoutTask: Task? private var projectionHeartbeatTask: Task? private var routeHeartbeatTask: Task? - private var navEntered = false init(transport: DashTransport = DashTransport(), log: DiagnosticLog = DiagnosticLog()) { self.transport = transport @@ -70,53 +73,52 @@ final class DashSessionCoordinator: ObservableObject { authTimeout: Duration = .seconds(8) ) async { disconnect() - self.ssid = ssid - self.hostname = hostname.isEmpty ? "iPhone" : hostname + self.ssid = ssid.trimmingCharacters(in: .whitespacesAndNewlines) + self.hostname = hostname.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? "iPhone" : hostname self.profile = profile - sequence = 0 - modulus = nil - exponent = nil - authenticatedSession = nil - navEntered = false + + guard !self.ssid.isEmpty else { + state = .failed("Display SSID is required") + return + } do { state = .startingTransport try transport.start(profile: profile) log.append("Control/input/video UDP transport requested", category: "session") - - // Network.framework is asynchronous. A short preparation window prevents - // the first burst from racing listener setup on normal device hardware. - try await Task.sleep(for: .milliseconds(250)) - try Task.checkCancellation() + 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") - - authTimeoutTask?.cancel() - authTimeoutTask = Task { [weak self] in - try? await Task.sleep(for: authTimeout) - guard !Task.isCancelled else { return } - await MainActor.run { - guard let self else { return } - if self.authenticatedSession == nil { - self.state = .failed("Authentication timed out") - self.log.append("Authentication timeout", category: "auth", level: .error) - } - } - } + startAuthTimeout(authTimeout) } catch { state = .failed(error.localizedDescription) log.append(error.localizedDescription, category: "session", level: .error) } } + func retryLastConnection() async { + let currentSSID = ssid + let currentHostname = hostname + let currentProfile = profile + guard !currentSSID.isEmpty else { return } + await connect(ssid: currentSSID, hostname: currentHostname, profile: currentProfile) + } + func enterNavigation(title: String? = nil) async throws { - guard authenticatedSession != nil else { throw DashSessionError.notAuthenticated } - if let title, !title.isEmpty { routeTitle = title } + guard authConfirmed, authenticatedSession != nil else { + throw DashSessionError.notAuthenticated + } + if let title, !title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + routeTitle = title + } + routeHeartbeatTask?.cancel() + projectionHeartbeatTask?.cancel() state = .enteringNavigation + try await sendHex(K1GCodec.navContextHex) try await sendHex(K1GCodec.emptyListsHex) @@ -137,9 +139,10 @@ final class DashSessionCoordinator: ObservableObject { } func beginProjectionHeartbeat() { - guard navEntered else { return } + 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 } @@ -156,18 +159,23 @@ final class DashSessionCoordinator: ObservableObject { func stopProjection() async { projectionHeartbeatTask?.cancel() + routeHeartbeatTask?.cancel() projectionHeartbeatTask = nil + routeHeartbeatTask = nil + guard navEntered else { return } state = .stopping do { try await sendHex(K1GCodec.projectionStopHex) try await sendHex(K1GCodec.projectionOffHex) - state = .authenticated + 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) } - navEntered = false } func disconnect() { @@ -177,23 +185,27 @@ final class DashSessionCoordinator: ObservableObject { authTimeoutTask = nil projectionHeartbeatTask = nil routeHeartbeatTask = nil + transport.stop() - navEntered = false - authenticatedSession = nil + sequence = 0 modulus = nil exponent = nil + pendingAESKey = nil + authenticatedSession = nil + authConfirmed = false + navEntered = false + lastButton = nil state = .disconnected } - // MARK: - RX + // MARK: - Receive path private func handle(_ datagram: DashDatagram) { - if datagram.direction == .inbound { - log.append( - "RX \(datagram.data.count)B \(HexCodec.string(datagram.data, maxBytes: 24))", - category: "packet" - ) - } + 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 { @@ -201,38 +213,55 @@ final class DashSessionCoordinator: ObservableObject { 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") + return + } + authenticatedSession = DashAuthenticatedSession(aesKey: key) + pendingAESKey = nil + authConfirmed = true state = .authenticated log.append("Dash authentication accepted", category: "auth") onAuthenticated?() + case .authRejected(let status): + pendingAESKey = nil authenticatedSession = nil + authConfirmed = false modulus = nil exponent = nil state = .requestingAuthentication - log.append("Dash authentication rejected status=0x\(String(format: "%02X", status))", category: "auth", level: .error) + log.append( + "Dash authentication rejected status=0x\(String(format: "%02X", status))", + category: "auth", + level: .error + ) Task { [weak self] in guard let self else { return } try? await self.sendHex(K1GCodec.requestAuthHex) self.state = .awaitingPublicKey } + case .button(let button): lastButton = button log.append("Dash input: \(String(describing: button))", category: "input") onButton?(button) if profile.respondToInput { Task { [weak self] in - guard let self else { return } - if let ack = try? K1GCodec.buttonAck(button.rawValue) { - try? await self.sendRaw(ack) - } + 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") @@ -242,7 +271,8 @@ final class DashSessionCoordinator: ObservableObject { } private func attemptSessionKeyIfReady() { - guard authenticatedSession == nil, + guard pendingAESKey == nil, + !authConfirmed, let modulus, let exponent, !ssid.isEmpty else { return } @@ -258,27 +288,23 @@ final class DashSessionCoordinator: ObservableObject { exponent: exponent, aesKey: aesKey ) - let packet = try K1GCodec.buildSessionKeyPacket(ciphertext: ciphertext) - try await self.sendRaw(packet) - self.authenticatedSession = DashAuthenticatedSession(aesKey: aesKey) - self.log.append("Encrypted AES session key sent", category: "auth") + 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) } } } - // MARK: - TX + // MARK: - Send path private func sendInitialBurst() async throws { for entry in K1GCodec.initialBurst { - let packet: Data - if let entry { - packet = try HexCodec.data(from: entry) - } else { - packet = K1GCodec.hostnameAnnounce(hostname) - } + let packet = try entry.map { try HexCodec.data(from: $0) } ?? K1GCodec.hostnameAnnounce(hostname) try await sendRaw(packet) try await Task.sleep(for: .milliseconds(20)) } @@ -300,7 +326,9 @@ final class DashSessionCoordinator: ObservableObject { while !Task.isCancelled { guard let self else { return } do { - try await self.sendRaw(K1GCodec.routeCard(title: self.routeTitle, projectionOn: true)) + try await self.sendRaw( + K1GCodec.routeCard(title: self.routeTitle, projectionOn: true) + ) } catch { self.log.append(error.localizedDescription, category: "heartbeat", level: .error) } @@ -308,14 +336,47 @@ final class DashSessionCoordinator: ObservableObject { } } } + + 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) + } + } + + 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 dash before entering navigation mode." + 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)" } } } From 0a7c937314318d266fffd2e8842bd2c7247986e0 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:01:11 +0530 Subject: [PATCH 027/112] refactor: align H264 RTP packaging with dash reference behavior --- RideDash/ProjectionCore/ProjectionCore.swift | 475 ------------------- 1 file changed, 475 deletions(-) delete mode 100644 RideDash/ProjectionCore/ProjectionCore.swift diff --git a/RideDash/ProjectionCore/ProjectionCore.swift b/RideDash/ProjectionCore/ProjectionCore.swift deleted file mode 100644 index 7692b09..0000000 --- a/RideDash/ProjectionCore/ProjectionCore.swift +++ /dev/null @@ -1,475 +0,0 @@ -import AVFoundation -import CoreGraphics -import CoreMedia -import CoreVideo -import Foundation -import UIKit -import VideoToolbox - -struct ProjectionUIState: Sendable, Hashable { - var destination: String = "RideDash" - var maneuver: String = "Continue" - var distanceToManeuver: String = "--" - var eta: String = "--" - var remainingDistance: String = "--" - var speedKph: Double = 0 - var gpsAccuracy: Double? = nil - var isCalibrationGrid = false - var statusMessage: String? = nil -} - -// MARK: - Frame 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 pixelBuffer: CVPixelBuffer? - let attributes: [CFString: Any] = [ - kCVPixelBufferCGImageCompatibilityKey: true, - kCVPixelBufferCGBitmapContextCompatibilityKey: true, - kCVPixelBufferIOSurfacePropertiesKey: [:] - ] - let status = CVPixelBufferCreate( - kCFAllocatorDefault, - width, - height, - kCVPixelFormatType_32BGRA, - attributes as CFDictionary, - &pixelBuffer - ) - guard status == kCVReturnSuccess, let pixelBuffer else { - throw ProjectionError.pixelBufferCreationFailed(status) - } - - CVPixelBufferLockBaseAddress(pixelBuffer, []) - defer { CVPixelBufferUnlockBaseAddress(pixelBuffer, []) } - guard let baseAddress = CVPixelBufferGetBaseAddress(pixelBuffer) else { - throw ProjectionError.pixelBufferMissingBaseAddress - } - - guard let context = CGContext( - data: baseAddress, - width: width, - height: height, - bitsPerComponent: 8, - bytesPerRow: CVPixelBufferGetBytesPerRow(pixelBuffer), - 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(in: context) - } else { - drawNavigation(state) - } - return pixelBuffer - } - - private func drawCalibration(in context: CGContext) { - let w = CGFloat(width) - let h = CGFloat(height) - let rect = CGRect(x: 0, y: 0, width: w, height: h) - context.setStrokeColor(UIColor.white.withAlphaComponent(0.35).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: rect.insetBy(dx: 7, dy: 7)) - 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: 80, y: 125, width: 366, height: 40), 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) - let path = UIBezierPath(roundedRect: card, cornerRadius: 24) - UIColor(white: 0.10, alpha: 1).setFill() - path.fill() - drawText(state.maneuver, frame: CGRect(x: card.minX + 16, y: card.minY + 13, width: card.width - 32, height: 42), size: 32, 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: "\(Int(state.speedKph.rounded()))", x: safe.maxX - 127, y: safe.maxY - 70, width: 105) - - if let status = state.statusMessage { - drawText(status, frame: CGRect(x: 90, y: h - 25, width: w - 180, height: 18), 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( - _ text: String, - frame: CGRect, - size: CGFloat, - weight: UIFont.Weight, - alignment: NSTextAlignment, - color: UIColor = .white - ) { - let paragraph = NSMutableParagraphStyle() - paragraph.alignment = alignment - paragraph.lineBreakMode = .byTruncatingTail - (text as NSString).draw( - in: frame, - withAttributes: [ - .font: UIFont.systemFont(ofSize: size, weight: weight), - .foregroundColor: color, - .paragraphStyle: paragraph - ] - ) - } -} - -// MARK: - H.264 - -struct H264NALUnit: Sendable, Hashable { - let bytes: Data - let isParameterSet: Bool -} - -final class H264Encoder { - var onNALUnits: (([H264NALUnit], CMTime) -> Void)? - - private let width: Int32 - private let height: Int32 - private let fps: Int - private let bitrate: Int - private var session: VTCompressionSession? - - init(width: Int, height: Int, fps: Int, bitrateKbps: Int) throws { - self.width = Int32(width) - self.height = Int32(height) - self.fps = max(1, fps) - self.bitrate = max(64, bitrateKbps) * 1_000 - try configure() - } - - deinit { - if let session { - VTCompressionSessionCompleteFrames(session, untilPresentationTimeStamp: .invalid) - VTCompressionSessionInvalidate(session) - } - } - - func encode(_ pixelBuffer: CVPixelBuffer, pts: CMTime) throws { - guard let session else { throw ProjectionError.encoderNotReady } - var flags = VTEncodeInfoFlags() - let status = VTCompressionSessionEncodeFrame( - session, - imageBuffer: pixelBuffer, - 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() 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, value: kCFBooleanTrue) - try set(kVTCompressionPropertyKey_ProfileLevel, value: kVTProfileLevel_H264_Baseline_AutoLevel) - try set(kVTCompressionPropertyKey_AllowFrameReordering, value: kCFBooleanFalse) - try set(kVTCompressionPropertyKey_AverageBitRate, value: NSNumber(value: bitrate)) - try set(kVTCompressionPropertyKey_ExpectedFrameRate, value: NSNumber(value: fps)) - try set(kVTCompressionPropertyKey_MaxKeyFrameInterval, value: NSNumber(value: fps * 2)) - let dataRateLimits = [NSNumber(value: bitrate / 8), NSNumber(value: 1)] as CFArray - try set(kVTCompressionPropertyKey_DataRateLimits, value: dataRateLimits) - let prepareStatus = VTCompressionSessionPrepareToEncodeFrames(created) - guard prepareStatus == noErr else { throw ProjectionError.videoToolbox(prepareStatus) } - } - - 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 } - Unmanaged.fromOpaque(refcon).takeUnretainedValue().consume(sampleBuffer) - } - - private func consume(_ sampleBuffer: CMSampleBuffer) { - var units: [H264NALUnit] = [] - - let attachments = CMSampleBufferGetSampleAttachmentsArray(sampleBuffer, createIfNecessary: false) as? [[CFString: Any]] - let notSync = attachments?.first?[kCMSampleAttachmentKey_NotSync] as? Bool ?? false - let isKeyframe = !notSync - - if isKeyframe, let format = CMSampleBufferGetFormatDescription(sampleBuffer) { - for index in 0..<2 { - var pointer: UnsafePointer? - var size = 0 - var count = 0 - var headerLength: Int32 = 0 - let result = CMVideoFormatDescriptionGetH264ParameterSetAtIndex( - format, - parameterSetIndex: index, - parameterSetPointerOut: &pointer, - parameterSetSizeOut: &size, - parameterSetCountOut: &count, - nalUnitHeaderLengthOut: &headerLength - ) - if result == noErr, let pointer { - units.append(.init(bytes: Data(bytes: pointer, count: size), isParameterSet: true)) - } - } - } - - guard let blockBuffer = CMSampleBufferGetDataBuffer(sampleBuffer) else { return } - var totalLength = 0 - var lengthAtOffset = 0 - var pointer: UnsafeMutablePointer? - let status = CMBlockBufferGetDataPointer( - blockBuffer, - atOffset: 0, - lengthAtOffsetOut: &lengthAtOffset, - totalLengthOut: &totalLength, - dataPointerOut: &pointer - ) - guard status == kCMBlockBufferNoErr, let pointer else { return } - - let bytes = UnsafeRawPointer(pointer).assumingMemoryBound(to: UInt8.self) - var offset = 0 - while offset + 4 <= totalLength { - let nalLength = Int(bytes[offset]) << 24 | - Int(bytes[offset + 1]) << 16 | - Int(bytes[offset + 2]) << 8 | - Int(bytes[offset + 3]) - offset += 4 - guard nalLength > 0, offset + nalLength <= totalLength else { break } - units.append(.init(bytes: Data(bytes: bytes.advanced(by: offset), count: nalLength), isParameterSet: false)) - offset += nalLength - } - - if !units.isEmpty { - onNALUnits?(units, CMSampleBufferGetPresentationTimeStamp(sampleBuffer)) - } - } -} - -// MARK: - RTP packetizer - -final class H264RTPPacketizer { - private(set) var sequence: UInt16 = UInt16.random(in: 0...UInt16.max) - private(set) var timestamp: UInt32 = UInt32.random(in: 0...UInt32.max) - private let ssrc = UInt32.random(in: 1...UInt32.max) - private let payloadType: UInt8 = 96 - private let maxPayload: Int - private let timestampStep: UInt32 - - init(fps: Int, maxPayload: Int = 1_180) { - self.maxPayload = max(300, maxPayload) - self.timestampStep = UInt32(90_000 / max(1, fps)) - } - - func packetize(_ units: [H264NALUnit]) -> [Data] { - var packets: [Data] = [] - for (unitIndex, unit) in units.enumerated() { - let isLastUnit = unitIndex == units.count - 1 - let bytes = unit.bytes - guard let first = bytes.first else { continue } - - if bytes.count <= maxPayload { - packets.append(makePacket(payload: bytes, marker: isLastUnit)) - continue - } - - let fuIndicator = (first & 0x80) | (first & 0x60) | 28 - let nalType = first & 0x1F - let body = Data(bytes.dropFirst()) - let fragmentSize = maxPayload - 2 - var offset = 0 - while offset < body.count { - let end = min(body.count, offset + fragmentSize) - 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) - packet.append((marker ? 0x80 : 0) | payloadType) - appendBE(sequence, to: &packet) - appendBE(timestamp, to: &packet) - appendBE(ssrc, to: &packet) - packet.append(payload) - sequence &+= 1 - return packet - } - - private func appendBE(_ value: T, to data: inout Data) { - var bigEndian = value.bigEndian - withUnsafeBytes(of: &bigEndian) { data.append(contentsOf: $0) } - } -} - -// MARK: - End-to-end streamer - -@MainActor -final class ProjectionStreamer: ObservableObject { - enum State: Equatable { case stopped, starting, streaming, 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 - 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 byteCount = units.reduce(0) { $0 + $1.bytes.count } - Task { @MainActor in - self.encodedBytes += byteCount - 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 frameDuration = 1.0 / Double(max(1, profile.fps)) - renderTask = Task { [weak self, weak coordinator] in - guard let coordinator else { return } - var frame: Int64 = 0 - while !Task.isCancelled { - guard let self else { return } - do { - let buffer = try self.renderer.render(stateProvider()) - try encoder.encode(buffer, pts: CMTime(value: frame, timescale: CMTimeScale(max(1, profile.fps)))) - self.renderedFrames += 1 - frame += 1 - } catch { - self.state = .failed(error.localizedDescription) - coordinator.log.append(error.localizedDescription, category: "encoder", level: .error) - return - } - try? await Task.sleep(for: .seconds(frameDuration)) - } - } - } - - 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 frame graphics context." - case .encoderNotReady: return "H.264 encoder is not ready." - case .videoToolbox(let status): return "VideoToolbox returned status \(status)." - } - } -} From fe0c82ef7d7c8195d7dc020c022f04792c4b581a Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:02:02 +0530 Subject: [PATCH 028/112] feat: implement dash-compatible VideoToolbox H264 RTP projection --- RideDash/ProjectionCore/ProjectionCore.swift | 560 +++++++++++++++++++ 1 file changed, 560 insertions(+) create mode 100644 RideDash/ProjectionCore/ProjectionCore.swift 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)." + } + } +} From f600a6d87f63861ac87ad574d501764f263f7ab0 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:02:04 +0530 Subject: [PATCH 029/112] docs: track implementation status for manual testing --- Docs/IMPLEMENTATION_STATUS.md | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Docs/IMPLEMENTATION_STATUS.md diff --git a/Docs/IMPLEMENTATION_STATUS.md b/Docs/IMPLEMENTATION_STATUS.md new file mode 100644 index 0000000..e15f7de --- /dev/null +++ b/Docs/IMPLEMENTATION_STATUS.md @@ -0,0 +1,33 @@ +# RideDash Implementation Status + +This file tracks code completion independent of CI/CD. Final validation is manual on a physical iPhone and compatible motorcycle dash. + +## Implemented + +- [x] Project skeleton +- [x] Hotspot Configuration entitlement +- [x] In-app Wi-Fi join request +- [x] Local network path monitoring +- [x] UDP route scaffold +- [x] Diagnostic logging/export +- [x] Hardware test profile + +## In progress + +- [ ] Multi-port UDP transport and packet receive stream +- [ ] Protocol framing / K1G-TLV helpers +- [ ] Session state machine +- [ ] Authentication handshake +- [ ] Projection control plane +- [ ] H.264 encoder +- [ ] RTP packetization +- [ ] Projection streamer +- [ ] Dash renderer +- [ ] Navigation state engine +- [ ] Dash input decoder +- [ ] Recovery/reconnect +- [ ] Product UI + +## Validation policy + +No GitHub Actions or CI/CD workflow is used. The final integration test is performed manually on the user's owned Guerrilla 450 dash and iPhone. Firmware-specific constants remain configurable until that test is complete. From 7cccfb9808fa19856134c07097934d871ab62dfd Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:02:14 +0530 Subject: [PATCH 030/112] docs: add protocol reference notes --- Docs/PROTOCOL_NOTES.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Docs/PROTOCOL_NOTES.md diff --git a/Docs/PROTOCOL_NOTES.md b/Docs/PROTOCOL_NOTES.md new file mode 100644 index 0000000..5f15e20 --- /dev/null +++ b/Docs/PROTOCOL_NOTES.md @@ -0,0 +1,31 @@ +# Protocol Notes + +RideDash keeps hardware/protocol assumptions isolated from product UI. The constants below are starting points from public interoperability references and must be validated against the user's owned dash firmware. + +## Reference endpoints + +- Dash host hypothesis: `192.168.1.1` +- Control send port hypothesis: UDP `2000` +- Input/listen port hypothesis: UDP `2002` +- H.264/RTP video port hypothesis: UDP `5000` +- Broadcast hypothesis: `192.168.1.255` +- Initial renderer size hypothesis: `526×300` + +## Known public control messages + +The public better-dash reference describes: + +- RSA/AES session authentication before navigation projection. +- Navigation context and route-card messages. +- Projection-on / projection-off TLVs. +- Start-navigation command. +- Periodic projection, route, nav-info and status heartbeats. +- Button/input events received on the control listener. + +## Safety rule + +Unknown message families stay read-only until their meaning is understood. The app never sends commands to ECU, throttle, ABS, traction control, brakes, immobilizer, engine-management or other safety-critical services. + +## Compatibility strategy + +All endpoint/packet assumptions live in `DashProtocolConfiguration` and `DashProtocolConstants`. If manual testing shows firmware variation, add a capability profile rather than scattering conditional literals throughout UI/network code. From 4b116cc7924320532835aaaaa157b35e23fe5b21 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:02:33 +0530 Subject: [PATCH 031/112] feat: add centralized dash protocol configuration --- .../DashProtocolConfiguration.swift | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 RideDash/DashProtocol/DashProtocolConfiguration.swift diff --git a/RideDash/DashProtocol/DashProtocolConfiguration.swift b/RideDash/DashProtocol/DashProtocolConfiguration.swift new file mode 100644 index 0000000..60e8393 --- /dev/null +++ b/RideDash/DashProtocol/DashProtocolConfiguration.swift @@ -0,0 +1,17 @@ +import Foundation + +struct DashProtocolConfiguration: Codable, Hashable, Sendable { + var dashHost: 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 projectionFPS: Double = 4 + var videoBitrate: Int = 240_000 + var routeTitle: String = "RideDash" + var hostname: String = "iPhone" + + static let `default` = DashProtocolConfiguration() +} From a666b178ba1fe133d17931189c3a469cfa4b5ae0 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:02:41 +0530 Subject: [PATCH 032/112] feat: add reusable hex codec --- RideDash/DashProtocol/HexCodec.swift | 43 ++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 RideDash/DashProtocol/HexCodec.swift diff --git a/RideDash/DashProtocol/HexCodec.swift b/RideDash/DashProtocol/HexCodec.swift new file mode 100644 index 0000000..7e673f4 --- /dev/null +++ b/RideDash/DashProtocol/HexCodec.swift @@ -0,0 +1,43 @@ +import Foundation + +enum HexCodecError: LocalizedError { + case oddLength + case invalidByte(String) + + var errorDescription: String? { + switch self { + case .oddLength: return "Hex string must contain an even number of digits." + case .invalidByte(let value): return "Invalid hex byte: \(value)" + } + } +} + +enum HexCodec { + static func data(from string: String) throws -> Data { + let cleaned = string + .replacingOccurrences(of: " ", with: "") + .replacingOccurrences(of: "\n", with: "") + .replacingOccurrences(of: "\t", with: "") + guard cleaned.count.isMultiple(of: 2) else { throw HexCodecError.oddLength } + + var result = Data() + var index = cleaned.startIndex + while index < cleaned.endIndex { + let next = cleaned.index(index, offsetBy: 2) + let byteString = String(cleaned[index.. String { + let bytes = limit.map { data.prefix($0) } ?? data[...] + let value = bytes.map { String(format: "%02X", $0) }.joined(separator: " ") + if let limit, data.count > limit { return value + " …" } + return value + } +} From 80a4136f37b5cdfae1f3173d3b3cdbd5f758d82e Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:02:53 +0530 Subject: [PATCH 033/112] feat: model inbound and outbound dash datagrams --- RideDash/DashProtocol/DashDatagram.swift | 33 ++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 RideDash/DashProtocol/DashDatagram.swift diff --git a/RideDash/DashProtocol/DashDatagram.swift b/RideDash/DashProtocol/DashDatagram.swift new file mode 100644 index 0000000..602986b --- /dev/null +++ b/RideDash/DashProtocol/DashDatagram.swift @@ -0,0 +1,33 @@ +import Foundation + +enum DashDatagramDirection: String, Codable, Sendable { + case inbound + case outbound +} + +struct DashDatagram: Identifiable, Hashable, Sendable { + let id: UUID + let timestamp: Date + let direction: DashDatagramDirection + let host: String + let port: UInt16 + let payload: Data + + init( + id: UUID = UUID(), + timestamp: Date = .now, + direction: DashDatagramDirection, + host: String, + port: UInt16, + payload: Data + ) { + self.id = id + self.timestamp = timestamp + self.direction = direction + self.host = host + self.port = port + self.payload = payload + } + + var hexPreview: String { HexCodec.string(from: payload, limit: 48) } +} From 1dfd3f5fe976db624c23f5a9702abb3bf73b6a4f Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:02:57 +0530 Subject: [PATCH 034/112] chore: keep hardware test profile generic in app UI --- RideDash/Models/DashTestProfile.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/RideDash/Models/DashTestProfile.swift b/RideDash/Models/DashTestProfile.swift index cd85307..9e14488 100644 --- a/RideDash/Models/DashTestProfile.swift +++ b/RideDash/Models/DashTestProfile.swift @@ -11,7 +11,7 @@ struct DashTestProfile: Codable, Equatable { static var defaultProfile: DashTestProfile { DashTestProfile( - bikeModel: "Guerrilla 450", + bikeModel: "Test motorcycle", dashFirmware: "", dashSSID: "", dashHost: "192.168.1.1", From 6efe53e9a5e9efb0b71567958456f3fa127e7771 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:03:26 +0530 Subject: [PATCH 035/112] chore: make diagnostics generic and reflect complete transport stack --- .../Diagnostics/DiagnosticsView.swift | 43 +++++++++---------- 1 file changed, 20 insertions(+), 23 deletions(-) diff --git a/RideDash/Features/Diagnostics/DiagnosticsView.swift b/RideDash/Features/Diagnostics/DiagnosticsView.swift index 1d52f88..6cedcf7 100644 --- a/RideDash/Features/Diagnostics/DiagnosticsView.swift +++ b/RideDash/Features/Diagnostics/DiagnosticsView.swift @@ -6,7 +6,7 @@ struct DiagnosticsView: View { @StateObject private var transport = DashTransport() @StateObject private var log = DiagnosticLog() - @AppStorage("dash.test.bikeModel") private var bikeModel = "Guerrilla 450" + @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" @@ -36,6 +36,9 @@ struct DiagnosticsView: View { networkMonitor.start() log.append("Diagnostics screen opened", category: "app") } + .onDisappear { + transport.stop() + } .onChange(of: networkMonitor.statusText) { _, newValue in log.append("Path status: \(newValue); Wi-Fi=\(networkMonitor.usesWiFi)", category: "network") } @@ -46,8 +49,8 @@ struct DiagnosticsView: View { private var hardwareSection: some View { Section("Hardware test profile") { - TextField("Bike model", text: $bikeModel) - TextField("Dash firmware", text: $dashFirmware) + TextField("Motorcycle model", text: $bikeModel) + TextField("Display firmware", text: $dashFirmware) .textInputAutocapitalization(.never) LabeledContent("Phone", value: profile.iPhoneModel) LabeledContent("iOS", value: profile.iOSVersion) @@ -56,14 +59,14 @@ struct DiagnosticsView: View { private var wiFiSection: some View { Section { - TextField("Dash Wi-Fi SSID", text: $dashSSID) + 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 dash SSID", category: "wifi") + 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") @@ -86,7 +89,7 @@ struct DiagnosticsView: View { } header: { Text("Wi-Fi") } footer: { - Text("RideDash uses Apple's Hotspot Configuration API. iOS controls the user approval flow. The password is kept only in this screen state and is never written to the diagnostic log.") + Text("The password exists only in this screen state and is never written to diagnostic logs.") } } @@ -95,12 +98,10 @@ struct DiagnosticsView: View { 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) + Text("No interfaces reported yet").foregroundStyle(.secondary) } else { ForEach(networkMonitor.interfaceNames, id: \.self) { name in - Text(name) - .font(.caption) + Text(name).font(.caption) } } } @@ -108,7 +109,7 @@ struct DiagnosticsView: View { private var transportSection: some View { Section { - TextField("Dash host", text: $dashHost) + TextField("Display host", text: $dashHost) .textInputAutocapitalization(.never) .autocorrectionDisabled() TextField("UDP port", value: $dashPort, format: .number) @@ -128,26 +129,26 @@ struct DiagnosticsView: View { } 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("A UDP connection reaching Ready only proves iOS has a route/socket. It does not prove the motorcycle dash responded. Phase 2 will add receive loops and validated, non-destructive protocol probes.") + Text("This screen is intentionally transport-only. Use Settings → Connection & Projection for authentication, navigation-mode control and H.264/RTP projection.") } } private var logSection: some View { Section { if log.entries.isEmpty { - Text("No diagnostic events yet") - .foregroundStyle(.secondary) + 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) + Text(entry.message).font(.caption) } } } @@ -160,19 +161,15 @@ struct DiagnosticsView: View { Label("Export Diagnostic Log", systemImage: "square.and.arrow.up") } - Button("Clear Log", role: .destructive) { - log.clear() - } + Button("Clear Log", role: .destructive) { log.clear() } } header: { Text("Session log") } footer: { - Text("Export deliberately redacts most of the SSID and does not include the Wi-Fi password, cryptographic secrets, or route history.") + Text("Export redacts most of the SSID and excludes the Wi-Fi password, cryptographic session keys and route history.") } } } #Preview { - NavigationStack { - DiagnosticsView() - } + NavigationStack { DiagnosticsView() } } From 5a167ee629eda5f912099dc7aac844f67ce9330c Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:03:31 +0530 Subject: [PATCH 036/112] feat: add dash session and input state models --- RideDash/DashProtocol/DashSessionState.swift | 22 ++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 RideDash/DashProtocol/DashSessionState.swift diff --git a/RideDash/DashProtocol/DashSessionState.swift b/RideDash/DashProtocol/DashSessionState.swift new file mode 100644 index 0000000..754a423 --- /dev/null +++ b/RideDash/DashProtocol/DashSessionState.swift @@ -0,0 +1,22 @@ +import Foundation + +enum DashSessionState: String, Codable, CaseIterable, Sendable { + case disconnected + case joiningWiFi + case networkReady + case transportReady + case authenticating + case authenticated + case navigationReady + case projecting + case recovering + case failed +} + +enum DashInputAction: String, Codable, Sendable { + case right + case left + case down + case click + case unknown +} From 84be181a2fa8504f14b87b6f78a72b6eada87e8d Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:03:40 +0530 Subject: [PATCH 037/112] feat: centralize public protocol constants --- .../DashProtocol/DashProtocolConstants.swift | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 RideDash/DashProtocol/DashProtocolConstants.swift diff --git a/RideDash/DashProtocol/DashProtocolConstants.swift b/RideDash/DashProtocol/DashProtocolConstants.swift new file mode 100644 index 0000000..53197f6 --- /dev/null +++ b/RideDash/DashProtocol/DashProtocolConstants.swift @@ -0,0 +1,20 @@ +import Foundation + +enum DashProtocolConstants { + // Public interoperability reference values. Keep centralized for firmware tuning. + static let requestAuthenticationHex = "0016000200000000020100054B314720000804000101" + static let navigationContextHex = "0016000200000000020100054B31472000052E00011E" + static let emptyNavigationListsHex = "002A000600000000020100054B31472000052F0001000530000100053100010005320001000533000100" + static let startNavigationHex = "0016000200000000020100054B31472000068000010B" + static let projectionFrameHex = "0016000200000000020100054B314720000556000155" + static let projectionOnHex = "0016000200000000020100054B314720000605000155" + static let projectionStopHex = "0016000200000000020100054B3147200005560001AA" + static let projectionOffHex = "0016000200000000020100054B3147200006050001AA" + static let authenticationPayloadPrefixHex = "0095000200000000020100054B3147200008000080" + + static let buttonRight: UInt8 = 0x13 + static let buttonLeft: UInt8 = 0x14 + static let buttonDown: UInt8 = 0x15 + static let buttonClick: UInt8 = 0x18 + static let buttonAckPrefixHex = "0016000200000000020100054B3147200006800001" +} From 8a673527637188dcd9f298aa35953c96c92ecb0e Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:03:48 +0530 Subject: [PATCH 038/112] feat: decode dash navigation button events --- RideDash/DashProtocol/DashInputDecoder.swift | 43 ++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 RideDash/DashProtocol/DashInputDecoder.swift diff --git a/RideDash/DashProtocol/DashInputDecoder.swift b/RideDash/DashProtocol/DashInputDecoder.swift new file mode 100644 index 0000000..710ffa1 --- /dev/null +++ b/RideDash/DashProtocol/DashInputDecoder.swift @@ -0,0 +1,43 @@ +import Foundation + +struct DashInputEvent: Identifiable, Sendable { + let id = UUID() + let action: DashInputAction + let rawCode: UInt8 + let payload: Data +} + +enum DashInputDecoder { + /// Public references show button events containing `09 00 00 01 XX`. + /// We intentionally search for that marker instead of assuming a fixed outer wrapper. + static func decode(_ data: Data) -> DashInputEvent? { + let bytes = [UInt8](data) + guard bytes.count >= 5 else { return nil } + + for index in 0...(bytes.count - 5) { + guard bytes[index] == 0x09, + bytes[index + 1] == 0x00, + bytes[index + 2] == 0x00, + bytes[index + 3] == 0x01 else { continue } + + let code = bytes[index + 4] + let action: DashInputAction + switch code { + case DashProtocolConstants.buttonRight: action = .right + case DashProtocolConstants.buttonLeft: action = .left + case DashProtocolConstants.buttonDown: action = .down + case DashProtocolConstants.buttonClick: action = .click + default: action = .unknown + } + return DashInputEvent(action: action, rawCode: code, payload: data) + } + return nil + } + + static func acknowledgement(for event: DashInputEvent) throws -> Data? { + guard event.action != .unknown else { return nil } + return try HexCodec.data( + from: DashProtocolConstants.buttonAckPrefixHex + String(format: "%02X", event.rawCode) + ) + } +} From 5c9fac00e11caf08d271dfc8af533be24d96554d Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:03:59 +0530 Subject: [PATCH 039/112] feat: add defensive K1G packet codec --- RideDash/DashProtocol/K1GCodec.swift | 44 ++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 RideDash/DashProtocol/K1GCodec.swift diff --git a/RideDash/DashProtocol/K1GCodec.swift b/RideDash/DashProtocol/K1GCodec.swift new file mode 100644 index 0000000..d6216ac --- /dev/null +++ b/RideDash/DashProtocol/K1GCodec.swift @@ -0,0 +1,44 @@ +import Foundation + +/// Minimal, defensive framing helpers for the public K1G/TLV-shaped packets. +/// The protocol is intentionally represented as raw typed envelopes until hardware validation. +struct K1GPacket: Hashable, Sendable { + let raw: Data + + var declaredLength: Int? { + guard raw.count >= 2 else { return nil } + return Int(raw[0]) << 8 | Int(raw[1]) + } + + var payload: Data { + guard raw.count > 2 else { return Data() } + return raw.dropFirst(2) + } + + var isLengthPlausible: Bool { + guard let declaredLength else { return false } + // Public captures use an outer two-byte length. Some firmware wrappers may + // count slightly differently, so keep decoding tolerant but never unsafe. + return declaredLength <= raw.count + 4 && declaredLength >= 0 + } +} + +enum K1GCodec { + static func decode(_ data: Data) -> K1GPacket? { + guard data.count >= 2 else { return nil } + return K1GPacket(raw: data) + } + + static func knownControlPacket(hex: String) throws -> K1GPacket { + K1GPacket(raw: try HexCodec.data(from: hex)) + } + + static func contains(_ bytes: [UInt8], in data: Data) -> Bool { + guard !bytes.isEmpty, data.count >= bytes.count else { return false } + let raw = [UInt8](data) + for i in 0...(raw.count - bytes.count) { + if Array(raw[i..<(i + bytes.count)]) == bytes { return true } + } + return false + } +} From 8c097b5505c433759c169df54e114a2e11ae878a Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:04:07 +0530 Subject: [PATCH 040/112] feat: add typed projection control packet accessors --- .../ProjectionControlPackets.swift | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 RideDash/DashProtocol/ProjectionControlPackets.swift diff --git a/RideDash/DashProtocol/ProjectionControlPackets.swift b/RideDash/DashProtocol/ProjectionControlPackets.swift new file mode 100644 index 0000000..6fdac28 --- /dev/null +++ b/RideDash/DashProtocol/ProjectionControlPackets.swift @@ -0,0 +1,35 @@ +import Foundation + +enum ProjectionControlPackets { + static func authenticationRequest() throws -> Data { + try HexCodec.data(from: DashProtocolConstants.requestAuthenticationHex) + } + + static func navigationContext() throws -> Data { + try HexCodec.data(from: DashProtocolConstants.navigationContextHex) + } + + static func emptyNavigationLists() throws -> Data { + try HexCodec.data(from: DashProtocolConstants.emptyNavigationListsHex) + } + + static func startNavigation() throws -> Data { + try HexCodec.data(from: DashProtocolConstants.startNavigationHex) + } + + static func projectionFrame() throws -> Data { + try HexCodec.data(from: DashProtocolConstants.projectionFrameHex) + } + + static func projectionOn() throws -> Data { + try HexCodec.data(from: DashProtocolConstants.projectionOnHex) + } + + static func projectionStop() throws -> Data { + try HexCodec.data(from: DashProtocolConstants.projectionStopHex) + } + + static func projectionOff() throws -> Data { + try HexCodec.data(from: DashProtocolConstants.projectionOffHex) + } +} From fb4f97e2220cdb221f780d7f084e6772b3d8b323 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:04:13 +0530 Subject: [PATCH 041/112] feat: add session metrics model --- RideDash/DashProtocol/DashSessionMetrics.swift | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 RideDash/DashProtocol/DashSessionMetrics.swift diff --git a/RideDash/DashProtocol/DashSessionMetrics.swift b/RideDash/DashProtocol/DashSessionMetrics.swift new file mode 100644 index 0000000..d0ba693 --- /dev/null +++ b/RideDash/DashProtocol/DashSessionMetrics.swift @@ -0,0 +1,17 @@ +import Foundation + +struct DashSessionMetrics: Sendable { + var connectedAt: Date? + var authenticatedAt: Date? + var projectionStartedAt: Date? + var inboundPackets: Int = 0 + var outboundPackets: Int = 0 + var videoPackets: Int = 0 + var encodedFrames: Int = 0 + var reconnectAttempts: Int = 0 + + var projectionDuration: TimeInterval { + guard let projectionStartedAt else { return 0 } + return Date().timeIntervalSince(projectionStartedAt) + } +} From 3686bbbd8fca6adeab8cd37b7cdc7581c0770701 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:04:16 +0530 Subject: [PATCH 042/112] fix: keep Network.framework callbacks actor-safe --- RideDash/DashConnectivity/DashTransport.swift | 28 ++++++++++--------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/RideDash/DashConnectivity/DashTransport.swift b/RideDash/DashConnectivity/DashTransport.swift index 61b6e28..9a1dea9 100644 --- a/RideDash/DashConnectivity/DashTransport.swift +++ b/RideDash/DashConnectivity/DashTransport.swift @@ -99,7 +99,7 @@ final class DashTransport: ObservableObject { Task { @MainActor in self?.handleListenerState(newState) } } listener.newConnectionHandler = { [weak self] connection in - self?.acceptInput(connection) + Task { @MainActor in self?.acceptInput(connection) } } listener.start(queue: queue) } @@ -212,14 +212,16 @@ final class DashTransport: ObservableObject { let id = ObjectIdentifier(connection) inputConnections[id] = connection connection.stateUpdateHandler = { [weak self, weak connection] state 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 + 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) @@ -227,9 +229,9 @@ final class DashTransport: ObservableObject { private func receiveNext(on connection: NWConnection) { connection.receiveMessage { [weak self, weak connection] data, _, _, error in - guard let self, let connection else { return } - if let data, !data.isEmpty { - Task { @MainActor in + Task { @MainActor in + guard let self, let connection else { return } + if let data, !data.isEmpty { self.receivedPackets += 1 self.emit(.init( timestamp: .now, @@ -239,8 +241,8 @@ final class DashTransport: ObservableObject { data: data )) } + if error == nil { self.receiveNext(on: connection) } } - if error == nil { self.receiveNext(on: connection) } } } From b61c444a2fe1a5b7c5792291099fc6658fc49824 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:04:20 +0530 Subject: [PATCH 043/112] feat: add firmware compatibility profile --- .../DashCompatibilityProfile.swift | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 RideDash/DashProtocol/DashCompatibilityProfile.swift diff --git a/RideDash/DashProtocol/DashCompatibilityProfile.swift b/RideDash/DashProtocol/DashCompatibilityProfile.swift new file mode 100644 index 0000000..35b341a --- /dev/null +++ b/RideDash/DashProtocol/DashCompatibilityProfile.swift @@ -0,0 +1,19 @@ +import Foundation + +struct DashCompatibilityProfile: Codable, Hashable, Identifiable, Sendable { + var id: String { "\(model)-\(firmware)" } + var model: String + var firmware: String + var configuration: DashProtocolConfiguration + var requiresButtonAck: Bool = true + var projectionHeartbeatHz: Double = 4 + var routeHeartbeatHz: Double = 1 + var navigationHeartbeatHz: Double = 1 + var statusHeartbeatHz: Double = 1 + + static let researchDefault = DashCompatibilityProfile( + model: "Generic compatible dash", + firmware: "unverified", + configuration: .default + ) +} From e73d40087c85faa3c6c27c4d074aa285460826a4 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:04:28 +0530 Subject: [PATCH 044/112] feat: add protocol error model --- RideDash/DashProtocol/DashProtocolError.swift | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 RideDash/DashProtocol/DashProtocolError.swift diff --git a/RideDash/DashProtocol/DashProtocolError.swift b/RideDash/DashProtocol/DashProtocolError.swift new file mode 100644 index 0000000..3248f14 --- /dev/null +++ b/RideDash/DashProtocol/DashProtocolError.swift @@ -0,0 +1,23 @@ +import Foundation + +enum DashProtocolError: LocalizedError { + case transportNotReady + case authenticationTimeout + case missingPublicKey + case invalidPublicKey + case authenticationRejected + case invalidPacket(String) + case projectionNotReady + + var errorDescription: String? { + switch self { + case .transportNotReady: return "Dash transport is not ready." + case .authenticationTimeout: return "Dash authentication timed out." + case .missingPublicKey: return "Dash did not provide the required public-key material." + case .invalidPublicKey: return "Dash public-key material could not be imported." + case .authenticationRejected: return "Dash rejected the session authentication." + case .invalidPacket(let reason): return "Invalid dash packet: \(reason)" + case .projectionNotReady: return "Dash session is not ready for projection." + } + } +} From 9292e1851cc82232109da62b244d156c60c6fcc6 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:04:34 +0530 Subject: [PATCH 045/112] feat: add packet trace model --- RideDash/DashProtocol/DashPacketTrace.swift | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 RideDash/DashProtocol/DashPacketTrace.swift diff --git a/RideDash/DashProtocol/DashPacketTrace.swift b/RideDash/DashProtocol/DashPacketTrace.swift new file mode 100644 index 0000000..390ac42 --- /dev/null +++ b/RideDash/DashProtocol/DashPacketTrace.swift @@ -0,0 +1,21 @@ +import Foundation + +struct DashPacketTrace: Identifiable, Sendable { + let id: UUID + let timestamp: Date + let direction: DashDatagramDirection + let host: String + let port: UInt16 + let byteCount: Int + let hexPreview: String + + init(datagram: DashDatagram) { + id = datagram.id + timestamp = datagram.timestamp + direction = datagram.direction + host = datagram.host + port = datagram.port + byteCount = datagram.payload.count + hexPreview = datagram.hexPreview + } +} From 97e2f11f629a118d6eccb91cd9e9ef520792eba1 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:04:40 +0530 Subject: [PATCH 046/112] feat: add session timeline entry model --- RideDash/DashProtocol/DashSessionTimeline.swift | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 RideDash/DashProtocol/DashSessionTimeline.swift diff --git a/RideDash/DashProtocol/DashSessionTimeline.swift b/RideDash/DashProtocol/DashSessionTimeline.swift new file mode 100644 index 0000000..247f45d --- /dev/null +++ b/RideDash/DashProtocol/DashSessionTimeline.swift @@ -0,0 +1,8 @@ +import Foundation + +struct DashSessionTimelineEntry: Identifiable, Sendable { + let id = UUID() + let timestamp = Date() + let state: DashSessionState + let message: String +} From 05029adb471e789fe027620fbcbaa75c07c00fa2 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:04:44 +0530 Subject: [PATCH 047/112] feat: add Maps route share extension --- RideDashShare/ShareViewController.swift | 71 +++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 RideDashShare/ShareViewController.swift 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) + } +} From 5cb0eb91e8172be7e5d2d9a66d0ba0694c5ee0b5 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:04:49 +0530 Subject: [PATCH 048/112] feat: add safe byte cursor for protocol decoding --- RideDash/DashProtocol/ByteCursor.swift | 28 ++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 RideDash/DashProtocol/ByteCursor.swift diff --git a/RideDash/DashProtocol/ByteCursor.swift b/RideDash/DashProtocol/ByteCursor.swift new file mode 100644 index 0000000..9496b14 --- /dev/null +++ b/RideDash/DashProtocol/ByteCursor.swift @@ -0,0 +1,28 @@ +import Foundation + +struct ByteCursor { + private let bytes: [UInt8] + private(set) var offset: Int = 0 + + init(_ data: Data) { bytes = Array(data) } + + var remaining: Int { bytes.count - offset } + + mutating func readUInt8() -> UInt8? { + guard remaining >= 1 else { return nil } + defer { offset += 1 } + return bytes[offset] + } + + mutating func readUInt16BE() -> UInt16? { + guard remaining >= 2 else { return nil } + defer { offset += 2 } + return UInt16(bytes[offset]) << 8 | UInt16(bytes[offset + 1]) + } + + mutating func readData(count: Int) -> Data? { + guard count >= 0, remaining >= count else { return nil } + defer { offset += count } + return Data(bytes[offset..<(offset + count)]) + } +} From 43054f8805aa1e65d3a89339cb2e9474a18e739f Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:04:56 +0530 Subject: [PATCH 049/112] chore: configure RideDash share extension activation --- RideDashShare/Info.plist | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 RideDashShare/Info.plist 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 + + + From 1a2f49934e1fb388bca77e4417683dfc1caa1d20 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:04:57 +0530 Subject: [PATCH 050/112] feat: add generic TLV codec --- RideDash/DashProtocol/TLV.swift | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 RideDash/DashProtocol/TLV.swift diff --git a/RideDash/DashProtocol/TLV.swift b/RideDash/DashProtocol/TLV.swift new file mode 100644 index 0000000..f4c5bee --- /dev/null +++ b/RideDash/DashProtocol/TLV.swift @@ -0,0 +1,33 @@ +import Foundation + +struct TLV: Hashable, Sendable { + let type: UInt16 + let value: Data +} + +enum TLVCodec { + /// Generic two-byte type + two-byte big-endian length helper for local fixtures. + /// Hardware-specific outer framing remains in K1GCodec. + static func encode(_ tlv: TLV) -> Data { + var result = Data() + result.append(UInt8((tlv.type >> 8) & 0xff)) + result.append(UInt8(tlv.type & 0xff)) + let length = UInt16(clamping: tlv.value.count) + result.append(UInt8((length >> 8) & 0xff)) + result.append(UInt8(length & 0xff)) + result.append(tlv.value) + return result + } + + static func decodeMany(_ data: Data) -> [TLV] { + var cursor = ByteCursor(data) + var result: [TLV] = [] + while cursor.remaining >= 4 { + guard let type = cursor.readUInt16BE(), + let length = cursor.readUInt16BE(), + let value = cursor.readData(count: Int(length)) else { break } + result.append(TLV(type: type, value: value)) + } + return result + } +} From 72344fdc5daa0b3b52c9dc49d1518a4b9e233743 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:05:05 +0530 Subject: [PATCH 051/112] feat: add dash capability flags --- RideDash/DashProtocol/DashProtocolCapabilities.swift | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 RideDash/DashProtocol/DashProtocolCapabilities.swift diff --git a/RideDash/DashProtocol/DashProtocolCapabilities.swift b/RideDash/DashProtocol/DashProtocolCapabilities.swift new file mode 100644 index 0000000..4fda450 --- /dev/null +++ b/RideDash/DashProtocol/DashProtocolCapabilities.swift @@ -0,0 +1,12 @@ +import Foundation + +struct DashProtocolCapabilities: Codable, Hashable, Sendable { + var supportsAuthentication = true + var supportsProjection = true + var supportsButtonInput = true + var supportsNavigationInfo = true + var supportsRouteCard = true + var supportsProjectionHeartbeat = true + + static let `default` = DashProtocolCapabilities() +} From 10bf3cae3062ff6c119ddf29075283197ef1e936 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:05:12 +0530 Subject: [PATCH 052/112] feat: add protocol version metadata --- RideDash/DashProtocol/DashProtocolVersion.swift | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 RideDash/DashProtocol/DashProtocolVersion.swift diff --git a/RideDash/DashProtocol/DashProtocolVersion.swift b/RideDash/DashProtocol/DashProtocolVersion.swift new file mode 100644 index 0000000..a44e0ee --- /dev/null +++ b/RideDash/DashProtocol/DashProtocolVersion.swift @@ -0,0 +1,8 @@ +import Foundation + +struct DashProtocolVersion: Codable, Hashable, Sendable { + var firmware: String + var notes: String + + static let unknown = DashProtocolVersion(firmware: "unknown", notes: "Hardware validation pending") +} From af430274031bbfac05d8a0089915fd85f6fadfa9 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:05:20 +0530 Subject: [PATCH 053/112] feat: define session commands --- RideDash/DashProtocol/DashSessionCommand.swift | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 RideDash/DashProtocol/DashSessionCommand.swift diff --git a/RideDash/DashProtocol/DashSessionCommand.swift b/RideDash/DashProtocol/DashSessionCommand.swift new file mode 100644 index 0000000..76bb524 --- /dev/null +++ b/RideDash/DashProtocol/DashSessionCommand.swift @@ -0,0 +1,9 @@ +import Foundation + +enum DashSessionCommand: Sendable { + case requestAuthentication + case enterNavigation + case startProjection + case stopProjection + case acknowledgeInput(DashInputEvent) +} From e717be8364f552052296a857964129abbbf40829 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:05:25 +0530 Subject: [PATCH 054/112] feat: add session snapshot model --- RideDash/DashProtocol/DashSessionSnapshot.swift | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 RideDash/DashProtocol/DashSessionSnapshot.swift diff --git a/RideDash/DashProtocol/DashSessionSnapshot.swift b/RideDash/DashProtocol/DashSessionSnapshot.swift new file mode 100644 index 0000000..5075778 --- /dev/null +++ b/RideDash/DashProtocol/DashSessionSnapshot.swift @@ -0,0 +1,8 @@ +import Foundation + +struct DashSessionSnapshot: Sendable { + var state: DashSessionState + var lastError: String? + var metrics: DashSessionMetrics + var compatibility: DashCompatibilityProfile +} From 53e61e3bb13ca6c27688377f1c24f6ff0e3b8828 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:05:36 +0530 Subject: [PATCH 055/112] feat: add session timing policy --- RideDash/DashProtocol/DashSessionPolicy.swift | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 RideDash/DashProtocol/DashSessionPolicy.swift diff --git a/RideDash/DashProtocol/DashSessionPolicy.swift b/RideDash/DashProtocol/DashSessionPolicy.swift new file mode 100644 index 0000000..6eb8d3a --- /dev/null +++ b/RideDash/DashProtocol/DashSessionPolicy.swift @@ -0,0 +1,10 @@ +import Foundation + +struct DashSessionPolicy: Sendable { + var authenticationTimeout: TimeInterval = 8 + var reconnectDelay: TimeInterval = 2 + var maximumReconnectAttempts: Int = 5 + var projectionHeartbeatHz: Double = 4 + var routeHeartbeatHz: Double = 1 + var navInfoHeartbeatHz: Double = 1 +} From 6ad9010908361a2bf7ecd71efb783b8015c1c02e Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:05:43 +0530 Subject: [PATCH 056/112] feat: add session events --- RideDash/DashProtocol/DashSessionEvent.swift | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 RideDash/DashProtocol/DashSessionEvent.swift diff --git a/RideDash/DashProtocol/DashSessionEvent.swift b/RideDash/DashProtocol/DashSessionEvent.swift new file mode 100644 index 0000000..697923f --- /dev/null +++ b/RideDash/DashProtocol/DashSessionEvent.swift @@ -0,0 +1,15 @@ +import Foundation + +enum DashSessionEvent: Sendable { + case wifiJoinRequested + case networkSatisfied + case transportReady + case authenticationStarted + case authenticationSucceeded + case authenticationFailed(String) + case navigationReady + case projectionStarted + case projectionStopped + case input(DashInputAction) + case transportLost(String) +} From 4f47430646e20aa15068c5496e862840031b7f5b Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:05:50 +0530 Subject: [PATCH 057/112] feat: add deterministic session reducer --- .../DashProtocol/DashSessionReducer.swift | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 RideDash/DashProtocol/DashSessionReducer.swift diff --git a/RideDash/DashProtocol/DashSessionReducer.swift b/RideDash/DashProtocol/DashSessionReducer.swift new file mode 100644 index 0000000..ee6476b --- /dev/null +++ b/RideDash/DashProtocol/DashSessionReducer.swift @@ -0,0 +1,19 @@ +import Foundation + +enum DashSessionReducer { + static func reduce(state: DashSessionState, event: DashSessionEvent) -> DashSessionState { + switch event { + case .wifiJoinRequested: return .joiningWiFi + case .networkSatisfied: return .networkReady + case .transportReady: return .transportReady + case .authenticationStarted: return .authenticating + case .authenticationSucceeded: return .authenticated + case .authenticationFailed: return .failed + case .navigationReady: return .navigationReady + case .projectionStarted: return .projecting + case .projectionStopped: return .navigationReady + case .input: return state + case .transportLost: return .recovering + } + } +} From 775bf62b09c6292a545d597406ef8b07a45609ed Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:06:10 +0530 Subject: [PATCH 058/112] feat: add full UDP datagram transport --- .../DashDatagramTransport.swift | 149 ++++++++++++++++++ 1 file changed, 149 insertions(+) create mode 100644 RideDash/DashConnectivity/DashDatagramTransport.swift diff --git a/RideDash/DashConnectivity/DashDatagramTransport.swift b/RideDash/DashConnectivity/DashDatagramTransport.swift new file mode 100644 index 0000000..db03db3 --- /dev/null +++ b/RideDash/DashConnectivity/DashDatagramTransport.swift @@ -0,0 +1,149 @@ +import Foundation +import Network + +final class DashDatagramTransport: @unchecked Sendable { + let incomingPackets: AsyncStream + + private let queue = DispatchQueue(label: "dev.dagerott.RideDash.datagrams") + private var continuation: AsyncStream.Continuation? + private var listener: NWListener? + private var connections: [String: NWConnection] = [:] + private var configuration: DashProtocolConfiguration = .default + + init() { + var captured: AsyncStream.Continuation? + incomingPackets = AsyncStream { captured = $0 } + continuation = captured + } + + deinit { + stop() + continuation?.finish() + } + + func start(configuration: DashProtocolConfiguration) throws { + stop() + self.configuration = configuration + + guard let inputPort = NWEndpoint.Port(rawValue: configuration.inputPort) else { + throw DashTransportError.invalidPort + } + + let listener = try NWListener(using: .udp, on: inputPort) + listener.newConnectionHandler = { [weak self] connection in + guard let self else { return } + connection.start(queue: self.queue) + self.receiveNext(on: connection) + } + listener.start(queue: queue) + self.listener = listener + + // Pre-create the control channel. UDP send is still lazy and can queue while preparing. + _ = channel( + host: configuration.broadcastHost, + port: configuration.controlPort, + localPort: configuration.controlPort + ) + } + + func stop() { + listener?.cancel() + listener = nil + for connection in connections.values { connection.cancel() } + connections.removeAll() + } + + func sendControl(_ data: Data) async throws { + try await send( + data, + host: configuration.broadcastHost, + port: configuration.controlPort, + localPort: configuration.controlPort + ) + } + + func sendVideo(_ data: Data) async throws { + try await send( + data, + host: configuration.dashHost, + port: configuration.videoPort, + localPort: nil + ) + } + + func send( + _ data: Data, + host: String, + port: UInt16, + localPort: UInt16? = nil + ) async throws { + guard let remotePort = NWEndpoint.Port(rawValue: port) else { + throw DashTransportError.invalidPort + } + let connection = channel(host: host, port: port, localPort: localPort) + + try await withCheckedThrowingContinuation { (checked: CheckedContinuation) in + connection.send(content: data, completion: .contentProcessed { [weak self] error in + if let error { + checked.resume(throwing: error) + return + } + self?.continuation?.yield( + DashDatagram( + direction: .outbound, + host: host, + port: remotePort.rawValue, + payload: data + ) + ) + checked.resume() + }) + } + } + + private func channel(host: String, port: UInt16, localPort: UInt16?) -> NWConnection { + let key = "\(host):\(port):\(localPort ?? 0)" + if let existing = connections[key] { return existing } + + let parameters = NWParameters.udp + parameters.allowLocalEndpointReuse = true + if let localPort, let sourcePort = NWEndpoint.Port(rawValue: localPort) { + parameters.requiredLocalEndpoint = .hostPort( + host: NWEndpoint.Host("0.0.0.0"), + port: sourcePort + ) + } + + let connection = NWConnection( + host: NWEndpoint.Host(host), + port: NWEndpoint.Port(rawValue: port)!, + using: parameters + ) + connection.start(queue: queue) + connections[key] = connection + return connection + } + + private func receiveNext(on connection: NWConnection) { + connection.receiveMessage { [weak self] data, _, _, error in + guard let self else { return } + if let data, !data.isEmpty { + var host = "unknown" + var port: UInt16 = 0 + if case let .hostPort(remoteHost, remotePort) = connection.endpoint { + host = String(describing: remoteHost) + port = remotePort.rawValue + } + self.continuation?.yield( + DashDatagram( + direction: .inbound, + host: host, + port: port, + payload: data + ) + ) + } + if error == nil { self.receiveNext(on: connection) } + } + } +} From 9b262e1276225736ab4cb97288cb479c50ee9e07 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:06:14 +0530 Subject: [PATCH 059/112] feat: embed RideDash route share extension target --- RideDash.xcodeproj/project.pbxproj | 144 +++++++++++++++++++++++++++++ 1 file changed, 144 insertions(+) diff --git a/RideDash.xcodeproj/project.pbxproj b/RideDash.xcodeproj/project.pbxproj index 099a5ef..e1d5719 100644 --- a/RideDash.xcodeproj/project.pbxproj +++ b/RideDash.xcodeproj/project.pbxproj @@ -20,10 +20,37 @@ 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, ); }; }; /* 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 = ""; }; @@ -39,6 +66,8 @@ 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 = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -49,6 +78,13 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + 000000000000000000000312 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ @@ -56,6 +92,7 @@ isa = PBXGroup; children = ( 000000000000000000000011 /* RideDash */, + 000000000000000000000023 /* RideDashShare */, 000000000000000000000017 /* Products */, ); sourceTree = ""; @@ -162,10 +199,20 @@ 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 = ""; @@ -180,16 +227,35 @@ 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 */ @@ -203,6 +269,9 @@ 000000000000000000000002 = { CreatedOnToolsVersion = 16.0; }; + 000000000000000000000005 = { + CreatedOnToolsVersion = 16.0; + }; }; }; buildConfigurationList = 000000000000000000000401 /* Build configuration list for PBXProject "RideDash" */; @@ -219,6 +288,7 @@ projectRoot = ""; targets = ( 000000000000000000000002 /* RideDash */, + 000000000000000000000005 /* RideDashShare */, ); }; /* End PBXProject section */ @@ -231,6 +301,13 @@ ); runOnlyForDeploymentPostprocessing = 0; }; + 000000000000000000000313 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXResourcesBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ @@ -254,8 +331,24 @@ ); 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; @@ -339,6 +432,48 @@ }; 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 */ @@ -360,6 +495,15 @@ 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 */; From d087e9957771ca3feeb89f858f8a614406c44ccd Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:06:16 +0530 Subject: [PATCH 060/112] feat: model dash public key material --- RideDash/DashProtocol/DashPublicKeyMaterial.swift | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 RideDash/DashProtocol/DashPublicKeyMaterial.swift diff --git a/RideDash/DashProtocol/DashPublicKeyMaterial.swift b/RideDash/DashProtocol/DashPublicKeyMaterial.swift new file mode 100644 index 0000000..2bddd35 --- /dev/null +++ b/RideDash/DashProtocol/DashPublicKeyMaterial.swift @@ -0,0 +1,8 @@ +import Foundation + +struct DashPublicKeyMaterial: Sendable { + var modulus: Data? + var exponent: Data? + + var isComplete: Bool { modulus != nil && exponent != nil } +} From 81634833e4439854470e31796a6aaacdee091b51 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:06:29 +0530 Subject: [PATCH 061/112] feat: parse public authentication response markers --- .../DashAuthenticationResponseParser.swift | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 RideDash/DashProtocol/DashAuthenticationResponseParser.swift diff --git a/RideDash/DashProtocol/DashAuthenticationResponseParser.swift b/RideDash/DashProtocol/DashAuthenticationResponseParser.swift new file mode 100644 index 0000000..8f2c4e6 --- /dev/null +++ b/RideDash/DashProtocol/DashAuthenticationResponseParser.swift @@ -0,0 +1,43 @@ +import Foundation + +enum DashAuthenticationResponseParser { + enum Event: Sendable { + case modulus(Data) + case exponent(Data) + case authenticated + case rejected + } + + /// Parses the public response markers documented by the interoperability reference. + /// The outer packet wrapper is intentionally tolerated; the marker is searched inside. + static func parse(_ data: Data) -> Event? { + let bytes = [UInt8](data) + guard bytes.count >= 3 else { return nil } + + // 07 01 01 => auth OK in the public reference. + if contains([0x07, 0x01, 0x01], in: bytes) { return .authenticated } + if contains([0x07, 0x01, 0x00], in: bytes) { return .rejected } + + // 07 00 and 07 03 . Capture bytes after the marker; + // hardware testing may refine wrapper-length stripping per firmware. + if let index = index(of: [0x07, 0x00], in: bytes), index + 2 < bytes.count { + return .modulus(Data(bytes[(index + 2)...])) + } + if let index = index(of: [0x07, 0x03], in: bytes), index + 2 < bytes.count { + return .exponent(Data(bytes[(index + 2)...])) + } + return nil + } + + private static func contains(_ needle: [UInt8], in haystack: [UInt8]) -> Bool { + index(of: needle, in: haystack) != nil + } + + private static func index(of 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 Array(haystack[i..<(i + needle.count)]) == needle { return i } + } + return nil + } +} From c0a63bc0f5c1db4ff94221805767155a8dd9245e Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:06:35 +0530 Subject: [PATCH 062/112] feat: generate ephemeral session key material --- RideDash/DashProtocol/RandomSessionKey.swift | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 RideDash/DashProtocol/RandomSessionKey.swift diff --git a/RideDash/DashProtocol/RandomSessionKey.swift b/RideDash/DashProtocol/RandomSessionKey.swift new file mode 100644 index 0000000..175f824 --- /dev/null +++ b/RideDash/DashProtocol/RandomSessionKey.swift @@ -0,0 +1,13 @@ +import Foundation +import Security + +enum RandomSessionKey { + static func generate(length: Int = 16) throws -> Data { + var bytes = [UInt8](repeating: 0, count: length) + let status = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) + guard status == errSecSuccess else { + throw NSError(domain: NSOSStatusErrorDomain, code: Int(status)) + } + return Data(bytes) + } +} From 2c5a10e5b7563f417ffffc6e0340bb38c65d3014 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:06:44 +0530 Subject: [PATCH 063/112] feat: add integer byte normalization helper --- RideDash/DashProtocol/DataIntegerEncoding.swift | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 RideDash/DashProtocol/DataIntegerEncoding.swift diff --git a/RideDash/DashProtocol/DataIntegerEncoding.swift b/RideDash/DashProtocol/DataIntegerEncoding.swift new file mode 100644 index 0000000..62dc3e6 --- /dev/null +++ b/RideDash/DashProtocol/DataIntegerEncoding.swift @@ -0,0 +1,8 @@ +import Foundation + +enum DataIntegerEncoding { + static func stripLeadingZeroes(_ data: Data) -> Data { + let bytes = data.drop { $0 == 0 } + return bytes.isEmpty ? Data([0]) : Data(bytes) + } +} From c9b845e381d507b976aff9b38f1495a1c96c07a1 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:07:01 +0530 Subject: [PATCH 064/112] feat: build DER RSA public keys from dash modulus exponent --- RideDash/DashProtocol/DERBuilder.swift | 27 ++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 RideDash/DashProtocol/DERBuilder.swift diff --git a/RideDash/DashProtocol/DERBuilder.swift b/RideDash/DashProtocol/DERBuilder.swift new file mode 100644 index 0000000..b35197d --- /dev/null +++ b/RideDash/DashProtocol/DERBuilder.swift @@ -0,0 +1,27 @@ +import Foundation + +enum DERBuilder { + static func rsaPublicKey(modulus: Data, exponent: Data) -> Data { + let body = integer(modulus) + integer(exponent) + return Data([0x30]) + length(body.count) + body + } + + private static func integer(_ value: Data) -> Data { + var normalized = DataIntegerEncoding.stripLeadingZeroes(value) + if let first = normalized.first, first & 0x80 != 0 { + normalized.insert(0, at: normalized.startIndex) + } + return Data([0x02]) + length(normalized.count) + normalized + } + + private static func length(_ value: Int) -> Data { + if value < 0x80 { return Data([UInt8(value)]) } + var bytes: [UInt8] = [] + var remaining = value + while remaining > 0 { + bytes.insert(UInt8(remaining & 0xff), at: 0) + remaining >>= 8 + } + return Data([0x80 | UInt8(bytes.count)]) + Data(bytes) + } +} From 1357955ad7936e57710433485f3a2330f87a1b9d Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:07:14 +0530 Subject: [PATCH 065/112] feat: add Security-framework RSA session encryption --- RideDash/DashProtocol/RSAEncryptor.swift | 43 ++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 RideDash/DashProtocol/RSAEncryptor.swift diff --git a/RideDash/DashProtocol/RSAEncryptor.swift b/RideDash/DashProtocol/RSAEncryptor.swift new file mode 100644 index 0000000..af21366 --- /dev/null +++ b/RideDash/DashProtocol/RSAEncryptor.swift @@ -0,0 +1,43 @@ +import Foundation +import Security + +enum RSAEncryptor { + static func encryptPKCS1( + plaintext: Data, + modulus: Data, + exponent: Data + ) throws -> Data { + let der = DERBuilder.rsaPublicKey(modulus: modulus, exponent: exponent) + let attributes: [CFString: Any] = [ + kSecAttrKeyType: kSecAttrKeyTypeRSA, + kSecAttrKeyClass: kSecAttrKeyClassPublic, + kSecAttrKeySizeInBits: modulus.count * 8 + ] + + var importError: Unmanaged? + guard let key = SecKeyCreateWithData( + der as CFData, + attributes as CFDictionary, + &importError + ) else { + throw importError?.takeRetainedValue() ?? DashProtocolError.invalidPublicKey as CFError + } + + let algorithm = SecKeyAlgorithm.rsaEncryptionPKCS1 + guard SecKeyIsAlgorithmSupported(key, .encrypt, algorithm) else { + throw DashProtocolError.invalidPublicKey + } + + var encryptionError: Unmanaged? + guard let encrypted = SecKeyCreateEncryptedData( + key, + algorithm, + plaintext as CFData, + &encryptionError + ) else { + if let error = encryptionError?.takeRetainedValue() { throw error } + throw DashProtocolError.invalidPublicKey + } + return encrypted as Data + } +} From a175101bdd43a99d4a3ba72038011c74615d5eba Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:07:24 +0530 Subject: [PATCH 066/112] feat: build encrypted dash authentication packet --- .../DashAuthenticationPacketBuilder.swift | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 RideDash/DashProtocol/DashAuthenticationPacketBuilder.swift diff --git a/RideDash/DashProtocol/DashAuthenticationPacketBuilder.swift b/RideDash/DashProtocol/DashAuthenticationPacketBuilder.swift new file mode 100644 index 0000000..913fb0f --- /dev/null +++ b/RideDash/DashProtocol/DashAuthenticationPacketBuilder.swift @@ -0,0 +1,31 @@ +import Foundation + +enum DashAuthenticationPacketBuilder { + static func makeEncryptedSessionPacket( + ssid: String, + sessionKey: Data, + modulus: Data, + exponent: Data + ) throws -> Data { + var plaintext = Data(ssid.utf8) + plaintext.append(sessionKey) + + let encrypted = try RSAEncryptor.encryptPKCS1( + plaintext: plaintext, + modulus: modulus, + exponent: exponent + ) + + // Public reference uses a 128-byte RSA ciphertext field for the known dash. + // Do not silently truncate if a different firmware/key size is encountered. + guard encrypted.count == 128 else { + throw DashProtocolError.invalidPacket( + "Expected 128-byte RSA ciphertext, got \(encrypted.count). Add a firmware capability profile before sending." + ) + } + + var packet = try HexCodec.data(from: DashProtocolConstants.authenticationPayloadPrefixHex) + packet.append(encrypted) + return packet + } +} From a31046fd9dd865313e71d6bae0d8e53aee892cae Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:07:33 +0530 Subject: [PATCH 067/112] docs: describe complete RideDash implementation and manual validation status --- README.md | 86 +++++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 77 insertions(+), 9 deletions(-) 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. From 251ab72751ae6614fccf61524524e089fcecad65 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:07:41 +0530 Subject: [PATCH 068/112] feat: implement async dash authentication flow --- RideDash/DashProtocol/DashAuthenticator.swift | 80 +++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 RideDash/DashProtocol/DashAuthenticator.swift diff --git a/RideDash/DashProtocol/DashAuthenticator.swift b/RideDash/DashProtocol/DashAuthenticator.swift new file mode 100644 index 0000000..5521d4f --- /dev/null +++ b/RideDash/DashProtocol/DashAuthenticator.swift @@ -0,0 +1,80 @@ +import Foundation + +struct AuthenticatedDashSession: Sendable { + let establishedAt: Date + let sessionKey: Data +} + +struct DashAuthenticator: Sendable { + let timeout: TimeInterval + + init(timeout: TimeInterval = 8) { + self.timeout = timeout + } + + func authenticate( + ssid: String, + transport: DashDatagramTransport + ) async throws -> AuthenticatedDashSession { + try await withThrowingTaskGroup(of: AuthenticatedDashSession.self) { group in + group.addTask { + try await authenticateFlow(ssid: ssid, transport: transport) + } + group.addTask { + try await Task.sleep(for: .seconds(timeout)) + throw DashProtocolError.authenticationTimeout + } + + guard let first = try await group.next() else { + throw DashProtocolError.authenticationTimeout + } + group.cancelAll() + return first + } + } + + private func authenticateFlow( + ssid: String, + transport: DashDatagramTransport + ) async throws -> AuthenticatedDashSession { + let sessionKey = try RandomSessionKey.generate() + try await transport.sendControl(ProjectionControlPackets.authenticationRequest()) + + var keyMaterial = DashPublicKeyMaterial() + var encryptedKeySent = false + + for await datagram in transport.incomingPackets { + guard datagram.direction == .inbound, + let event = DashAuthenticationResponseParser.parse(datagram.payload) else { + continue + } + + switch event { + case .modulus(let modulus): + keyMaterial.modulus = modulus + case .exponent(let exponent): + keyMaterial.exponent = exponent + case .authenticated: + return AuthenticatedDashSession(establishedAt: .now, sessionKey: sessionKey) + case .rejected: + throw DashProtocolError.authenticationRejected + } + + if keyMaterial.isComplete, + !encryptedKeySent, + let modulus = keyMaterial.modulus, + let exponent = keyMaterial.exponent { + let packet = try DashAuthenticationPacketBuilder.makeEncryptedSessionPacket( + ssid: ssid, + sessionKey: sessionKey, + modulus: modulus, + exponent: exponent + ) + try await transport.sendControl(packet) + encryptedKeySent = true + } + } + + throw DashProtocolError.authenticationTimeout + } +} From f291603c16eab76dd4b6a74ce722a3c8ddee49a3 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:07:52 +0530 Subject: [PATCH 069/112] feat: add route card model --- RideDash/DashProtocol/RouteCard.swift | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 RideDash/DashProtocol/RouteCard.swift diff --git a/RideDash/DashProtocol/RouteCard.swift b/RideDash/DashProtocol/RouteCard.swift new file mode 100644 index 0000000..1c29d69 --- /dev/null +++ b/RideDash/DashProtocol/RouteCard.swift @@ -0,0 +1,13 @@ +import Foundation + +struct RouteCard: Sendable { + var title: String + var remainingDistanceMeters: Int + var projectionOn: Bool + + init(title: String, remainingDistanceMeters: Int = 0, projectionOn: Bool = true) { + self.title = title + self.remainingDistanceMeters = remainingDistanceMeters + self.projectionOn = projectionOn + } +} From b9222b4e369460ea12e08c1af684cc54bd383e90 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:07:59 +0530 Subject: [PATCH 070/112] feat: add dash navigation instruction model --- .../DashProtocol/NavigationInstruction.swift | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 RideDash/DashProtocol/NavigationInstruction.swift diff --git a/RideDash/DashProtocol/NavigationInstruction.swift b/RideDash/DashProtocol/NavigationInstruction.swift new file mode 100644 index 0000000..c33a1aa --- /dev/null +++ b/RideDash/DashProtocol/NavigationInstruction.swift @@ -0,0 +1,19 @@ +import Foundation + +enum NavigationManeuver: UInt8, Codable, Sendable { + case continueStraight = 0 + case turnLeft = 1 + case turnRight = 2 + case slightLeft = 3 + case slightRight = 4 + case uTurn = 5 + case roundabout = 6 + case arrive = 7 +} + +struct DashNavigationInstruction: Sendable { + var maneuver: NavigationManeuver + var distanceToTurnMeters: Int + var remainingDistanceMeters: Int + var roadName: String +} From 913f5ba7de737e398dfc502f9ed93f80c13741d0 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:08:12 +0530 Subject: [PATCH 071/112] feat: add isolated route and navigation packet builders --- RideDash/DashProtocol/DashPacketBuilder.swift | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 RideDash/DashProtocol/DashPacketBuilder.swift diff --git a/RideDash/DashProtocol/DashPacketBuilder.swift b/RideDash/DashProtocol/DashPacketBuilder.swift new file mode 100644 index 0000000..dcb0d62 --- /dev/null +++ b/RideDash/DashProtocol/DashPacketBuilder.swift @@ -0,0 +1,41 @@ +import Foundation + +enum DashPacketBuilder { + /// Builds a conservative opaque route-card payload used by the session coordinator. + /// The public protocol's outer 0x007E route-card framing is firmware-sensitive; + /// manual hardware testing may refine this builder without touching navigation UI. + static func routeCard(_ card: RouteCard) -> Data { + var body = Data() + body.append(contentsOf: [0x00, 0x7E]) + let title = Data(card.title.utf8.prefix(48)) + body.append(UInt8(clamping: title.count)) + body.append(title) + let distance = UInt32(clamping: card.remainingDistanceMeters) + body.append(UInt8((distance >> 24) & 0xff)) + body.append(UInt8((distance >> 16) & 0xff)) + body.append(UInt8((distance >> 8) & 0xff)) + body.append(UInt8(distance & 0xff)) + body.append(card.projectionOn ? 1 : 0) + return body + } + + /// Local typed format. This is kept separate from the public K1G constants so + /// firmware validation can replace only this function when exact nav-info framing is confirmed. + static func navigationInfo(_ instruction: DashNavigationInstruction) -> Data { + var body = Data([0x4E, 0x41, 0x56, 0x01]) // NAV + local schema version + body.append(instruction.maneuver.rawValue) + appendUInt32(UInt32(clamping: instruction.distanceToTurnMeters), to: &body) + appendUInt32(UInt32(clamping: instruction.remainingDistanceMeters), to: &body) + let road = Data(instruction.roadName.utf8.prefix(48)) + body.append(UInt8(clamping: road.count)) + body.append(road) + return body + } + + private static func appendUInt32(_ value: UInt32, to data: inout Data) { + data.append(UInt8((value >> 24) & 0xff)) + data.append(UInt8((value >> 16) & 0xff)) + data.append(UInt8((value >> 8) & 0xff)) + data.append(UInt8(value & 0xff)) + } +} From 8581d4017b9c5c738cdabf4f11449b1ad40a32f1 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:08:18 +0530 Subject: [PATCH 072/112] docs: embed protocol validation warning --- RideDash/DashProtocol/ProtocolResearchWarning.swift | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 RideDash/DashProtocol/ProtocolResearchWarning.swift diff --git a/RideDash/DashProtocol/ProtocolResearchWarning.swift b/RideDash/DashProtocol/ProtocolResearchWarning.swift new file mode 100644 index 0000000..8106e0c --- /dev/null +++ b/RideDash/DashProtocol/ProtocolResearchWarning.swift @@ -0,0 +1,5 @@ +import Foundation + +enum ProtocolResearchWarning { + static let packetBuilders = "Route/nav-info packet builders are intentionally isolated. Validate exact firmware framing on owned hardware before riding." +} From 8e31557c9ed042805a3ae8b519065c4a077296fd Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:08:19 +0530 Subject: [PATCH 073/112] docs: expand protocol implementation notes --- Docs/PROTOCOL_NOTES.md | 143 +++++++++++++++++++++++++++++++++++------ 1 file changed, 122 insertions(+), 21 deletions(-) diff --git a/Docs/PROTOCOL_NOTES.md b/Docs/PROTOCOL_NOTES.md index 5f15e20..ec655b5 100644 --- a/Docs/PROTOCOL_NOTES.md +++ b/Docs/PROTOCOL_NOTES.md @@ -1,31 +1,132 @@ -# Protocol Notes +# RideDash protocol notes -RideDash keeps hardware/protocol assumptions isolated from product UI. The constants below are starting points from public interoperability references and must be validated against the user's owned dash firmware. +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. -## Reference endpoints +## Default network profile -- Dash host hypothesis: `192.168.1.1` -- Control send port hypothesis: UDP `2000` -- Input/listen port hypothesis: UDP `2002` -- H.264/RTP video port hypothesis: UDP `5000` -- Broadcast hypothesis: `192.168.1.255` -- Initial renderer size hypothesis: `526×300` +| 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` | -## Known public control messages +All network values are represented by `DashProtocolProfile` and are editable from the developer-facing Display screen. -The public better-dash reference describes: +## K1G envelope -- RSA/AES session authentication before navigation projection. -- Navigation context and route-card messages. -- Projection-on / projection-off TLVs. -- Start-navigation command. -- Periodic projection, route, nav-info and status heartbeats. -- Button/input events received on the control listener. +The current codec treats packets as: -## Safety rule +```text +0..1 outer packet length, big endian +2..3 segment count, big endian +4..7 reserved/header bytes +8.. TLV-like segments +``` -Unknown message families stay read-only until their meaning is understood. The app never sends commands to ECU, throttle, ABS, traction control, brakes, immobilizer, engine-management or other safety-critical services. +Each segment begins with: -## Compatibility strategy +```text +type:1 | subtype:1 | length:2 big endian | payload:length +``` -All endpoint/packet assumptions live in `DashProtocolConfiguration` and `DashProtocolConstants`. If manual testing shows firmware variation, add a capability profile rather than scattering conditional literals throughout UI/network code. +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. From 3fa2d86d5e4dcb2d6e11292498e46e2b286a4955 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:08:26 +0530 Subject: [PATCH 074/112] docs: record public protocol source reference --- RideDash/DashProtocol/ProtocolSourceReference.swift | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 RideDash/DashProtocol/ProtocolSourceReference.swift diff --git a/RideDash/DashProtocol/ProtocolSourceReference.swift b/RideDash/DashProtocol/ProtocolSourceReference.swift new file mode 100644 index 0000000..b84d812 --- /dev/null +++ b/RideDash/DashProtocol/ProtocolSourceReference.swift @@ -0,0 +1,5 @@ +import Foundation + +enum ProtocolSourceReference { + static let betterDashRepository = "https://github.com/OpenMotoDash/better-dash" +} From 2779fd8761295434ba9ab06c4e1873bb9e49d84a Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:08:34 +0530 Subject: [PATCH 075/112] docs: note clean-room protocol asset boundary --- RideDash/DashProtocol/DashProtocolLicenseNote.swift | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 RideDash/DashProtocol/DashProtocolLicenseNote.swift diff --git a/RideDash/DashProtocol/DashProtocolLicenseNote.swift b/RideDash/DashProtocol/DashProtocolLicenseNote.swift new file mode 100644 index 0000000..6eb06f2 --- /dev/null +++ b/RideDash/DashProtocol/DashProtocolLicenseNote.swift @@ -0,0 +1,4 @@ +import Foundation + +/// No manufacturer-owned assets, private keys, certificates or firmware blobs are bundled. +enum DashProtocolLicenseNote {} From ad33902245f2250c166bdee6a06d7594afa8382c Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:08:51 +0530 Subject: [PATCH 076/112] feat: add H264 NAL models --- RideDash/ProjectionCore/H264NALUnit.swift | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 RideDash/ProjectionCore/H264NALUnit.swift diff --git a/RideDash/ProjectionCore/H264NALUnit.swift b/RideDash/ProjectionCore/H264NALUnit.swift new file mode 100644 index 0000000..5313566 --- /dev/null +++ b/RideDash/ProjectionCore/H264NALUnit.swift @@ -0,0 +1,16 @@ +import Foundation + +struct H264NALUnit: Sendable, Hashable { + let data: Data + + var type: UInt8 { data.first.map { $0 & 0x1F } ?? 0 } + var isIDR: Bool { type == 5 } + var isSPS: Bool { type == 7 } + var isPPS: Bool { type == 8 } +} + +struct EncodedH264Frame: Sendable { + let presentationTime: Double + let isKeyFrame: Bool + let nalUnits: [H264NALUnit] +} From 4fad0a3ab0648f844c66b279f932419d072792fc Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:09:19 +0530 Subject: [PATCH 077/112] feat: implement VideoToolbox H264 encoder --- RideDash/ProjectionCore/H264Encoder.swift | 193 ++++++++++++++++++++++ 1 file changed, 193 insertions(+) create mode 100644 RideDash/ProjectionCore/H264Encoder.swift diff --git a/RideDash/ProjectionCore/H264Encoder.swift b/RideDash/ProjectionCore/H264Encoder.swift new file mode 100644 index 0000000..445061d --- /dev/null +++ b/RideDash/ProjectionCore/H264Encoder.swift @@ -0,0 +1,193 @@ +import CoreMedia +import Foundation +import VideoToolbox + +final class H264Encoder { + var onEncodedFrame: ((EncodedH264Frame) -> Void)? + var onError: ((Error) -> Void)? + + private var session: VTCompressionSession? + private let width: Int32 + private let height: Int32 + private let fps: Int32 + private let bitrate: Int + + init(width: Int, height: Int, fps: Double, bitrate: Int) throws { + self.width = Int32(width) + self.height = Int32(height) + self.fps = Int32(max(1, fps.rounded())) + self.bitrate = bitrate + try configure() + } + + deinit { invalidate() } + + func encode(_ pixelBuffer: CVPixelBuffer, presentationTime: CMTime) throws { + guard let session else { throw H264EncoderError.sessionUnavailable } + var flags = VTEncodeInfoFlags() + let status = VTCompressionSessionEncodeFrame( + session, + imageBuffer: pixelBuffer, + presentationTimeStamp: presentationTime, + duration: CMTime(value: 1, timescale: fps), + frameProperties: nil, + sourceFrameRefcon: nil, + infoFlagsOut: &flags + ) + guard status == noErr else { throw H264EncoderError.encodeFailed(status) } + } + + func completeFrames() { + if let session { + VTCompressionSessionCompleteFrames(session, untilPresentationTimeStamp: .invalid) + } + } + + func invalidate() { + if let session { + VTCompressionSessionInvalidate(session) + self.session = nil + } + } + + private func configure() throws { + var created: VTCompressionSession? + let status = VTCompressionSessionCreate( + allocator: kCFAllocatorDefault, + width: width, + height: height, + codecType: kCMVideoCodecType_H264, + encoderSpecification: nil, + imageBufferAttributes: nil, + compressedDataAllocator: nil, + outputCallback: h264OutputCallback, + refcon: Unmanaged.passUnretained(self).toOpaque(), + compressionSessionOut: &created + ) + guard status == noErr, let created else { + throw H264EncoderError.sessionCreationFailed(status) + } + session = created + + set(kVTCompressionPropertyKey_RealTime, value: kCFBooleanTrue) + set(kVTCompressionPropertyKey_AllowFrameReordering, value: kCFBooleanFalse) + set(kVTCompressionPropertyKey_AverageBitRate, value: NSNumber(value: bitrate)) + set(kVTCompressionPropertyKey_ExpectedFrameRate, value: NSNumber(value: fps)) + set(kVTCompressionPropertyKey_MaxKeyFrameInterval, value: NSNumber(value: max(1, fps * 2))) + set(kVTCompressionPropertyKey_ProfileLevel, value: kVTProfileLevel_H264_Baseline_AutoLevel) + + let prepareStatus = VTCompressionSessionPrepareToEncodeFrames(created) + guard prepareStatus == noErr else { + throw H264EncoderError.prepareFailed(prepareStatus) + } + } + + private func set(_ key: CFString, value: CFTypeRef) { + guard let session else { return } + VTSessionSetProperty(session, key: key, value: value) + } + + fileprivate func handle(status: OSStatus, sampleBuffer: CMSampleBuffer?) { + guard status == noErr else { + onError?(H264EncoderError.encodeFailed(status)) + return + } + guard let sampleBuffer, CMSampleBufferDataIsReady(sampleBuffer) else { return } + + let isKeyFrame: Bool = { + guard let attachments = CMSampleBufferGetSampleAttachmentsArray( + sampleBuffer, + createIfNecessary: false + ) as? [[CFString: Any]], let first = attachments.first else { return false } + return first[kCMSampleAttachmentKey_NotSync] == nil + }() + + var nalUnits: [H264NALUnit] = [] + if isKeyFrame, let format = CMSampleBufferGetFormatDescription(sampleBuffer) { + nalUnits.append(contentsOf: parameterSets(from: format)) + } + nalUnits.append(contentsOf: avccNALUnits(from: sampleBuffer)) + + guard !nalUnits.isEmpty else { return } + let pts = CMTimeGetSeconds(CMSampleBufferGetPresentationTimeStamp(sampleBuffer)) + onEncodedFrame?( + EncodedH264Frame( + presentationTime: pts.isFinite ? pts : 0, + isKeyFrame: isKeyFrame, + nalUnits: nalUnits + ) + ) + } + + private func parameterSets(from format: CMFormatDescription) -> [H264NALUnit] { + var result: [H264NALUnit] = [] + for index in 0..<2 { + var pointer: UnsafePointer? + var size = 0 + var count = 0 + var headerLength: Int32 = 0 + let status = CMVideoFormatDescriptionGetH264ParameterSetAtIndex( + format, + parameterSetIndex: index, + parameterSetPointerOut: &pointer, + parameterSetSizeOut: &size, + parameterSetCountOut: &count, + nalUnitHeaderLengthOut: &headerLength + ) + if status == noErr, let pointer, size > 0 { + result.append(H264NALUnit(data: Data(bytes: pointer, count: size))) + } + } + return result + } + + private func avccNALUnits(from sampleBuffer: CMSampleBuffer) -> [H264NALUnit] { + guard let blockBuffer = CMSampleBufferGetDataBuffer(sampleBuffer) else { return [] } + let totalLength = CMBlockBufferGetDataLength(blockBuffer) + guard totalLength > 4 else { return [] } + + var bytes = Data(count: totalLength) + let status = bytes.withUnsafeMutableBytes { destination in + CMBlockBufferCopyDataBytes( + blockBuffer, + atOffset: 0, + dataLength: totalLength, + destination: destination.baseAddress! + ) + } + guard status == kCMBlockBufferNoErr else { return [] } + + var result: [H264NALUnit] = [] + var offset = 0 + while offset + 4 <= bytes.count { + let length = bytes[offset..<(offset + 4)].reduce(0) { ($0 << 8) | Int($1) } + offset += 4 + guard length > 0, offset + length <= bytes.count else { break } + result.append(H264NALUnit(data: bytes.subdata(in: offset..<(offset + length)))) + offset += length + } + return result + } +} + +private let h264OutputCallback: VTCompressionOutputCallback = { refcon, _, status, _, sampleBuffer in + guard let refcon else { return } + let encoder = Unmanaged.fromOpaque(refcon).takeUnretainedValue() + encoder.handle(status: status, sampleBuffer: sampleBuffer) +} + +enum H264EncoderError: LocalizedError { + case sessionCreationFailed(OSStatus) + case prepareFailed(OSStatus) + case encodeFailed(OSStatus) + case sessionUnavailable + + var errorDescription: String? { + switch self { + case .sessionCreationFailed(let code): return "H.264 session creation failed (\(code))." + case .prepareFailed(let code): return "H.264 encoder prepare failed (\(code))." + case .encodeFailed(let code): return "H.264 encode failed (\(code))." + case .sessionUnavailable: return "H.264 encoder session is unavailable." + } + } +} From fc4fc9bbd2c5c72c0b195f5db248c1e21fdc4f6f Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:09:40 +0530 Subject: [PATCH 078/112] feat: implement H264 RTP packetizer with FU-A --- RideDash/ProjectionCore/RTPPacketizer.swift | 108 ++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 RideDash/ProjectionCore/RTPPacketizer.swift diff --git a/RideDash/ProjectionCore/RTPPacketizer.swift b/RideDash/ProjectionCore/RTPPacketizer.swift new file mode 100644 index 0000000..d9cef02 --- /dev/null +++ b/RideDash/ProjectionCore/RTPPacketizer.swift @@ -0,0 +1,108 @@ +import Foundation + +struct RTPPacket: Sendable { + let sequenceNumber: UInt16 + let timestamp: UInt32 + let marker: Bool + let data: Data +} + +final class RTPPacketizer { + private var sequenceNumber: UInt16 + private let ssrc: UInt32 + private let payloadType: UInt8 + private let maxPayloadSize: Int + + init( + initialSequence: UInt16 = UInt16.random(in: 0...UInt16.max), + ssrc: UInt32 = UInt32.random(in: 1...UInt32.max), + payloadType: UInt8 = 96, + maxPayloadSize: Int = 1_180 + ) { + self.sequenceNumber = initialSequence + self.ssrc = ssrc + self.payloadType = payloadType + self.maxPayloadSize = max(256, maxPayloadSize) + } + + func packetize(frame: EncodedH264Frame) -> [RTPPacket] { + let scaled = max(0, frame.presentationTime) * 90_000 + let timestamp = UInt32(truncatingIfNeeded: UInt64(scaled.rounded())) + var result: [RTPPacket] = [] + + for (nalIndex, nal) in frame.nalUnits.enumerated() { + let isFinalNAL = nalIndex == frame.nalUnits.count - 1 + if nal.data.count <= maxPayloadSize { + result.append(makePacket(payload: nal.data, timestamp: timestamp, marker: isFinalNAL)) + } else { + result.append(contentsOf: fragment(nal: nal, timestamp: timestamp, markerOnLast: isFinalNAL)) + } + } + return result + } + + private func fragment(nal: H264NALUnit, timestamp: UInt32, markerOnLast: Bool) -> [RTPPacket] { + guard let nalHeader = nal.data.first else { return [] } + let payload = nal.data.dropFirst() + let chunkSize = maxPayloadSize - 2 + let fuIndicator = (nalHeader & 0xE0) | 28 + let nalType = nalHeader & 0x1F + + var result: [RTPPacket] = [] + var offset = 0 + while offset < payload.count { + let end = min(offset + chunkSize, payload.count) + let isStart = offset == 0 + let isEnd = end == payload.count + var fuHeader = nalType + if isStart { fuHeader |= 0x80 } + if isEnd { fuHeader |= 0x40 } + + var body = Data([fuIndicator, fuHeader]) + let lower = payload.index(payload.startIndex, offsetBy: offset) + let upper = payload.index(payload.startIndex, offsetBy: end) + body.append(contentsOf: payload[lower.. RTPPacket { + let currentSequence = sequenceNumber + sequenceNumber &+= 1 + + var packet = Data(capacity: 12 + payload.count) + packet.append(0x80) // RTP v2 + packet.append((marker ? 0x80 : 0x00) | (payloadType & 0x7F)) + appendUInt16(currentSequence, to: &packet) + appendUInt32(timestamp, to: &packet) + appendUInt32(ssrc, to: &packet) + packet.append(payload) + + return RTPPacket( + sequenceNumber: currentSequence, + timestamp: timestamp, + marker: marker, + data: packet + ) + } + + private func appendUInt16(_ value: UInt16, to data: inout Data) { + data.append(UInt8((value >> 8) & 0xff)) + data.append(UInt8(value & 0xff)) + } + + private func appendUInt32(_ value: UInt32, to data: inout Data) { + data.append(UInt8((value >> 24) & 0xff)) + data.append(UInt8((value >> 16) & 0xff)) + data.append(UInt8((value >> 8) & 0xff)) + data.append(UInt8(value & 0xff)) + } +} From 5704f473d6feb1abfb2e71d5eee40b960e623d58 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:09:52 +0530 Subject: [PATCH 079/112] feat: add projection UI state --- .../ProjectionCore/ProjectionUIState.swift | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 RideDash/ProjectionCore/ProjectionUIState.swift diff --git a/RideDash/ProjectionCore/ProjectionUIState.swift b/RideDash/ProjectionCore/ProjectionUIState.swift new file mode 100644 index 0000000..6a09fac --- /dev/null +++ b/RideDash/ProjectionCore/ProjectionUIState.swift @@ -0,0 +1,25 @@ +import Foundation + +struct ProjectionUIState: Sendable, Equatable { + var maneuver: NavigationManeuver = .continueStraight + var distanceToTurnMeters: Int = 0 + var remainingDistanceMeters: Int = 0 + var eta: Date? + var roadName: String = "Ready" + var speedKPH: Double = 0 + var gpsAccuracyMeters: Double? + var isRerouting = false + var statusText = "RideDash" + + static let preview = ProjectionUIState( + maneuver: .turnRight, + distanceToTurnMeters: 350, + remainingDistanceMeters: 12_400, + eta: Date().addingTimeInterval(1_800), + roadName: "Continue to destination", + speedKPH: 42, + gpsAccuracyMeters: 5, + isRerouting: false, + statusText: "Navigation" + ) +} From 1a650a13c0cd744c2f1b9d5adbb0c2d4a256e882 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:10:24 +0530 Subject: [PATCH 080/112] feat: implement 526x300 offscreen dash renderer --- RideDash/ProjectionCore/DashRenderer.swift | 232 +++++++++++++++++++++ 1 file changed, 232 insertions(+) create mode 100644 RideDash/ProjectionCore/DashRenderer.swift diff --git a/RideDash/ProjectionCore/DashRenderer.swift b/RideDash/ProjectionCore/DashRenderer.swift new file mode 100644 index 0000000..f36a678 --- /dev/null +++ b/RideDash/ProjectionCore/DashRenderer.swift @@ -0,0 +1,232 @@ +import CoreGraphics +import CoreVideo +import Foundation +import UIKit + +final class DashRenderer { + 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 DashRendererError.pixelBufferCreationFailed(status) + } + + CVPixelBufferLockBaseAddress(buffer, []) + defer { CVPixelBufferUnlockBaseAddress(buffer, []) } + guard let baseAddress = CVPixelBufferGetBaseAddress(buffer) else { + throw DashRendererError.missingBaseAddress + } + + let bytesPerRow = CVPixelBufferGetBytesPerRow(buffer) + guard let context = CGContext( + data: baseAddress, + width: width, + height: height, + bitsPerComponent: 8, + bytesPerRow: bytesPerRow, + space: CGColorSpaceCreateDeviceRGB(), + bitmapInfo: CGBitmapInfo.byteOrder32Little.rawValue | + CGImageAlphaInfo.premultipliedFirst.rawValue + ) else { + throw DashRendererError.contextCreationFailed + } + + context.setFillColor(UIColor.black.cgColor) + context.fill(CGRect(x: 0, y: 0, width: width, height: height)) + context.translateBy(x: 0, y: CGFloat(height)) + context.scaleBy(x: 1, y: -1) + + UIGraphicsPushContext(context) + defer { UIGraphicsPopContext() } + draw(state, in: CGRect(x: 0, y: 0, width: width, height: height)) + return buffer + } + + private func draw(_ state: ProjectionUIState, in bounds: CGRect) { + let safe = bounds.insetBy(dx: 52, dy: 20) + let white = UIColor.white + let secondary = UIColor(white: 0.72, alpha: 1) + let accent = UIColor.systemOrange + + let topFont = UIFont.systemFont(ofSize: 17, weight: .semibold) + state.statusText.draw( + in: CGRect(x: safe.minX, y: safe.minY, width: safe.width, height: 24), + withAttributes: [.font: topFont, .foregroundColor: secondary] + ) + + let arrowRect = CGRect(x: safe.minX + 6, y: 65, width: 88, height: 88) + drawManeuver(state.maneuver, in: arrowRect, color: accent) + + let distanceText = formattedDistance(state.distanceToTurnMeters) + distanceText.draw( + in: CGRect(x: safe.minX + 110, y: 58, width: safe.width - 110, height: 52), + withAttributes: [ + .font: UIFont.monospacedDigitSystemFont(ofSize: 42, weight: .bold), + .foregroundColor: white + ] + ) + + state.roadName.draw( + in: CGRect(x: safe.minX + 110, y: 112, width: safe.width - 115, height: 58), + withAttributes: [ + .font: UIFont.systemFont(ofSize: 20, weight: .medium), + .foregroundColor: white + ] + ) + + let remaining = "Remaining \(formattedDistance(state.remainingDistanceMeters))" + remaining.draw( + in: CGRect(x: safe.minX, y: 204, width: safe.width * 0.55, height: 28), + withAttributes: [ + .font: UIFont.systemFont(ofSize: 16, weight: .medium), + .foregroundColor: secondary + ] + ) + + let speed = "\(Int(state.speedKPH.rounded())) km/h" + speed.draw( + in: CGRect(x: safe.midX, y: 204, width: safe.width * 0.5, height: 28), + withAttributes: [ + .font: UIFont.monospacedDigitSystemFont(ofSize: 17, weight: .semibold), + .foregroundColor: secondary + ] + ) + + if let eta = state.eta { + let formatter = DateFormatter() + formatter.dateFormat = "h:mm a" + let etaText = "ETA \(formatter.string(from: eta))" + etaText.draw( + in: CGRect(x: safe.minX, y: 238, width: safe.width, height: 28), + withAttributes: [ + .font: UIFont.systemFont(ofSize: 16, weight: .semibold), + .foregroundColor: white + ] + ) + } + + if state.isRerouting { + let text = "Rerouting…" + text.draw( + in: CGRect(x: safe.maxX - 120, y: safe.minY, width: 120, height: 24), + withAttributes: [.font: topFont, .foregroundColor: accent] + ) + } + } + + private func drawManeuver(_ maneuver: NavigationManeuver, in rect: CGRect, color: UIColor) { + guard let context = UIGraphicsGetCurrentContext() else { return } + context.saveGState() + defer { context.restoreGState() } + context.setStrokeColor(color.cgColor) + context.setFillColor(color.cgColor) + context.setLineWidth(12) + context.setLineCap(.round) + context.setLineJoin(.round) + + let center = CGPoint(x: rect.midX, y: rect.midY) + let top = rect.minY + 8 + let bottom = rect.maxY - 8 + let left = rect.minX + 8 + let right = rect.maxX - 8 + + switch maneuver { + case .turnLeft, .slightLeft: + context.move(to: CGPoint(x: center.x, y: bottom)) + context.addLine(to: CGPoint(x: center.x, y: center.y)) + context.addLine(to: CGPoint(x: left + 12, y: center.y)) + context.strokePath() + drawArrowHead(at: CGPoint(x: left + 8, y: center.y), pointing: .left, context: context) + case .turnRight, .slightRight: + context.move(to: CGPoint(x: center.x, y: bottom)) + context.addLine(to: CGPoint(x: center.x, y: center.y)) + context.addLine(to: CGPoint(x: right - 12, y: center.y)) + context.strokePath() + drawArrowHead(at: CGPoint(x: right - 8, y: center.y), pointing: .right, context: context) + case .uTurn: + context.addArc(center: CGPoint(x: center.x, y: center.y), radius: 25, startAngle: .pi / 2, endAngle: .pi * 1.8, clockwise: true) + context.strokePath() + drawArrowHead(at: CGPoint(x: center.x - 24, y: center.y + 8), pointing: .down, context: context) + case .roundabout: + context.addEllipse(in: rect.insetBy(dx: 18, dy: 18)) + context.strokePath() + drawArrowHead(at: CGPoint(x: right - 12, y: center.y), pointing: .right, context: context) + case .arrive: + context.fillEllipse(in: CGRect(x: center.x - 16, y: center.y - 16, width: 32, height: 32)) + case .continueStraight: + context.move(to: CGPoint(x: center.x, y: bottom)) + context.addLine(to: CGPoint(x: center.x, y: top + 15)) + context.strokePath() + drawArrowHead(at: CGPoint(x: center.x, y: top + 6), pointing: .up, context: context) + } + } + + private enum ArrowDirection { case up, down, left, right } + + private func drawArrowHead(at point: CGPoint, pointing direction: ArrowDirection, context: CGContext) { + let size: CGFloat = 17 + let path = UIBezierPath() + switch direction { + case .up: + path.move(to: CGPoint(x: point.x, y: point.y - size)) + path.addLine(to: CGPoint(x: point.x - size, y: point.y + size * 0.6)) + path.addLine(to: CGPoint(x: point.x + size, y: point.y + size * 0.6)) + case .down: + path.move(to: CGPoint(x: point.x, y: point.y + size)) + path.addLine(to: CGPoint(x: point.x - size, y: point.y - size * 0.6)) + path.addLine(to: CGPoint(x: point.x + size, y: point.y - size * 0.6)) + case .left: + path.move(to: CGPoint(x: point.x - size, y: point.y)) + path.addLine(to: CGPoint(x: point.x + size * 0.6, y: point.y - size)) + path.addLine(to: CGPoint(x: point.x + size * 0.6, y: point.y + size)) + case .right: + path.move(to: CGPoint(x: point.x + size, y: point.y)) + path.addLine(to: CGPoint(x: point.x - size * 0.6, y: point.y - size)) + path.addLine(to: CGPoint(x: point.x - size * 0.6, y: point.y + size)) + } + path.close() + context.addPath(path.cgPath) + context.fillPath() + } + + private func formattedDistance(_ meters: Int) -> String { + if meters >= 1000 { + return String(format: "%.1f km", Double(meters) / 1000) + } + return "\(max(0, meters)) m" + } +} + +enum DashRendererError: LocalizedError { + case pixelBufferCreationFailed(CVReturn) + case missingBaseAddress + case contextCreationFailed + + var errorDescription: String? { + switch self { + case .pixelBufferCreationFailed(let code): return "Pixel buffer creation failed (\(code))." + case .missingBaseAddress: return "Pixel buffer has no writable base address." + case .contextCreationFailed: return "Could not create dash drawing context." + } + } +} From 6dee7368b9664d6b79ed12d50f1aee54b4b1b621 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:10:40 +0530 Subject: [PATCH 081/112] feat: stream rendered frames as H264 RTP over UDP --- .../ProjectionCore/ProjectionStreamer.swift | 103 ++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 RideDash/ProjectionCore/ProjectionStreamer.swift diff --git a/RideDash/ProjectionCore/ProjectionStreamer.swift b/RideDash/ProjectionCore/ProjectionStreamer.swift new file mode 100644 index 0000000..2da3957 --- /dev/null +++ b/RideDash/ProjectionCore/ProjectionStreamer.swift @@ -0,0 +1,103 @@ +import Combine +import CoreMedia +import Foundation + +@MainActor +final class ProjectionStreamer: ObservableObject { + @Published private(set) var isRunning = false + @Published private(set) var encodedFrameCount = 0 + @Published private(set) var sentPacketCount = 0 + @Published private(set) var lastError: String? + + private let transport: DashDatagramTransport + private let configuration: DashProtocolConfiguration + private let renderer: DashRenderer + private let packetizer = RTPPacketizer() + private var encoder: H264Encoder? + private var renderTask: Task? + private var stateProvider: (() -> ProjectionUIState)? + + init( + transport: DashDatagramTransport, + configuration: DashProtocolConfiguration + ) { + self.transport = transport + self.configuration = configuration + renderer = DashRenderer(width: configuration.renderWidth, height: configuration.renderHeight) + } + + func start(stateProvider: @escaping () -> ProjectionUIState) throws { + stop() + self.stateProvider = stateProvider + + let encoder = try H264Encoder( + width: configuration.renderWidth, + height: configuration.renderHeight, + fps: configuration.projectionFPS, + bitrate: configuration.videoBitrate + ) + encoder.onEncodedFrame = { [weak self] frame in + Task { @MainActor in + await self?.handle(frame) + } + } + encoder.onError = { [weak self] error in + Task { @MainActor in self?.lastError = error.localizedDescription } + } + self.encoder = encoder + isRunning = true + + let fps = max(1, configuration.projectionFPS) + let frameDuration = 1.0 / fps + let timescale = Int32(max(1, fps.rounded())) + + renderTask = Task { [weak self] in + guard let self else { return } + var frameIndex: Int64 = 0 + while !Task.isCancelled, self.isRunning { + do { + guard let provider = self.stateProvider, + let encoder = self.encoder else { break } + let pixelBuffer = try self.renderer.render(provider()) + try encoder.encode( + pixelBuffer, + presentationTime: CMTime(value: frameIndex, timescale: timescale) + ) + frameIndex += 1 + } catch { + self.lastError = error.localizedDescription + } + + do { + try await Task.sleep(for: .seconds(frameDuration)) + } catch { + break + } + } + } + } + + func stop() { + isRunning = false + renderTask?.cancel() + renderTask = nil + encoder?.completeFrames() + encoder?.invalidate() + encoder = nil + stateProvider = nil + } + + private func handle(_ frame: EncodedH264Frame) async { + encodedFrameCount += 1 + let packets = packetizer.packetize(frame: frame) + for packet in packets { + do { + try await transport.sendVideo(packet.data) + sentPacketCount += 1 + } catch { + lastError = error.localizedDescription + break + } + } + } +} From 2f27154a654efb2d7e821a9658180d388bff2101 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:10:56 +0530 Subject: [PATCH 082/112] feat: add navigation-grade CoreLocation service --- RideDash/NavigationCore/LocationService.swift | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 RideDash/NavigationCore/LocationService.swift diff --git a/RideDash/NavigationCore/LocationService.swift b/RideDash/NavigationCore/LocationService.swift new file mode 100644 index 0000000..ee03185 --- /dev/null +++ b/RideDash/NavigationCore/LocationService.swift @@ -0,0 +1,55 @@ +import Combine +import CoreLocation +import Foundation + +@MainActor +final class LocationService: NSObject, ObservableObject, CLLocationManagerDelegate { + @Published private(set) var location: CLLocation? + @Published private(set) var heading: CLHeading? + @Published private(set) var authorizationStatus: CLAuthorizationStatus + @Published private(set) var lastError: String? + + private let manager = CLLocationManager() + + override init() { + authorizationStatus = manager.authorizationStatus + super.init() + manager.delegate = self + manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation + manager.distanceFilter = 2 + manager.activityType = .automotiveNavigation + manager.pausesLocationUpdatesAutomatically = true + } + + func requestPermission() { + manager.requestWhenInUseAuthorization() + } + + func startNavigationUpdates() { + manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation + manager.startUpdatingLocation() + manager.startUpdatingHeading() + } + + func stopNavigationUpdates() { + manager.stopUpdatingLocation() + manager.stopUpdatingHeading() + } + + func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) { + authorizationStatus = manager.authorizationStatus + } + + func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { + guard let latest = locations.last else { return } + location = latest + } + + func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) { + heading = newHeading + } + + func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { + lastError = error.localizedDescription + } +} From 381f696d2540528c94d85e603002eca293dfe96b Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:11:21 +0530 Subject: [PATCH 083/112] feat: implement MapKit navigation state engine --- .../NavigationCore/NavigationEngine.swift | 126 ++++++++++++++++++ 1 file changed, 126 insertions(+) create mode 100644 RideDash/NavigationCore/NavigationEngine.swift diff --git a/RideDash/NavigationCore/NavigationEngine.swift b/RideDash/NavigationCore/NavigationEngine.swift new file mode 100644 index 0000000..8a96c63 --- /dev/null +++ b/RideDash/NavigationCore/NavigationEngine.swift @@ -0,0 +1,126 @@ +import Combine +import CoreLocation +import Foundation +import MapKit + +@MainActor +final class NavigationEngine: ObservableObject { + @Published private(set) var route: MKRoute? + @Published private(set) var destination: MKMapItem? + @Published private(set) var projectionState: ProjectionUIState = .init() + @Published private(set) var isCalculating = false + @Published private(set) var lastError: String? + + private var stepIndex = 0 + + func plan(destinationQuery: String, from origin: CLLocation) async throws { + isCalculating = true + defer { isCalculating = false } + + let searchRequest = MKLocalSearch.Request() + searchRequest.naturalLanguageQuery = destinationQuery + searchRequest.region = MKCoordinateRegion( + center: origin.coordinate, + latitudinalMeters: 100_000, + longitudinalMeters: 100_000 + ) + let searchResponse = try await MKLocalSearch(request: searchRequest).start() + guard let item = searchResponse.mapItems.first else { + throw NavigationEngineError.destinationNotFound + } + + let request = MKDirections.Request() + request.source = MKMapItem(placemark: MKPlacemark(coordinate: origin.coordinate)) + request.destination = item + request.transportType = .automobile + request.requestsAlternateRoutes = false + + let response = try await MKDirections(request: request).calculate() + guard let route = response.routes.first else { + throw NavigationEngineError.routeUnavailable + } + + self.destination = item + self.route = route + stepIndex = firstUsefulStep(in: route.steps) + update(location: origin) + } + + func clearRoute() { + route = nil + destination = nil + stepIndex = 0 + projectionState = .init() + } + + func update(location: CLLocation) { + guard let route else { + projectionState.speedKPH = max(0, location.speed * 3.6) + projectionState.gpsAccuracyMeters = max(0, location.horizontalAccuracy) + return + } + + let steps = route.steps + guard !steps.isEmpty else { return } + stepIndex = min(max(0, stepIndex), steps.count - 1) + + var step = steps[stepIndex] + var distanceToTurn = distance(from: location, toEndOf: step) + if distanceToTurn < 30, stepIndex + 1 < steps.count { + stepIndex += 1 + step = steps[stepIndex] + distanceToTurn = distance(from: location, toEndOf: step) + } + + let laterDistance = steps.dropFirst(stepIndex + 1).reduce(0) { $0 + $1.distance } + let remaining = max(0, distanceToTurn + laterDistance) + let remainingRatio = route.distance > 0 ? remaining / route.distance : 0 + let eta = Date().addingTimeInterval(max(0, route.expectedTravelTime * remainingRatio)) + + projectionState = ProjectionUIState( + maneuver: maneuver(from: step.instructions), + distanceToTurnMeters: Int(distanceToTurn.rounded()), + remainingDistanceMeters: Int(remaining.rounded()), + eta: eta, + roadName: step.instructions.isEmpty ? (destination?.name ?? "Continue") : step.instructions, + speedKPH: max(0, location.speed * 3.6), + gpsAccuracyMeters: max(0, location.horizontalAccuracy), + isRerouting: false, + statusText: location.horizontalAccuracy > 35 ? "GPS accuracy low" : "Navigation" + ) + } + + private func firstUsefulStep(in steps: [MKRoute.Step]) -> Int { + steps.firstIndex(where: { !$0.instructions.isEmpty && $0.distance > 0 }) ?? 0 + } + + private func distance(from location: CLLocation, toEndOf step: MKRoute.Step) -> CLLocationDistance { + guard step.polyline.pointCount > 0 else { return step.distance } + let point = step.polyline.point(at: step.polyline.pointCount - 1).coordinate + return location.distance(from: CLLocation(latitude: point.latitude, longitude: point.longitude)) + } + + private func maneuver(from instructions: String) -> NavigationManeuver { + let text = instructions.lowercased() + if text.contains("u-turn") || text.contains("u turn") { return .uTurn } + if text.contains("roundabout") || text.contains("circle") { return .roundabout } + if text.contains("slight left") || text.contains("keep left") { return .slightLeft } + if text.contains("slight right") || text.contains("keep right") { return .slightRight } + if text.contains("left") { return .turnLeft } + if text.contains("right") { return .turnRight } + if text.contains("arrive") || text.contains("destination") { return .arrive } + return .continueStraight + } +} + +enum NavigationEngineError: LocalizedError { + case destinationNotFound + case routeUnavailable + + var errorDescription: String? { + switch self { + case .destinationNotFound: return "Destination could not be found." + case .routeUnavailable: return "No driving route is available." + } + } +} From 85ff20d7990c4f2e4d2c83f43cbf35930eba2b2f Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:11:30 +0530 Subject: [PATCH 084/112] feat: parse shared map destinations --- .../NavigationShareParser.swift | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 RideDash/NavigationCore/NavigationShareParser.swift diff --git a/RideDash/NavigationCore/NavigationShareParser.swift b/RideDash/NavigationCore/NavigationShareParser.swift new file mode 100644 index 0000000..42a7490 --- /dev/null +++ b/RideDash/NavigationCore/NavigationShareParser.swift @@ -0,0 +1,21 @@ +import Foundation + +struct SharedDestination: Sendable { + var query: String +} + +enum NavigationShareParser { + static func parse(_ text: String) -> SharedDestination? { + let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) + guard !trimmed.isEmpty else { return nil } + if let url = URL(string: trimmed), let components = URLComponents(url: url, resolvingAgainstBaseURL: false) { + for key in ["q", "query", "destination", "daddr"] { + if let value = components.queryItems?.first(where: { $0.name.lowercased() == key })?.value, + !value.isEmpty { + return SharedDestination(query: value) + } + } + } + return SharedDestination(query: trimmed) + } +} From cb37b9d120e07475460d56defcff5c1c6a48a10a Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:11:37 +0530 Subject: [PATCH 085/112] feat: add RideDash route deep link parser --- RideDash/NavigationCore/NavigationDeepLink.swift | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 RideDash/NavigationCore/NavigationDeepLink.swift diff --git a/RideDash/NavigationCore/NavigationDeepLink.swift b/RideDash/NavigationCore/NavigationDeepLink.swift new file mode 100644 index 0000000..e9cac0f --- /dev/null +++ b/RideDash/NavigationCore/NavigationDeepLink.swift @@ -0,0 +1,13 @@ +import Foundation + +enum NavigationDeepLink { + static func destination(from url: URL) -> SharedDestination? { + guard url.scheme?.lowercased() == "ridedash" else { return nil } + let components = URLComponents(url: url, resolvingAgainstBaseURL: false) + if url.host == "route", + let value = components?.queryItems?.first(where: { $0.name == "q" || $0.name == "url" })?.value { + return NavigationShareParser.parse(value) + } + return nil + } +} From ba71faae1bff4701f48ffa6c2c81935a17188bbe Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:12:04 +0530 Subject: [PATCH 086/112] feat: orchestrate auth navigation projection and input lifecycle --- .../DashProtocol/DashSessionCoordinator.swift | 188 ++++++++++++++++++ 1 file changed, 188 insertions(+) create mode 100644 RideDash/DashProtocol/DashSessionCoordinator.swift diff --git a/RideDash/DashProtocol/DashSessionCoordinator.swift b/RideDash/DashProtocol/DashSessionCoordinator.swift new file mode 100644 index 0000000..e8d555a --- /dev/null +++ b/RideDash/DashProtocol/DashSessionCoordinator.swift @@ -0,0 +1,188 @@ +import Combine +import Foundation + +@MainActor +final class DashSessionCoordinator: ObservableObject { + @Published private(set) var state: DashSessionState = .disconnected + @Published private(set) var timeline: [DashSessionTimelineEntry] = [] + @Published private(set) var lastError: String? + @Published private(set) var lastInput: DashInputAction? + @Published private(set) var metrics = DashSessionMetrics() + + let transport: DashDatagramTransport + let configuration: DashProtocolConfiguration + let streamer: ProjectionStreamer + + private let policy: DashSessionPolicy + private let authenticator: DashAuthenticator + private var inputTask: Task? + private var heartbeatTask: Task? + private var routeCard = RouteCard(title: "RideDash") + private var navigationInstruction = DashNavigationInstruction( + maneuver: .continueStraight, + distanceToTurnMeters: 0, + remainingDistanceMeters: 0, + roadName: "Ready" + ) + + init( + configuration: DashProtocolConfiguration = .default, + policy: DashSessionPolicy = .init() + ) { + self.configuration = configuration + self.policy = policy + transport = DashDatagramTransport() + authenticator = DashAuthenticator(timeout: policy.authenticationTimeout) + streamer = ProjectionStreamer(transport: transport, configuration: configuration) + } + + func connect(ssid: String) async { + await disconnect() + do { + transition(.transportReady, "Starting UDP control/input transport") + try transport.start(configuration: configuration) + metrics.connectedAt = .now + + transition(.authenticating, "Requesting dash session authentication") + _ = try await authenticator.authenticate(ssid: ssid, transport: transport) + metrics.authenticatedAt = .now + transition(.authenticated, "Session authentication accepted") + + startInputLoop() + try await enterNavigationMode() + transition(.navigationReady, "Dash navigation control plane initialized") + } catch { + fail(error) + } + } + + func startProjection(stateProvider: @escaping () -> ProjectionUIState) async { + guard state == .navigationReady || state == .projecting else { + fail(DashProtocolError.projectionNotReady) + return + } + do { + try await sendProjectionOnSequence() + try streamer.start(stateProvider: stateProvider) + metrics.projectionStartedAt = .now + transition(.projecting, "H.264/RTP projection started") + startHeartbeatLoop() + } catch { + fail(error) + } + } + + func updateNavigation(_ state: ProjectionUIState) { + routeCard = RouteCard( + title: state.roadName.isEmpty ? configuration.routeTitle : state.roadName, + remainingDistanceMeters: state.remainingDistanceMeters, + projectionOn: true + ) + navigationInstruction = DashNavigationInstruction( + maneuver: state.maneuver, + distanceToTurnMeters: state.distanceToTurnMeters, + remainingDistanceMeters: state.remainingDistanceMeters, + roadName: state.roadName + ) + } + + func stopProjection() async { + heartbeatTask?.cancel() + heartbeatTask = nil + streamer.stop() + do { + try await transport.sendControl(ProjectionControlPackets.projectionStop()) + try await transport.sendControl(ProjectionControlPackets.projectionOff()) + } catch { + lastError = error.localizedDescription + } + if state == .projecting { transition(.navigationReady, "Projection stopped") } + } + + func disconnect() async { + if state == .projecting || state == .navigationReady { + await stopProjection() + } + inputTask?.cancel() + inputTask = nil + heartbeatTask?.cancel() + heartbeatTask = nil + transport.stop() + metrics = DashSessionMetrics() + transition(.disconnected, "Session disconnected") + } + + private func enterNavigationMode() async throws { + try await transport.sendControl(ProjectionControlPackets.navigationContext()) + try await transport.sendControl(ProjectionControlPackets.emptyNavigationLists()) + // Route/nav payload builders are intentionally isolated because their inner layout + // is the most firmware-sensitive part of the public interoperability research. + try await transport.sendControl(DashPacketBuilder.routeCard(routeCard)) + try await transport.sendControl(ProjectionControlPackets.projectionFrame()) + try await transport.sendControl(ProjectionControlPackets.projectionOn()) + try await transport.sendControl(ProjectionControlPackets.startNavigation()) + } + + private func sendProjectionOnSequence() async throws { + try await transport.sendControl(ProjectionControlPackets.projectionFrame()) + try await transport.sendControl(ProjectionControlPackets.projectionOn()) + try await transport.sendControl(ProjectionControlPackets.startNavigation()) + } + + private func startInputLoop() { + inputTask?.cancel() + inputTask = Task { [weak self] in + guard let self else { return } + for await datagram in self.transport.incomingPackets { + guard !Task.isCancelled else { break } + self.metrics.inboundPackets += datagram.direction == .inbound ? 1 : 0 + self.metrics.outboundPackets += datagram.direction == .outbound ? 1 : 0 + guard datagram.direction == .inbound, + let event = DashInputDecoder.decode(datagram.payload) else { continue } + self.lastInput = event.action + self.timeline.append( + DashSessionTimelineEntry(state: self.state, message: "Dash input: \(event.action.rawValue)") + ) + if let ack = try? DashInputDecoder.acknowledgement(for: event) { + try? await self.transport.sendControl(ack) + } + } + } + } + + private func startHeartbeatLoop() { + heartbeatTask?.cancel() + heartbeatTask = Task { [weak self] in + guard let self else { return } + var projectionTick = 0 + while !Task.isCancelled, self.state == .projecting { + do { + try await self.transport.sendControl(ProjectionControlPackets.projectionFrame()) + projectionTick += 1 + + let ticksPerSecond = max(1, Int(self.policy.projectionHeartbeatHz.rounded())) + if projectionTick.isMultiple(of: ticksPerSecond) { + try await self.transport.sendControl(DashPacketBuilder.routeCard(self.routeCard)) + try await self.transport.sendControl(DashPacketBuilder.navigationInfo(self.navigationInstruction)) + } + } catch { + self.lastError = error.localizedDescription + } + + let hz = max(1, self.policy.projectionHeartbeatHz) + try? await Task.sleep(for: .seconds(1.0 / hz)) + } + } + } + + private func transition(_ newState: DashSessionState, _ message: String) { + state = newState + timeline.append(DashSessionTimelineEntry(state: newState, message: message)) + if timeline.count > 200 { timeline.removeFirst(timeline.count - 200) } + } + + private func fail(_ error: Error) { + lastError = error.localizedDescription + transition(.failed, error.localizedDescription) + } +} From 5455fbfa4d07a3314035f5b67901e0f9c149d3ec Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:12:15 +0530 Subject: [PATCH 087/112] feat: add protocol hardware validation state --- RideDash/DashProtocol/ProtocolValidationState.swift | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 RideDash/DashProtocol/ProtocolValidationState.swift diff --git a/RideDash/DashProtocol/ProtocolValidationState.swift b/RideDash/DashProtocol/ProtocolValidationState.swift new file mode 100644 index 0000000..8ace10d --- /dev/null +++ b/RideDash/DashProtocol/ProtocolValidationState.swift @@ -0,0 +1,9 @@ +import Foundation + +struct ProtocolValidationState: Codable, Sendable { + var authenticationValidated = false + var routeCardValidated = false + var navigationInfoValidated = false + var videoValidated = false + var inputValidated = false +} From 59a3468a4468b5e74a6fc26834aa462afd8e0a88 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:12:34 +0530 Subject: [PATCH 088/112] feat: add shared application model --- RideDash/App/AppModel.swift | 64 +++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 RideDash/App/AppModel.swift diff --git a/RideDash/App/AppModel.swift b/RideDash/App/AppModel.swift new file mode 100644 index 0000000..0816ba8 --- /dev/null +++ b/RideDash/App/AppModel.swift @@ -0,0 +1,64 @@ +import Combine +import Foundation + +@MainActor +final class AppModel: ObservableObject { + let wiFiManager = TripperWiFiManager() + let locationService = LocationService() + let navigationEngine = NavigationEngine() + let dashSession = DashSessionCoordinator() + + @Published var dashSSID = "" + @Published var dashPassphrase = "" + @Published var destinationQuery = "" + + private var cancellables: Set = [] + + init() { + locationService.$location + .compactMap { $0 } + .sink { [weak self] location in + guard let self else { return } + self.navigationEngine.update(location: location) + self.dashSession.updateNavigation(self.navigationEngine.projectionState) + } + .store(in: &cancellables) + + navigationEngine.$projectionState + .sink { [weak self] state in + self?.dashSession.updateNavigation(state) + } + .store(in: &cancellables) + } + + func connectDash() async { + guard !dashSSID.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return } + do { + try await wiFiManager.join(ssid: dashSSID, passphrase: dashPassphrase) + dashPassphrase = "" + await dashSession.connect(ssid: dashSSID) + } catch { + dashPassphrase = "" + } + } + + func startProjection() async { + await dashSession.startProjection { [weak self] in + self?.navigationEngine.projectionState ?? .preview + } + } + + func stopProjection() async { + await dashSession.stopProjection() + } + + func planRoute() async { + guard let origin = locationService.location, + !destinationQuery.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return } + do { + try await navigationEngine.plan(destinationQuery: destinationQuery, from: origin) + } catch { + // NavigationEngine exposes its own state; UI can surface failure after manual validation. + } + } +} From 0b9cedafff95d02e29c8ce024b30c75e9d06576f Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:12:41 +0530 Subject: [PATCH 089/112] feat: add persistent vehicle model --- RideDash/Models/Vehicle.swift | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 RideDash/Models/Vehicle.swift diff --git a/RideDash/Models/Vehicle.swift b/RideDash/Models/Vehicle.swift new file mode 100644 index 0000000..297d1b9 --- /dev/null +++ b/RideDash/Models/Vehicle.swift @@ -0,0 +1,33 @@ +import Foundation +import SwiftData + +@Model +final class Vehicle { + var id: UUID + var name: String + var registrationNumber: String + var odometerKM: Double + var insuranceExpiry: Date? + var pollutionCertificateExpiry: Date? + var lastServiceDate: Date? + var isActive: Bool + + init( + name: String, + registrationNumber: String = "", + odometerKM: Double = 0, + insuranceExpiry: Date? = nil, + pollutionCertificateExpiry: Date? = nil, + lastServiceDate: Date? = nil, + isActive: Bool = false + ) { + id = UUID() + self.name = name + self.registrationNumber = registrationNumber + self.odometerKM = odometerKM + self.insuranceExpiry = insuranceExpiry + self.pollutionCertificateExpiry = pollutionCertificateExpiry + self.lastServiceDate = lastServiceDate + self.isActive = isActive + } +} From f808b768bc63bd92719b9e894deb24a6efe701ba Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:12:54 +0530 Subject: [PATCH 090/112] feat: add garage expense fuel and ride models --- RideDash/Models/OwnershipModels.swift | 100 ++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 RideDash/Models/OwnershipModels.swift diff --git a/RideDash/Models/OwnershipModels.swift b/RideDash/Models/OwnershipModels.swift new file mode 100644 index 0000000..1b04965 --- /dev/null +++ b/RideDash/Models/OwnershipModels.swift @@ -0,0 +1,100 @@ +import Foundation +import SwiftData + +enum ExpenseCategory: String, CaseIterable, Codable, Identifiable { + case fuel, service, repair, accessory, gear, food, stay, transport, 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 note: String + + var category: ExpenseCategory { + get { ExpenseCategory(rawValue: categoryRaw) ?? .other } + set { categoryRaw = newValue.rawValue } + } + + init(date: Date = .now, category: ExpenseCategory, amount: Double, odometerKM: Double? = nil, note: String = "") { + id = UUID() + self.date = date + categoryRaw = category.rawValue + self.amount = amount + self.odometerKM = odometerKM + self.note = note + } +} + +enum MaintenanceKind: String, CaseIterable, Codable, Identifiable { + case service, chainClean, chainLube, tyre, brake, accessory, other + var id: String { rawValue } +} + +@Model +final class MaintenanceEntry { + var id: UUID + var date: Date + var kindRaw: String + var odometerKM: Double + var note: 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, note: String = "", nextDueKM: Double? = nil, nextDueDate: Date? = nil) { + id = UUID() + self.date = date + kindRaw = kind.rawValue + self.odometerKM = odometerKM + self.note = note + 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 isFullTank: Bool + + init(date: Date = .now, odometerKM: Double, litres: Double, totalCost: Double, isFullTank: Bool) { + id = UUID() + self.date = date + self.odometerKM = odometerKM + self.litres = litres + self.totalCost = totalCost + self.isFullTank = isFullTank + } +} + +@Model +final class RideRecord { + var id: UUID + var startedAt: Date + var endedAt: Date? + var destination: String + var distanceKM: Double + var note: String + + init(startedAt: Date = .now, endedAt: Date? = nil, destination: String = "", distanceKM: Double = 0, note: String = "") { + id = UUID() + self.startedAt = startedAt + self.endedAt = endedAt + self.destination = destination + self.distanceKM = distanceKM + self.note = note + } +} From 662ea04e5071b0ff2ded5e4017ffe8b740b3f513 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:13:09 +0530 Subject: [PATCH 091/112] chore: add lifecycle testing marker --- RideDash/App/AppLifecycleNotes.swift | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 RideDash/App/AppLifecycleNotes.swift diff --git a/RideDash/App/AppLifecycleNotes.swift b/RideDash/App/AppLifecycleNotes.swift new file mode 100644 index 0000000..33afdc8 --- /dev/null +++ b/RideDash/App/AppLifecycleNotes.swift @@ -0,0 +1,5 @@ +import Foundation + +enum AppLifecycleNotes { + static let manualHardwareTesting = true +} From 16dd92e2eadab8ebaad69a13b066e57379da0d20 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:13:16 +0530 Subject: [PATCH 092/112] chore: mark full manual-test implementation phase --- RideDash/App/AppBuildInfo.swift | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 RideDash/App/AppBuildInfo.swift diff --git a/RideDash/App/AppBuildInfo.swift b/RideDash/App/AppBuildInfo.swift new file mode 100644 index 0000000..a445d97 --- /dev/null +++ b/RideDash/App/AppBuildInfo.swift @@ -0,0 +1,5 @@ +import Foundation + +struct AppBuildInfo { + static let implementationPhase = "full-manual-test" +} From 7d8a00ea7975c6c58487ce81bfc7ee4fa00706e1 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:13:23 +0530 Subject: [PATCH 093/112] chore: document manual hardware validation requirement --- RideDash/App/ManualValidation.swift | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 RideDash/App/ManualValidation.swift diff --git a/RideDash/App/ManualValidation.swift b/RideDash/App/ManualValidation.swift new file mode 100644 index 0000000..dc87dc7 --- /dev/null +++ b/RideDash/App/ManualValidation.swift @@ -0,0 +1,5 @@ +import Foundation + +enum ManualValidation { + static let required = true +} From a9e6a1f013c927739f95a5be5f971aedb90915e1 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:13:33 +0530 Subject: [PATCH 094/112] chore: add application source marker --- RideDash/App/README_PLACEHOLDER.swift | 1 + 1 file changed, 1 insertion(+) create mode 100644 RideDash/App/README_PLACEHOLDER.swift diff --git a/RideDash/App/README_PLACEHOLDER.swift b/RideDash/App/README_PLACEHOLDER.swift new file mode 100644 index 0000000..7b09645 --- /dev/null +++ b/RideDash/App/README_PLACEHOLDER.swift @@ -0,0 +1 @@ +// Temporary source marker; application wiring is completed in RootView/App entry updates. From c8ae61de4648b9d129c9a8df9f5030a632f82220 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:13:41 +0530 Subject: [PATCH 095/112] feat: add projection feature flags --- RideDash/App/FeatureFlags.swift | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 RideDash/App/FeatureFlags.swift diff --git a/RideDash/App/FeatureFlags.swift b/RideDash/App/FeatureFlags.swift new file mode 100644 index 0000000..3a6288f --- /dev/null +++ b/RideDash/App/FeatureFlags.swift @@ -0,0 +1,6 @@ +import Foundation + +enum FeatureFlags { + static let dashProjectionEnabled = true + static let manualHardwareValidation = true +} From 07c9d69ecc922919c7284d9db9ac69bfdcbe52d3 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:20:49 +0530 Subject: [PATCH 096/112] feat: add nav-info and status heartbeat loops --- RideDash/App/DashSessionCoordinator.swift | 91 +++++++++++++++++++++-- 1 file changed, 84 insertions(+), 7 deletions(-) diff --git a/RideDash/App/DashSessionCoordinator.swift b/RideDash/App/DashSessionCoordinator.swift index 3088afa..08541ab 100644 --- a/RideDash/App/DashSessionCoordinator.swift +++ b/RideDash/App/DashSessionCoordinator.swift @@ -57,6 +57,8 @@ final class DashSessionCoordinator: ObservableObject { private var authTimeoutTask: Task? private var projectionHeartbeatTask: Task? private var routeHeartbeatTask: Task? + private var navInfoHeartbeatTask: Task? + private var statusHeartbeatTask: Task? init(transport: DashTransport = DashTransport(), log: DiagnosticLog = DiagnosticLog()) { self.transport = transport @@ -115,8 +117,7 @@ final class DashSessionCoordinator: ObservableObject { routeTitle = title } - routeHeartbeatTask?.cancel() - projectionHeartbeatTask?.cancel() + cancelNavigationKeepAlives() state = .enteringNavigation try await sendHex(K1GCodec.navContextHex) @@ -135,7 +136,9 @@ final class DashSessionCoordinator: ObservableObject { navEntered = true state = .navigationReady startRouteHeartbeat() - log.append("Navigation control plane entered", category: "session") + startNavInfoHeartbeat() + startStatusHeartbeat() + log.append("Navigation control plane entered; route/nav/status keep-alives running", category: "session") } func beginProjectionHeartbeat() { @@ -159,9 +162,8 @@ final class DashSessionCoordinator: ObservableObject { func stopProjection() async { projectionHeartbeatTask?.cancel() - routeHeartbeatTask?.cancel() + cancelNavigationKeepAlives() projectionHeartbeatTask = nil - routeHeartbeatTask = nil guard navEntered else { return } state = .stopping @@ -181,10 +183,9 @@ final class DashSessionCoordinator: ObservableObject { func disconnect() { authTimeoutTask?.cancel() projectionHeartbeatTask?.cancel() - routeHeartbeatTask?.cancel() + cancelNavigationKeepAlives() authTimeoutTask = nil projectionHeartbeatTask = nil - routeHeartbeatTask = nil transport.stop() sequence = 0 @@ -320,6 +321,8 @@ final class DashSessionCoordinator: ObservableObject { try await transport.sendControl(patched) } + // MARK: - Navigation keep-alives + private func startRouteHeartbeat() { routeHeartbeatTask?.cancel() routeHeartbeatTask = Task { [weak self] in @@ -337,6 +340,80 @@ final class DashSessionCoordinator: ObservableObject { } } + /// 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 From 07e1100300ee1a6d429262ce8882331cc5742565 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:21:19 +0530 Subject: [PATCH 097/112] fix: bind dash control traffic to expected local UDP port --- RideDash/DashConnectivity/DashTransport.swift | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/RideDash/DashConnectivity/DashTransport.swift b/RideDash/DashConnectivity/DashTransport.swift index 9a1dea9..9f77539 100644 --- a/RideDash/DashConnectivity/DashTransport.swift +++ b/RideDash/DashConnectivity/DashTransport.swift @@ -66,10 +66,20 @@ final class DashTransport: ObservableObject { 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: .udp + using: controlParameters ) controlConnection = control control.stateUpdateHandler = { [weak self] newState in From ca722669797a5c5fd7591b07360f0306e6a9e08f Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:22:19 +0530 Subject: [PATCH 098/112] chore: remove duplicate scratch implementations --- RideDash/App/AppBuildInfo.swift | 5 - RideDash/App/AppLifecycleNotes.swift | 5 - RideDash/App/AppModel.swift | 64 ----- RideDash/App/FeatureFlags.swift | 6 - RideDash/App/ManualValidation.swift | 5 - RideDash/App/README_PLACEHOLDER.swift | 1 - .../DashDatagramTransport.swift | 149 ----------- RideDash/DashProtocol/ByteCursor.swift | 28 --- RideDash/DashProtocol/DERBuilder.swift | 27 -- .../DashAuthenticationPacketBuilder.swift | 31 --- .../DashAuthenticationResponseParser.swift | 43 ---- RideDash/DashProtocol/DashAuthenticator.swift | 80 ------ .../DashCompatibilityProfile.swift | 19 -- RideDash/DashProtocol/DashDatagram.swift | 33 --- RideDash/DashProtocol/DashInputDecoder.swift | 43 ---- RideDash/DashProtocol/DashPacketBuilder.swift | 41 ---- RideDash/DashProtocol/DashPacketTrace.swift | 21 -- .../DashProtocolCapabilities.swift | 12 - .../DashProtocolConfiguration.swift | 17 -- .../DashProtocol/DashProtocolConstants.swift | 20 -- RideDash/DashProtocol/DashProtocolError.swift | 23 -- .../DashProtocolLicenseNote.swift | 4 - .../DashProtocol/DashProtocolVersion.swift | 8 - .../DashProtocol/DashPublicKeyMaterial.swift | 8 - .../DashProtocol/DashSessionCommand.swift | 9 - .../DashProtocol/DashSessionCoordinator.swift | 188 -------------- RideDash/DashProtocol/DashSessionEvent.swift | 15 -- .../DashProtocol/DashSessionMetrics.swift | 17 -- RideDash/DashProtocol/DashSessionPolicy.swift | 10 - .../DashProtocol/DashSessionReducer.swift | 19 -- .../DashProtocol/DashSessionSnapshot.swift | 8 - RideDash/DashProtocol/DashSessionState.swift | 22 -- .../DashProtocol/DashSessionTimeline.swift | 8 - .../DashProtocol/DataIntegerEncoding.swift | 8 - RideDash/DashProtocol/HexCodec.swift | 43 ---- RideDash/DashProtocol/K1GCodec.swift | 44 ---- .../DashProtocol/NavigationInstruction.swift | 19 -- .../ProjectionControlPackets.swift | 35 --- .../ProtocolResearchWarning.swift | 5 - .../ProtocolSourceReference.swift | 5 - .../ProtocolValidationState.swift | 9 - RideDash/DashProtocol/RSAEncryptor.swift | 43 ---- RideDash/DashProtocol/RandomSessionKey.swift | 13 - RideDash/DashProtocol/RouteCard.swift | 13 - RideDash/DashProtocol/TLV.swift | 33 --- RideDash/Models/OwnershipModels.swift | 100 -------- RideDash/Models/Vehicle.swift | 33 --- RideDash/NavigationCore/LocationService.swift | 55 ----- .../NavigationCore/NavigationDeepLink.swift | 13 - .../NavigationCore/NavigationEngine.swift | 126 ---------- .../NavigationShareParser.swift | 21 -- RideDash/ProjectionCore/DashRenderer.swift | 232 ------------------ RideDash/ProjectionCore/H264Encoder.swift | 193 --------------- RideDash/ProjectionCore/H264NALUnit.swift | 16 -- .../ProjectionCore/ProjectionStreamer.swift | 103 -------- .../ProjectionCore/ProjectionUIState.swift | 25 -- RideDash/ProjectionCore/RTPPacketizer.swift | 108 -------- 57 files changed, 2284 deletions(-) delete mode 100644 RideDash/App/AppBuildInfo.swift delete mode 100644 RideDash/App/AppLifecycleNotes.swift delete mode 100644 RideDash/App/AppModel.swift delete mode 100644 RideDash/App/FeatureFlags.swift delete mode 100644 RideDash/App/ManualValidation.swift delete mode 100644 RideDash/App/README_PLACEHOLDER.swift delete mode 100644 RideDash/DashConnectivity/DashDatagramTransport.swift delete mode 100644 RideDash/DashProtocol/ByteCursor.swift delete mode 100644 RideDash/DashProtocol/DERBuilder.swift delete mode 100644 RideDash/DashProtocol/DashAuthenticationPacketBuilder.swift delete mode 100644 RideDash/DashProtocol/DashAuthenticationResponseParser.swift delete mode 100644 RideDash/DashProtocol/DashAuthenticator.swift delete mode 100644 RideDash/DashProtocol/DashCompatibilityProfile.swift delete mode 100644 RideDash/DashProtocol/DashDatagram.swift delete mode 100644 RideDash/DashProtocol/DashInputDecoder.swift delete mode 100644 RideDash/DashProtocol/DashPacketBuilder.swift delete mode 100644 RideDash/DashProtocol/DashPacketTrace.swift delete mode 100644 RideDash/DashProtocol/DashProtocolCapabilities.swift delete mode 100644 RideDash/DashProtocol/DashProtocolConfiguration.swift delete mode 100644 RideDash/DashProtocol/DashProtocolConstants.swift delete mode 100644 RideDash/DashProtocol/DashProtocolError.swift delete mode 100644 RideDash/DashProtocol/DashProtocolLicenseNote.swift delete mode 100644 RideDash/DashProtocol/DashProtocolVersion.swift delete mode 100644 RideDash/DashProtocol/DashPublicKeyMaterial.swift delete mode 100644 RideDash/DashProtocol/DashSessionCommand.swift delete mode 100644 RideDash/DashProtocol/DashSessionCoordinator.swift delete mode 100644 RideDash/DashProtocol/DashSessionEvent.swift delete mode 100644 RideDash/DashProtocol/DashSessionMetrics.swift delete mode 100644 RideDash/DashProtocol/DashSessionPolicy.swift delete mode 100644 RideDash/DashProtocol/DashSessionReducer.swift delete mode 100644 RideDash/DashProtocol/DashSessionSnapshot.swift delete mode 100644 RideDash/DashProtocol/DashSessionState.swift delete mode 100644 RideDash/DashProtocol/DashSessionTimeline.swift delete mode 100644 RideDash/DashProtocol/DataIntegerEncoding.swift delete mode 100644 RideDash/DashProtocol/HexCodec.swift delete mode 100644 RideDash/DashProtocol/K1GCodec.swift delete mode 100644 RideDash/DashProtocol/NavigationInstruction.swift delete mode 100644 RideDash/DashProtocol/ProjectionControlPackets.swift delete mode 100644 RideDash/DashProtocol/ProtocolResearchWarning.swift delete mode 100644 RideDash/DashProtocol/ProtocolSourceReference.swift delete mode 100644 RideDash/DashProtocol/ProtocolValidationState.swift delete mode 100644 RideDash/DashProtocol/RSAEncryptor.swift delete mode 100644 RideDash/DashProtocol/RandomSessionKey.swift delete mode 100644 RideDash/DashProtocol/RouteCard.swift delete mode 100644 RideDash/DashProtocol/TLV.swift delete mode 100644 RideDash/Models/OwnershipModels.swift delete mode 100644 RideDash/Models/Vehicle.swift delete mode 100644 RideDash/NavigationCore/LocationService.swift delete mode 100644 RideDash/NavigationCore/NavigationDeepLink.swift delete mode 100644 RideDash/NavigationCore/NavigationEngine.swift delete mode 100644 RideDash/NavigationCore/NavigationShareParser.swift delete mode 100644 RideDash/ProjectionCore/DashRenderer.swift delete mode 100644 RideDash/ProjectionCore/H264Encoder.swift delete mode 100644 RideDash/ProjectionCore/H264NALUnit.swift delete mode 100644 RideDash/ProjectionCore/ProjectionStreamer.swift delete mode 100644 RideDash/ProjectionCore/ProjectionUIState.swift delete mode 100644 RideDash/ProjectionCore/RTPPacketizer.swift diff --git a/RideDash/App/AppBuildInfo.swift b/RideDash/App/AppBuildInfo.swift deleted file mode 100644 index a445d97..0000000 --- a/RideDash/App/AppBuildInfo.swift +++ /dev/null @@ -1,5 +0,0 @@ -import Foundation - -struct AppBuildInfo { - static let implementationPhase = "full-manual-test" -} diff --git a/RideDash/App/AppLifecycleNotes.swift b/RideDash/App/AppLifecycleNotes.swift deleted file mode 100644 index 33afdc8..0000000 --- a/RideDash/App/AppLifecycleNotes.swift +++ /dev/null @@ -1,5 +0,0 @@ -import Foundation - -enum AppLifecycleNotes { - static let manualHardwareTesting = true -} diff --git a/RideDash/App/AppModel.swift b/RideDash/App/AppModel.swift deleted file mode 100644 index 0816ba8..0000000 --- a/RideDash/App/AppModel.swift +++ /dev/null @@ -1,64 +0,0 @@ -import Combine -import Foundation - -@MainActor -final class AppModel: ObservableObject { - let wiFiManager = TripperWiFiManager() - let locationService = LocationService() - let navigationEngine = NavigationEngine() - let dashSession = DashSessionCoordinator() - - @Published var dashSSID = "" - @Published var dashPassphrase = "" - @Published var destinationQuery = "" - - private var cancellables: Set = [] - - init() { - locationService.$location - .compactMap { $0 } - .sink { [weak self] location in - guard let self else { return } - self.navigationEngine.update(location: location) - self.dashSession.updateNavigation(self.navigationEngine.projectionState) - } - .store(in: &cancellables) - - navigationEngine.$projectionState - .sink { [weak self] state in - self?.dashSession.updateNavigation(state) - } - .store(in: &cancellables) - } - - func connectDash() async { - guard !dashSSID.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return } - do { - try await wiFiManager.join(ssid: dashSSID, passphrase: dashPassphrase) - dashPassphrase = "" - await dashSession.connect(ssid: dashSSID) - } catch { - dashPassphrase = "" - } - } - - func startProjection() async { - await dashSession.startProjection { [weak self] in - self?.navigationEngine.projectionState ?? .preview - } - } - - func stopProjection() async { - await dashSession.stopProjection() - } - - func planRoute() async { - guard let origin = locationService.location, - !destinationQuery.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return } - do { - try await navigationEngine.plan(destinationQuery: destinationQuery, from: origin) - } catch { - // NavigationEngine exposes its own state; UI can surface failure after manual validation. - } - } -} diff --git a/RideDash/App/FeatureFlags.swift b/RideDash/App/FeatureFlags.swift deleted file mode 100644 index 3a6288f..0000000 --- a/RideDash/App/FeatureFlags.swift +++ /dev/null @@ -1,6 +0,0 @@ -import Foundation - -enum FeatureFlags { - static let dashProjectionEnabled = true - static let manualHardwareValidation = true -} diff --git a/RideDash/App/ManualValidation.swift b/RideDash/App/ManualValidation.swift deleted file mode 100644 index dc87dc7..0000000 --- a/RideDash/App/ManualValidation.swift +++ /dev/null @@ -1,5 +0,0 @@ -import Foundation - -enum ManualValidation { - static let required = true -} diff --git a/RideDash/App/README_PLACEHOLDER.swift b/RideDash/App/README_PLACEHOLDER.swift deleted file mode 100644 index 7b09645..0000000 --- a/RideDash/App/README_PLACEHOLDER.swift +++ /dev/null @@ -1 +0,0 @@ -// Temporary source marker; application wiring is completed in RootView/App entry updates. diff --git a/RideDash/DashConnectivity/DashDatagramTransport.swift b/RideDash/DashConnectivity/DashDatagramTransport.swift deleted file mode 100644 index db03db3..0000000 --- a/RideDash/DashConnectivity/DashDatagramTransport.swift +++ /dev/null @@ -1,149 +0,0 @@ -import Foundation -import Network - -final class DashDatagramTransport: @unchecked Sendable { - let incomingPackets: AsyncStream - - private let queue = DispatchQueue(label: "dev.dagerott.RideDash.datagrams") - private var continuation: AsyncStream.Continuation? - private var listener: NWListener? - private var connections: [String: NWConnection] = [:] - private var configuration: DashProtocolConfiguration = .default - - init() { - var captured: AsyncStream.Continuation? - incomingPackets = AsyncStream { captured = $0 } - continuation = captured - } - - deinit { - stop() - continuation?.finish() - } - - func start(configuration: DashProtocolConfiguration) throws { - stop() - self.configuration = configuration - - guard let inputPort = NWEndpoint.Port(rawValue: configuration.inputPort) else { - throw DashTransportError.invalidPort - } - - let listener = try NWListener(using: .udp, on: inputPort) - listener.newConnectionHandler = { [weak self] connection in - guard let self else { return } - connection.start(queue: self.queue) - self.receiveNext(on: connection) - } - listener.start(queue: queue) - self.listener = listener - - // Pre-create the control channel. UDP send is still lazy and can queue while preparing. - _ = channel( - host: configuration.broadcastHost, - port: configuration.controlPort, - localPort: configuration.controlPort - ) - } - - func stop() { - listener?.cancel() - listener = nil - for connection in connections.values { connection.cancel() } - connections.removeAll() - } - - func sendControl(_ data: Data) async throws { - try await send( - data, - host: configuration.broadcastHost, - port: configuration.controlPort, - localPort: configuration.controlPort - ) - } - - func sendVideo(_ data: Data) async throws { - try await send( - data, - host: configuration.dashHost, - port: configuration.videoPort, - localPort: nil - ) - } - - func send( - _ data: Data, - host: String, - port: UInt16, - localPort: UInt16? = nil - ) async throws { - guard let remotePort = NWEndpoint.Port(rawValue: port) else { - throw DashTransportError.invalidPort - } - let connection = channel(host: host, port: port, localPort: localPort) - - try await withCheckedThrowingContinuation { (checked: CheckedContinuation) in - connection.send(content: data, completion: .contentProcessed { [weak self] error in - if let error { - checked.resume(throwing: error) - return - } - self?.continuation?.yield( - DashDatagram( - direction: .outbound, - host: host, - port: remotePort.rawValue, - payload: data - ) - ) - checked.resume() - }) - } - } - - private func channel(host: String, port: UInt16, localPort: UInt16?) -> NWConnection { - let key = "\(host):\(port):\(localPort ?? 0)" - if let existing = connections[key] { return existing } - - let parameters = NWParameters.udp - parameters.allowLocalEndpointReuse = true - if let localPort, let sourcePort = NWEndpoint.Port(rawValue: localPort) { - parameters.requiredLocalEndpoint = .hostPort( - host: NWEndpoint.Host("0.0.0.0"), - port: sourcePort - ) - } - - let connection = NWConnection( - host: NWEndpoint.Host(host), - port: NWEndpoint.Port(rawValue: port)!, - using: parameters - ) - connection.start(queue: queue) - connections[key] = connection - return connection - } - - private func receiveNext(on connection: NWConnection) { - connection.receiveMessage { [weak self] data, _, _, error in - guard let self else { return } - if let data, !data.isEmpty { - var host = "unknown" - var port: UInt16 = 0 - if case let .hostPort(remoteHost, remotePort) = connection.endpoint { - host = String(describing: remoteHost) - port = remotePort.rawValue - } - self.continuation?.yield( - DashDatagram( - direction: .inbound, - host: host, - port: port, - payload: data - ) - ) - } - if error == nil { self.receiveNext(on: connection) } - } - } -} diff --git a/RideDash/DashProtocol/ByteCursor.swift b/RideDash/DashProtocol/ByteCursor.swift deleted file mode 100644 index 9496b14..0000000 --- a/RideDash/DashProtocol/ByteCursor.swift +++ /dev/null @@ -1,28 +0,0 @@ -import Foundation - -struct ByteCursor { - private let bytes: [UInt8] - private(set) var offset: Int = 0 - - init(_ data: Data) { bytes = Array(data) } - - var remaining: Int { bytes.count - offset } - - mutating func readUInt8() -> UInt8? { - guard remaining >= 1 else { return nil } - defer { offset += 1 } - return bytes[offset] - } - - mutating func readUInt16BE() -> UInt16? { - guard remaining >= 2 else { return nil } - defer { offset += 2 } - return UInt16(bytes[offset]) << 8 | UInt16(bytes[offset + 1]) - } - - mutating func readData(count: Int) -> Data? { - guard count >= 0, remaining >= count else { return nil } - defer { offset += count } - return Data(bytes[offset..<(offset + count)]) - } -} diff --git a/RideDash/DashProtocol/DERBuilder.swift b/RideDash/DashProtocol/DERBuilder.swift deleted file mode 100644 index b35197d..0000000 --- a/RideDash/DashProtocol/DERBuilder.swift +++ /dev/null @@ -1,27 +0,0 @@ -import Foundation - -enum DERBuilder { - static func rsaPublicKey(modulus: Data, exponent: Data) -> Data { - let body = integer(modulus) + integer(exponent) - return Data([0x30]) + length(body.count) + body - } - - private static func integer(_ value: Data) -> Data { - var normalized = DataIntegerEncoding.stripLeadingZeroes(value) - if let first = normalized.first, first & 0x80 != 0 { - normalized.insert(0, at: normalized.startIndex) - } - return Data([0x02]) + length(normalized.count) + normalized - } - - private static func length(_ value: Int) -> Data { - if value < 0x80 { return Data([UInt8(value)]) } - var bytes: [UInt8] = [] - var remaining = value - while remaining > 0 { - bytes.insert(UInt8(remaining & 0xff), at: 0) - remaining >>= 8 - } - return Data([0x80 | UInt8(bytes.count)]) + Data(bytes) - } -} diff --git a/RideDash/DashProtocol/DashAuthenticationPacketBuilder.swift b/RideDash/DashProtocol/DashAuthenticationPacketBuilder.swift deleted file mode 100644 index 913fb0f..0000000 --- a/RideDash/DashProtocol/DashAuthenticationPacketBuilder.swift +++ /dev/null @@ -1,31 +0,0 @@ -import Foundation - -enum DashAuthenticationPacketBuilder { - static func makeEncryptedSessionPacket( - ssid: String, - sessionKey: Data, - modulus: Data, - exponent: Data - ) throws -> Data { - var plaintext = Data(ssid.utf8) - plaintext.append(sessionKey) - - let encrypted = try RSAEncryptor.encryptPKCS1( - plaintext: plaintext, - modulus: modulus, - exponent: exponent - ) - - // Public reference uses a 128-byte RSA ciphertext field for the known dash. - // Do not silently truncate if a different firmware/key size is encountered. - guard encrypted.count == 128 else { - throw DashProtocolError.invalidPacket( - "Expected 128-byte RSA ciphertext, got \(encrypted.count). Add a firmware capability profile before sending." - ) - } - - var packet = try HexCodec.data(from: DashProtocolConstants.authenticationPayloadPrefixHex) - packet.append(encrypted) - return packet - } -} diff --git a/RideDash/DashProtocol/DashAuthenticationResponseParser.swift b/RideDash/DashProtocol/DashAuthenticationResponseParser.swift deleted file mode 100644 index 8f2c4e6..0000000 --- a/RideDash/DashProtocol/DashAuthenticationResponseParser.swift +++ /dev/null @@ -1,43 +0,0 @@ -import Foundation - -enum DashAuthenticationResponseParser { - enum Event: Sendable { - case modulus(Data) - case exponent(Data) - case authenticated - case rejected - } - - /// Parses the public response markers documented by the interoperability reference. - /// The outer packet wrapper is intentionally tolerated; the marker is searched inside. - static func parse(_ data: Data) -> Event? { - let bytes = [UInt8](data) - guard bytes.count >= 3 else { return nil } - - // 07 01 01 => auth OK in the public reference. - if contains([0x07, 0x01, 0x01], in: bytes) { return .authenticated } - if contains([0x07, 0x01, 0x00], in: bytes) { return .rejected } - - // 07 00 and 07 03 . Capture bytes after the marker; - // hardware testing may refine wrapper-length stripping per firmware. - if let index = index(of: [0x07, 0x00], in: bytes), index + 2 < bytes.count { - return .modulus(Data(bytes[(index + 2)...])) - } - if let index = index(of: [0x07, 0x03], in: bytes), index + 2 < bytes.count { - return .exponent(Data(bytes[(index + 2)...])) - } - return nil - } - - private static func contains(_ needle: [UInt8], in haystack: [UInt8]) -> Bool { - index(of: needle, in: haystack) != nil - } - - private static func index(of 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 Array(haystack[i..<(i + needle.count)]) == needle { return i } - } - return nil - } -} diff --git a/RideDash/DashProtocol/DashAuthenticator.swift b/RideDash/DashProtocol/DashAuthenticator.swift deleted file mode 100644 index 5521d4f..0000000 --- a/RideDash/DashProtocol/DashAuthenticator.swift +++ /dev/null @@ -1,80 +0,0 @@ -import Foundation - -struct AuthenticatedDashSession: Sendable { - let establishedAt: Date - let sessionKey: Data -} - -struct DashAuthenticator: Sendable { - let timeout: TimeInterval - - init(timeout: TimeInterval = 8) { - self.timeout = timeout - } - - func authenticate( - ssid: String, - transport: DashDatagramTransport - ) async throws -> AuthenticatedDashSession { - try await withThrowingTaskGroup(of: AuthenticatedDashSession.self) { group in - group.addTask { - try await authenticateFlow(ssid: ssid, transport: transport) - } - group.addTask { - try await Task.sleep(for: .seconds(timeout)) - throw DashProtocolError.authenticationTimeout - } - - guard let first = try await group.next() else { - throw DashProtocolError.authenticationTimeout - } - group.cancelAll() - return first - } - } - - private func authenticateFlow( - ssid: String, - transport: DashDatagramTransport - ) async throws -> AuthenticatedDashSession { - let sessionKey = try RandomSessionKey.generate() - try await transport.sendControl(ProjectionControlPackets.authenticationRequest()) - - var keyMaterial = DashPublicKeyMaterial() - var encryptedKeySent = false - - for await datagram in transport.incomingPackets { - guard datagram.direction == .inbound, - let event = DashAuthenticationResponseParser.parse(datagram.payload) else { - continue - } - - switch event { - case .modulus(let modulus): - keyMaterial.modulus = modulus - case .exponent(let exponent): - keyMaterial.exponent = exponent - case .authenticated: - return AuthenticatedDashSession(establishedAt: .now, sessionKey: sessionKey) - case .rejected: - throw DashProtocolError.authenticationRejected - } - - if keyMaterial.isComplete, - !encryptedKeySent, - let modulus = keyMaterial.modulus, - let exponent = keyMaterial.exponent { - let packet = try DashAuthenticationPacketBuilder.makeEncryptedSessionPacket( - ssid: ssid, - sessionKey: sessionKey, - modulus: modulus, - exponent: exponent - ) - try await transport.sendControl(packet) - encryptedKeySent = true - } - } - - throw DashProtocolError.authenticationTimeout - } -} diff --git a/RideDash/DashProtocol/DashCompatibilityProfile.swift b/RideDash/DashProtocol/DashCompatibilityProfile.swift deleted file mode 100644 index 35b341a..0000000 --- a/RideDash/DashProtocol/DashCompatibilityProfile.swift +++ /dev/null @@ -1,19 +0,0 @@ -import Foundation - -struct DashCompatibilityProfile: Codable, Hashable, Identifiable, Sendable { - var id: String { "\(model)-\(firmware)" } - var model: String - var firmware: String - var configuration: DashProtocolConfiguration - var requiresButtonAck: Bool = true - var projectionHeartbeatHz: Double = 4 - var routeHeartbeatHz: Double = 1 - var navigationHeartbeatHz: Double = 1 - var statusHeartbeatHz: Double = 1 - - static let researchDefault = DashCompatibilityProfile( - model: "Generic compatible dash", - firmware: "unverified", - configuration: .default - ) -} diff --git a/RideDash/DashProtocol/DashDatagram.swift b/RideDash/DashProtocol/DashDatagram.swift deleted file mode 100644 index 602986b..0000000 --- a/RideDash/DashProtocol/DashDatagram.swift +++ /dev/null @@ -1,33 +0,0 @@ -import Foundation - -enum DashDatagramDirection: String, Codable, Sendable { - case inbound - case outbound -} - -struct DashDatagram: Identifiable, Hashable, Sendable { - let id: UUID - let timestamp: Date - let direction: DashDatagramDirection - let host: String - let port: UInt16 - let payload: Data - - init( - id: UUID = UUID(), - timestamp: Date = .now, - direction: DashDatagramDirection, - host: String, - port: UInt16, - payload: Data - ) { - self.id = id - self.timestamp = timestamp - self.direction = direction - self.host = host - self.port = port - self.payload = payload - } - - var hexPreview: String { HexCodec.string(from: payload, limit: 48) } -} diff --git a/RideDash/DashProtocol/DashInputDecoder.swift b/RideDash/DashProtocol/DashInputDecoder.swift deleted file mode 100644 index 710ffa1..0000000 --- a/RideDash/DashProtocol/DashInputDecoder.swift +++ /dev/null @@ -1,43 +0,0 @@ -import Foundation - -struct DashInputEvent: Identifiable, Sendable { - let id = UUID() - let action: DashInputAction - let rawCode: UInt8 - let payload: Data -} - -enum DashInputDecoder { - /// Public references show button events containing `09 00 00 01 XX`. - /// We intentionally search for that marker instead of assuming a fixed outer wrapper. - static func decode(_ data: Data) -> DashInputEvent? { - let bytes = [UInt8](data) - guard bytes.count >= 5 else { return nil } - - for index in 0...(bytes.count - 5) { - guard bytes[index] == 0x09, - bytes[index + 1] == 0x00, - bytes[index + 2] == 0x00, - bytes[index + 3] == 0x01 else { continue } - - let code = bytes[index + 4] - let action: DashInputAction - switch code { - case DashProtocolConstants.buttonRight: action = .right - case DashProtocolConstants.buttonLeft: action = .left - case DashProtocolConstants.buttonDown: action = .down - case DashProtocolConstants.buttonClick: action = .click - default: action = .unknown - } - return DashInputEvent(action: action, rawCode: code, payload: data) - } - return nil - } - - static func acknowledgement(for event: DashInputEvent) throws -> Data? { - guard event.action != .unknown else { return nil } - return try HexCodec.data( - from: DashProtocolConstants.buttonAckPrefixHex + String(format: "%02X", event.rawCode) - ) - } -} diff --git a/RideDash/DashProtocol/DashPacketBuilder.swift b/RideDash/DashProtocol/DashPacketBuilder.swift deleted file mode 100644 index dcb0d62..0000000 --- a/RideDash/DashProtocol/DashPacketBuilder.swift +++ /dev/null @@ -1,41 +0,0 @@ -import Foundation - -enum DashPacketBuilder { - /// Builds a conservative opaque route-card payload used by the session coordinator. - /// The public protocol's outer 0x007E route-card framing is firmware-sensitive; - /// manual hardware testing may refine this builder without touching navigation UI. - static func routeCard(_ card: RouteCard) -> Data { - var body = Data() - body.append(contentsOf: [0x00, 0x7E]) - let title = Data(card.title.utf8.prefix(48)) - body.append(UInt8(clamping: title.count)) - body.append(title) - let distance = UInt32(clamping: card.remainingDistanceMeters) - body.append(UInt8((distance >> 24) & 0xff)) - body.append(UInt8((distance >> 16) & 0xff)) - body.append(UInt8((distance >> 8) & 0xff)) - body.append(UInt8(distance & 0xff)) - body.append(card.projectionOn ? 1 : 0) - return body - } - - /// Local typed format. This is kept separate from the public K1G constants so - /// firmware validation can replace only this function when exact nav-info framing is confirmed. - static func navigationInfo(_ instruction: DashNavigationInstruction) -> Data { - var body = Data([0x4E, 0x41, 0x56, 0x01]) // NAV + local schema version - body.append(instruction.maneuver.rawValue) - appendUInt32(UInt32(clamping: instruction.distanceToTurnMeters), to: &body) - appendUInt32(UInt32(clamping: instruction.remainingDistanceMeters), to: &body) - let road = Data(instruction.roadName.utf8.prefix(48)) - body.append(UInt8(clamping: road.count)) - body.append(road) - return body - } - - private static func appendUInt32(_ value: UInt32, to data: inout Data) { - data.append(UInt8((value >> 24) & 0xff)) - data.append(UInt8((value >> 16) & 0xff)) - data.append(UInt8((value >> 8) & 0xff)) - data.append(UInt8(value & 0xff)) - } -} diff --git a/RideDash/DashProtocol/DashPacketTrace.swift b/RideDash/DashProtocol/DashPacketTrace.swift deleted file mode 100644 index 390ac42..0000000 --- a/RideDash/DashProtocol/DashPacketTrace.swift +++ /dev/null @@ -1,21 +0,0 @@ -import Foundation - -struct DashPacketTrace: Identifiable, Sendable { - let id: UUID - let timestamp: Date - let direction: DashDatagramDirection - let host: String - let port: UInt16 - let byteCount: Int - let hexPreview: String - - init(datagram: DashDatagram) { - id = datagram.id - timestamp = datagram.timestamp - direction = datagram.direction - host = datagram.host - port = datagram.port - byteCount = datagram.payload.count - hexPreview = datagram.hexPreview - } -} diff --git a/RideDash/DashProtocol/DashProtocolCapabilities.swift b/RideDash/DashProtocol/DashProtocolCapabilities.swift deleted file mode 100644 index 4fda450..0000000 --- a/RideDash/DashProtocol/DashProtocolCapabilities.swift +++ /dev/null @@ -1,12 +0,0 @@ -import Foundation - -struct DashProtocolCapabilities: Codable, Hashable, Sendable { - var supportsAuthentication = true - var supportsProjection = true - var supportsButtonInput = true - var supportsNavigationInfo = true - var supportsRouteCard = true - var supportsProjectionHeartbeat = true - - static let `default` = DashProtocolCapabilities() -} diff --git a/RideDash/DashProtocol/DashProtocolConfiguration.swift b/RideDash/DashProtocol/DashProtocolConfiguration.swift deleted file mode 100644 index 60e8393..0000000 --- a/RideDash/DashProtocol/DashProtocolConfiguration.swift +++ /dev/null @@ -1,17 +0,0 @@ -import Foundation - -struct DashProtocolConfiguration: Codable, Hashable, Sendable { - var dashHost: 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 projectionFPS: Double = 4 - var videoBitrate: Int = 240_000 - var routeTitle: String = "RideDash" - var hostname: String = "iPhone" - - static let `default` = DashProtocolConfiguration() -} diff --git a/RideDash/DashProtocol/DashProtocolConstants.swift b/RideDash/DashProtocol/DashProtocolConstants.swift deleted file mode 100644 index 53197f6..0000000 --- a/RideDash/DashProtocol/DashProtocolConstants.swift +++ /dev/null @@ -1,20 +0,0 @@ -import Foundation - -enum DashProtocolConstants { - // Public interoperability reference values. Keep centralized for firmware tuning. - static let requestAuthenticationHex = "0016000200000000020100054B314720000804000101" - static let navigationContextHex = "0016000200000000020100054B31472000052E00011E" - static let emptyNavigationListsHex = "002A000600000000020100054B31472000052F0001000530000100053100010005320001000533000100" - static let startNavigationHex = "0016000200000000020100054B31472000068000010B" - static let projectionFrameHex = "0016000200000000020100054B314720000556000155" - static let projectionOnHex = "0016000200000000020100054B314720000605000155" - static let projectionStopHex = "0016000200000000020100054B3147200005560001AA" - static let projectionOffHex = "0016000200000000020100054B3147200006050001AA" - static let authenticationPayloadPrefixHex = "0095000200000000020100054B3147200008000080" - - static let buttonRight: UInt8 = 0x13 - static let buttonLeft: UInt8 = 0x14 - static let buttonDown: UInt8 = 0x15 - static let buttonClick: UInt8 = 0x18 - static let buttonAckPrefixHex = "0016000200000000020100054B3147200006800001" -} diff --git a/RideDash/DashProtocol/DashProtocolError.swift b/RideDash/DashProtocol/DashProtocolError.swift deleted file mode 100644 index 3248f14..0000000 --- a/RideDash/DashProtocol/DashProtocolError.swift +++ /dev/null @@ -1,23 +0,0 @@ -import Foundation - -enum DashProtocolError: LocalizedError { - case transportNotReady - case authenticationTimeout - case missingPublicKey - case invalidPublicKey - case authenticationRejected - case invalidPacket(String) - case projectionNotReady - - var errorDescription: String? { - switch self { - case .transportNotReady: return "Dash transport is not ready." - case .authenticationTimeout: return "Dash authentication timed out." - case .missingPublicKey: return "Dash did not provide the required public-key material." - case .invalidPublicKey: return "Dash public-key material could not be imported." - case .authenticationRejected: return "Dash rejected the session authentication." - case .invalidPacket(let reason): return "Invalid dash packet: \(reason)" - case .projectionNotReady: return "Dash session is not ready for projection." - } - } -} diff --git a/RideDash/DashProtocol/DashProtocolLicenseNote.swift b/RideDash/DashProtocol/DashProtocolLicenseNote.swift deleted file mode 100644 index 6eb06f2..0000000 --- a/RideDash/DashProtocol/DashProtocolLicenseNote.swift +++ /dev/null @@ -1,4 +0,0 @@ -import Foundation - -/// No manufacturer-owned assets, private keys, certificates or firmware blobs are bundled. -enum DashProtocolLicenseNote {} diff --git a/RideDash/DashProtocol/DashProtocolVersion.swift b/RideDash/DashProtocol/DashProtocolVersion.swift deleted file mode 100644 index a44e0ee..0000000 --- a/RideDash/DashProtocol/DashProtocolVersion.swift +++ /dev/null @@ -1,8 +0,0 @@ -import Foundation - -struct DashProtocolVersion: Codable, Hashable, Sendable { - var firmware: String - var notes: String - - static let unknown = DashProtocolVersion(firmware: "unknown", notes: "Hardware validation pending") -} diff --git a/RideDash/DashProtocol/DashPublicKeyMaterial.swift b/RideDash/DashProtocol/DashPublicKeyMaterial.swift deleted file mode 100644 index 2bddd35..0000000 --- a/RideDash/DashProtocol/DashPublicKeyMaterial.swift +++ /dev/null @@ -1,8 +0,0 @@ -import Foundation - -struct DashPublicKeyMaterial: Sendable { - var modulus: Data? - var exponent: Data? - - var isComplete: Bool { modulus != nil && exponent != nil } -} diff --git a/RideDash/DashProtocol/DashSessionCommand.swift b/RideDash/DashProtocol/DashSessionCommand.swift deleted file mode 100644 index 76bb524..0000000 --- a/RideDash/DashProtocol/DashSessionCommand.swift +++ /dev/null @@ -1,9 +0,0 @@ -import Foundation - -enum DashSessionCommand: Sendable { - case requestAuthentication - case enterNavigation - case startProjection - case stopProjection - case acknowledgeInput(DashInputEvent) -} diff --git a/RideDash/DashProtocol/DashSessionCoordinator.swift b/RideDash/DashProtocol/DashSessionCoordinator.swift deleted file mode 100644 index e8d555a..0000000 --- a/RideDash/DashProtocol/DashSessionCoordinator.swift +++ /dev/null @@ -1,188 +0,0 @@ -import Combine -import Foundation - -@MainActor -final class DashSessionCoordinator: ObservableObject { - @Published private(set) var state: DashSessionState = .disconnected - @Published private(set) var timeline: [DashSessionTimelineEntry] = [] - @Published private(set) var lastError: String? - @Published private(set) var lastInput: DashInputAction? - @Published private(set) var metrics = DashSessionMetrics() - - let transport: DashDatagramTransport - let configuration: DashProtocolConfiguration - let streamer: ProjectionStreamer - - private let policy: DashSessionPolicy - private let authenticator: DashAuthenticator - private var inputTask: Task? - private var heartbeatTask: Task? - private var routeCard = RouteCard(title: "RideDash") - private var navigationInstruction = DashNavigationInstruction( - maneuver: .continueStraight, - distanceToTurnMeters: 0, - remainingDistanceMeters: 0, - roadName: "Ready" - ) - - init( - configuration: DashProtocolConfiguration = .default, - policy: DashSessionPolicy = .init() - ) { - self.configuration = configuration - self.policy = policy - transport = DashDatagramTransport() - authenticator = DashAuthenticator(timeout: policy.authenticationTimeout) - streamer = ProjectionStreamer(transport: transport, configuration: configuration) - } - - func connect(ssid: String) async { - await disconnect() - do { - transition(.transportReady, "Starting UDP control/input transport") - try transport.start(configuration: configuration) - metrics.connectedAt = .now - - transition(.authenticating, "Requesting dash session authentication") - _ = try await authenticator.authenticate(ssid: ssid, transport: transport) - metrics.authenticatedAt = .now - transition(.authenticated, "Session authentication accepted") - - startInputLoop() - try await enterNavigationMode() - transition(.navigationReady, "Dash navigation control plane initialized") - } catch { - fail(error) - } - } - - func startProjection(stateProvider: @escaping () -> ProjectionUIState) async { - guard state == .navigationReady || state == .projecting else { - fail(DashProtocolError.projectionNotReady) - return - } - do { - try await sendProjectionOnSequence() - try streamer.start(stateProvider: stateProvider) - metrics.projectionStartedAt = .now - transition(.projecting, "H.264/RTP projection started") - startHeartbeatLoop() - } catch { - fail(error) - } - } - - func updateNavigation(_ state: ProjectionUIState) { - routeCard = RouteCard( - title: state.roadName.isEmpty ? configuration.routeTitle : state.roadName, - remainingDistanceMeters: state.remainingDistanceMeters, - projectionOn: true - ) - navigationInstruction = DashNavigationInstruction( - maneuver: state.maneuver, - distanceToTurnMeters: state.distanceToTurnMeters, - remainingDistanceMeters: state.remainingDistanceMeters, - roadName: state.roadName - ) - } - - func stopProjection() async { - heartbeatTask?.cancel() - heartbeatTask = nil - streamer.stop() - do { - try await transport.sendControl(ProjectionControlPackets.projectionStop()) - try await transport.sendControl(ProjectionControlPackets.projectionOff()) - } catch { - lastError = error.localizedDescription - } - if state == .projecting { transition(.navigationReady, "Projection stopped") } - } - - func disconnect() async { - if state == .projecting || state == .navigationReady { - await stopProjection() - } - inputTask?.cancel() - inputTask = nil - heartbeatTask?.cancel() - heartbeatTask = nil - transport.stop() - metrics = DashSessionMetrics() - transition(.disconnected, "Session disconnected") - } - - private func enterNavigationMode() async throws { - try await transport.sendControl(ProjectionControlPackets.navigationContext()) - try await transport.sendControl(ProjectionControlPackets.emptyNavigationLists()) - // Route/nav payload builders are intentionally isolated because their inner layout - // is the most firmware-sensitive part of the public interoperability research. - try await transport.sendControl(DashPacketBuilder.routeCard(routeCard)) - try await transport.sendControl(ProjectionControlPackets.projectionFrame()) - try await transport.sendControl(ProjectionControlPackets.projectionOn()) - try await transport.sendControl(ProjectionControlPackets.startNavigation()) - } - - private func sendProjectionOnSequence() async throws { - try await transport.sendControl(ProjectionControlPackets.projectionFrame()) - try await transport.sendControl(ProjectionControlPackets.projectionOn()) - try await transport.sendControl(ProjectionControlPackets.startNavigation()) - } - - private func startInputLoop() { - inputTask?.cancel() - inputTask = Task { [weak self] in - guard let self else { return } - for await datagram in self.transport.incomingPackets { - guard !Task.isCancelled else { break } - self.metrics.inboundPackets += datagram.direction == .inbound ? 1 : 0 - self.metrics.outboundPackets += datagram.direction == .outbound ? 1 : 0 - guard datagram.direction == .inbound, - let event = DashInputDecoder.decode(datagram.payload) else { continue } - self.lastInput = event.action - self.timeline.append( - DashSessionTimelineEntry(state: self.state, message: "Dash input: \(event.action.rawValue)") - ) - if let ack = try? DashInputDecoder.acknowledgement(for: event) { - try? await self.transport.sendControl(ack) - } - } - } - } - - private func startHeartbeatLoop() { - heartbeatTask?.cancel() - heartbeatTask = Task { [weak self] in - guard let self else { return } - var projectionTick = 0 - while !Task.isCancelled, self.state == .projecting { - do { - try await self.transport.sendControl(ProjectionControlPackets.projectionFrame()) - projectionTick += 1 - - let ticksPerSecond = max(1, Int(self.policy.projectionHeartbeatHz.rounded())) - if projectionTick.isMultiple(of: ticksPerSecond) { - try await self.transport.sendControl(DashPacketBuilder.routeCard(self.routeCard)) - try await self.transport.sendControl(DashPacketBuilder.navigationInfo(self.navigationInstruction)) - } - } catch { - self.lastError = error.localizedDescription - } - - let hz = max(1, self.policy.projectionHeartbeatHz) - try? await Task.sleep(for: .seconds(1.0 / hz)) - } - } - } - - private func transition(_ newState: DashSessionState, _ message: String) { - state = newState - timeline.append(DashSessionTimelineEntry(state: newState, message: message)) - if timeline.count > 200 { timeline.removeFirst(timeline.count - 200) } - } - - private func fail(_ error: Error) { - lastError = error.localizedDescription - transition(.failed, error.localizedDescription) - } -} diff --git a/RideDash/DashProtocol/DashSessionEvent.swift b/RideDash/DashProtocol/DashSessionEvent.swift deleted file mode 100644 index 697923f..0000000 --- a/RideDash/DashProtocol/DashSessionEvent.swift +++ /dev/null @@ -1,15 +0,0 @@ -import Foundation - -enum DashSessionEvent: Sendable { - case wifiJoinRequested - case networkSatisfied - case transportReady - case authenticationStarted - case authenticationSucceeded - case authenticationFailed(String) - case navigationReady - case projectionStarted - case projectionStopped - case input(DashInputAction) - case transportLost(String) -} diff --git a/RideDash/DashProtocol/DashSessionMetrics.swift b/RideDash/DashProtocol/DashSessionMetrics.swift deleted file mode 100644 index d0ba693..0000000 --- a/RideDash/DashProtocol/DashSessionMetrics.swift +++ /dev/null @@ -1,17 +0,0 @@ -import Foundation - -struct DashSessionMetrics: Sendable { - var connectedAt: Date? - var authenticatedAt: Date? - var projectionStartedAt: Date? - var inboundPackets: Int = 0 - var outboundPackets: Int = 0 - var videoPackets: Int = 0 - var encodedFrames: Int = 0 - var reconnectAttempts: Int = 0 - - var projectionDuration: TimeInterval { - guard let projectionStartedAt else { return 0 } - return Date().timeIntervalSince(projectionStartedAt) - } -} diff --git a/RideDash/DashProtocol/DashSessionPolicy.swift b/RideDash/DashProtocol/DashSessionPolicy.swift deleted file mode 100644 index 6eb8d3a..0000000 --- a/RideDash/DashProtocol/DashSessionPolicy.swift +++ /dev/null @@ -1,10 +0,0 @@ -import Foundation - -struct DashSessionPolicy: Sendable { - var authenticationTimeout: TimeInterval = 8 - var reconnectDelay: TimeInterval = 2 - var maximumReconnectAttempts: Int = 5 - var projectionHeartbeatHz: Double = 4 - var routeHeartbeatHz: Double = 1 - var navInfoHeartbeatHz: Double = 1 -} diff --git a/RideDash/DashProtocol/DashSessionReducer.swift b/RideDash/DashProtocol/DashSessionReducer.swift deleted file mode 100644 index ee6476b..0000000 --- a/RideDash/DashProtocol/DashSessionReducer.swift +++ /dev/null @@ -1,19 +0,0 @@ -import Foundation - -enum DashSessionReducer { - static func reduce(state: DashSessionState, event: DashSessionEvent) -> DashSessionState { - switch event { - case .wifiJoinRequested: return .joiningWiFi - case .networkSatisfied: return .networkReady - case .transportReady: return .transportReady - case .authenticationStarted: return .authenticating - case .authenticationSucceeded: return .authenticated - case .authenticationFailed: return .failed - case .navigationReady: return .navigationReady - case .projectionStarted: return .projecting - case .projectionStopped: return .navigationReady - case .input: return state - case .transportLost: return .recovering - } - } -} diff --git a/RideDash/DashProtocol/DashSessionSnapshot.swift b/RideDash/DashProtocol/DashSessionSnapshot.swift deleted file mode 100644 index 5075778..0000000 --- a/RideDash/DashProtocol/DashSessionSnapshot.swift +++ /dev/null @@ -1,8 +0,0 @@ -import Foundation - -struct DashSessionSnapshot: Sendable { - var state: DashSessionState - var lastError: String? - var metrics: DashSessionMetrics - var compatibility: DashCompatibilityProfile -} diff --git a/RideDash/DashProtocol/DashSessionState.swift b/RideDash/DashProtocol/DashSessionState.swift deleted file mode 100644 index 754a423..0000000 --- a/RideDash/DashProtocol/DashSessionState.swift +++ /dev/null @@ -1,22 +0,0 @@ -import Foundation - -enum DashSessionState: String, Codable, CaseIterable, Sendable { - case disconnected - case joiningWiFi - case networkReady - case transportReady - case authenticating - case authenticated - case navigationReady - case projecting - case recovering - case failed -} - -enum DashInputAction: String, Codable, Sendable { - case right - case left - case down - case click - case unknown -} diff --git a/RideDash/DashProtocol/DashSessionTimeline.swift b/RideDash/DashProtocol/DashSessionTimeline.swift deleted file mode 100644 index 247f45d..0000000 --- a/RideDash/DashProtocol/DashSessionTimeline.swift +++ /dev/null @@ -1,8 +0,0 @@ -import Foundation - -struct DashSessionTimelineEntry: Identifiable, Sendable { - let id = UUID() - let timestamp = Date() - let state: DashSessionState - let message: String -} diff --git a/RideDash/DashProtocol/DataIntegerEncoding.swift b/RideDash/DashProtocol/DataIntegerEncoding.swift deleted file mode 100644 index 62dc3e6..0000000 --- a/RideDash/DashProtocol/DataIntegerEncoding.swift +++ /dev/null @@ -1,8 +0,0 @@ -import Foundation - -enum DataIntegerEncoding { - static func stripLeadingZeroes(_ data: Data) -> Data { - let bytes = data.drop { $0 == 0 } - return bytes.isEmpty ? Data([0]) : Data(bytes) - } -} diff --git a/RideDash/DashProtocol/HexCodec.swift b/RideDash/DashProtocol/HexCodec.swift deleted file mode 100644 index 7e673f4..0000000 --- a/RideDash/DashProtocol/HexCodec.swift +++ /dev/null @@ -1,43 +0,0 @@ -import Foundation - -enum HexCodecError: LocalizedError { - case oddLength - case invalidByte(String) - - var errorDescription: String? { - switch self { - case .oddLength: return "Hex string must contain an even number of digits." - case .invalidByte(let value): return "Invalid hex byte: \(value)" - } - } -} - -enum HexCodec { - static func data(from string: String) throws -> Data { - let cleaned = string - .replacingOccurrences(of: " ", with: "") - .replacingOccurrences(of: "\n", with: "") - .replacingOccurrences(of: "\t", with: "") - guard cleaned.count.isMultiple(of: 2) else { throw HexCodecError.oddLength } - - var result = Data() - var index = cleaned.startIndex - while index < cleaned.endIndex { - let next = cleaned.index(index, offsetBy: 2) - let byteString = String(cleaned[index.. String { - let bytes = limit.map { data.prefix($0) } ?? data[...] - let value = bytes.map { String(format: "%02X", $0) }.joined(separator: " ") - if let limit, data.count > limit { return value + " …" } - return value - } -} diff --git a/RideDash/DashProtocol/K1GCodec.swift b/RideDash/DashProtocol/K1GCodec.swift deleted file mode 100644 index d6216ac..0000000 --- a/RideDash/DashProtocol/K1GCodec.swift +++ /dev/null @@ -1,44 +0,0 @@ -import Foundation - -/// Minimal, defensive framing helpers for the public K1G/TLV-shaped packets. -/// The protocol is intentionally represented as raw typed envelopes until hardware validation. -struct K1GPacket: Hashable, Sendable { - let raw: Data - - var declaredLength: Int? { - guard raw.count >= 2 else { return nil } - return Int(raw[0]) << 8 | Int(raw[1]) - } - - var payload: Data { - guard raw.count > 2 else { return Data() } - return raw.dropFirst(2) - } - - var isLengthPlausible: Bool { - guard let declaredLength else { return false } - // Public captures use an outer two-byte length. Some firmware wrappers may - // count slightly differently, so keep decoding tolerant but never unsafe. - return declaredLength <= raw.count + 4 && declaredLength >= 0 - } -} - -enum K1GCodec { - static func decode(_ data: Data) -> K1GPacket? { - guard data.count >= 2 else { return nil } - return K1GPacket(raw: data) - } - - static func knownControlPacket(hex: String) throws -> K1GPacket { - K1GPacket(raw: try HexCodec.data(from: hex)) - } - - static func contains(_ bytes: [UInt8], in data: Data) -> Bool { - guard !bytes.isEmpty, data.count >= bytes.count else { return false } - let raw = [UInt8](data) - for i in 0...(raw.count - bytes.count) { - if Array(raw[i..<(i + bytes.count)]) == bytes { return true } - } - return false - } -} diff --git a/RideDash/DashProtocol/NavigationInstruction.swift b/RideDash/DashProtocol/NavigationInstruction.swift deleted file mode 100644 index c33a1aa..0000000 --- a/RideDash/DashProtocol/NavigationInstruction.swift +++ /dev/null @@ -1,19 +0,0 @@ -import Foundation - -enum NavigationManeuver: UInt8, Codable, Sendable { - case continueStraight = 0 - case turnLeft = 1 - case turnRight = 2 - case slightLeft = 3 - case slightRight = 4 - case uTurn = 5 - case roundabout = 6 - case arrive = 7 -} - -struct DashNavigationInstruction: Sendable { - var maneuver: NavigationManeuver - var distanceToTurnMeters: Int - var remainingDistanceMeters: Int - var roadName: String -} diff --git a/RideDash/DashProtocol/ProjectionControlPackets.swift b/RideDash/DashProtocol/ProjectionControlPackets.swift deleted file mode 100644 index 6fdac28..0000000 --- a/RideDash/DashProtocol/ProjectionControlPackets.swift +++ /dev/null @@ -1,35 +0,0 @@ -import Foundation - -enum ProjectionControlPackets { - static func authenticationRequest() throws -> Data { - try HexCodec.data(from: DashProtocolConstants.requestAuthenticationHex) - } - - static func navigationContext() throws -> Data { - try HexCodec.data(from: DashProtocolConstants.navigationContextHex) - } - - static func emptyNavigationLists() throws -> Data { - try HexCodec.data(from: DashProtocolConstants.emptyNavigationListsHex) - } - - static func startNavigation() throws -> Data { - try HexCodec.data(from: DashProtocolConstants.startNavigationHex) - } - - static func projectionFrame() throws -> Data { - try HexCodec.data(from: DashProtocolConstants.projectionFrameHex) - } - - static func projectionOn() throws -> Data { - try HexCodec.data(from: DashProtocolConstants.projectionOnHex) - } - - static func projectionStop() throws -> Data { - try HexCodec.data(from: DashProtocolConstants.projectionStopHex) - } - - static func projectionOff() throws -> Data { - try HexCodec.data(from: DashProtocolConstants.projectionOffHex) - } -} diff --git a/RideDash/DashProtocol/ProtocolResearchWarning.swift b/RideDash/DashProtocol/ProtocolResearchWarning.swift deleted file mode 100644 index 8106e0c..0000000 --- a/RideDash/DashProtocol/ProtocolResearchWarning.swift +++ /dev/null @@ -1,5 +0,0 @@ -import Foundation - -enum ProtocolResearchWarning { - static let packetBuilders = "Route/nav-info packet builders are intentionally isolated. Validate exact firmware framing on owned hardware before riding." -} diff --git a/RideDash/DashProtocol/ProtocolSourceReference.swift b/RideDash/DashProtocol/ProtocolSourceReference.swift deleted file mode 100644 index b84d812..0000000 --- a/RideDash/DashProtocol/ProtocolSourceReference.swift +++ /dev/null @@ -1,5 +0,0 @@ -import Foundation - -enum ProtocolSourceReference { - static let betterDashRepository = "https://github.com/OpenMotoDash/better-dash" -} diff --git a/RideDash/DashProtocol/ProtocolValidationState.swift b/RideDash/DashProtocol/ProtocolValidationState.swift deleted file mode 100644 index 8ace10d..0000000 --- a/RideDash/DashProtocol/ProtocolValidationState.swift +++ /dev/null @@ -1,9 +0,0 @@ -import Foundation - -struct ProtocolValidationState: Codable, Sendable { - var authenticationValidated = false - var routeCardValidated = false - var navigationInfoValidated = false - var videoValidated = false - var inputValidated = false -} diff --git a/RideDash/DashProtocol/RSAEncryptor.swift b/RideDash/DashProtocol/RSAEncryptor.swift deleted file mode 100644 index af21366..0000000 --- a/RideDash/DashProtocol/RSAEncryptor.swift +++ /dev/null @@ -1,43 +0,0 @@ -import Foundation -import Security - -enum RSAEncryptor { - static func encryptPKCS1( - plaintext: Data, - modulus: Data, - exponent: Data - ) throws -> Data { - let der = DERBuilder.rsaPublicKey(modulus: modulus, exponent: exponent) - let attributes: [CFString: Any] = [ - kSecAttrKeyType: kSecAttrKeyTypeRSA, - kSecAttrKeyClass: kSecAttrKeyClassPublic, - kSecAttrKeySizeInBits: modulus.count * 8 - ] - - var importError: Unmanaged? - guard let key = SecKeyCreateWithData( - der as CFData, - attributes as CFDictionary, - &importError - ) else { - throw importError?.takeRetainedValue() ?? DashProtocolError.invalidPublicKey as CFError - } - - let algorithm = SecKeyAlgorithm.rsaEncryptionPKCS1 - guard SecKeyIsAlgorithmSupported(key, .encrypt, algorithm) else { - throw DashProtocolError.invalidPublicKey - } - - var encryptionError: Unmanaged? - guard let encrypted = SecKeyCreateEncryptedData( - key, - algorithm, - plaintext as CFData, - &encryptionError - ) else { - if let error = encryptionError?.takeRetainedValue() { throw error } - throw DashProtocolError.invalidPublicKey - } - return encrypted as Data - } -} diff --git a/RideDash/DashProtocol/RandomSessionKey.swift b/RideDash/DashProtocol/RandomSessionKey.swift deleted file mode 100644 index 175f824..0000000 --- a/RideDash/DashProtocol/RandomSessionKey.swift +++ /dev/null @@ -1,13 +0,0 @@ -import Foundation -import Security - -enum RandomSessionKey { - static func generate(length: Int = 16) throws -> Data { - var bytes = [UInt8](repeating: 0, count: length) - let status = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) - guard status == errSecSuccess else { - throw NSError(domain: NSOSStatusErrorDomain, code: Int(status)) - } - return Data(bytes) - } -} diff --git a/RideDash/DashProtocol/RouteCard.swift b/RideDash/DashProtocol/RouteCard.swift deleted file mode 100644 index 1c29d69..0000000 --- a/RideDash/DashProtocol/RouteCard.swift +++ /dev/null @@ -1,13 +0,0 @@ -import Foundation - -struct RouteCard: Sendable { - var title: String - var remainingDistanceMeters: Int - var projectionOn: Bool - - init(title: String, remainingDistanceMeters: Int = 0, projectionOn: Bool = true) { - self.title = title - self.remainingDistanceMeters = remainingDistanceMeters - self.projectionOn = projectionOn - } -} diff --git a/RideDash/DashProtocol/TLV.swift b/RideDash/DashProtocol/TLV.swift deleted file mode 100644 index f4c5bee..0000000 --- a/RideDash/DashProtocol/TLV.swift +++ /dev/null @@ -1,33 +0,0 @@ -import Foundation - -struct TLV: Hashable, Sendable { - let type: UInt16 - let value: Data -} - -enum TLVCodec { - /// Generic two-byte type + two-byte big-endian length helper for local fixtures. - /// Hardware-specific outer framing remains in K1GCodec. - static func encode(_ tlv: TLV) -> Data { - var result = Data() - result.append(UInt8((tlv.type >> 8) & 0xff)) - result.append(UInt8(tlv.type & 0xff)) - let length = UInt16(clamping: tlv.value.count) - result.append(UInt8((length >> 8) & 0xff)) - result.append(UInt8(length & 0xff)) - result.append(tlv.value) - return result - } - - static func decodeMany(_ data: Data) -> [TLV] { - var cursor = ByteCursor(data) - var result: [TLV] = [] - while cursor.remaining >= 4 { - guard let type = cursor.readUInt16BE(), - let length = cursor.readUInt16BE(), - let value = cursor.readData(count: Int(length)) else { break } - result.append(TLV(type: type, value: value)) - } - return result - } -} diff --git a/RideDash/Models/OwnershipModels.swift b/RideDash/Models/OwnershipModels.swift deleted file mode 100644 index 1b04965..0000000 --- a/RideDash/Models/OwnershipModels.swift +++ /dev/null @@ -1,100 +0,0 @@ -import Foundation -import SwiftData - -enum ExpenseCategory: String, CaseIterable, Codable, Identifiable { - case fuel, service, repair, accessory, gear, food, stay, transport, 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 note: String - - var category: ExpenseCategory { - get { ExpenseCategory(rawValue: categoryRaw) ?? .other } - set { categoryRaw = newValue.rawValue } - } - - init(date: Date = .now, category: ExpenseCategory, amount: Double, odometerKM: Double? = nil, note: String = "") { - id = UUID() - self.date = date - categoryRaw = category.rawValue - self.amount = amount - self.odometerKM = odometerKM - self.note = note - } -} - -enum MaintenanceKind: String, CaseIterable, Codable, Identifiable { - case service, chainClean, chainLube, tyre, brake, accessory, other - var id: String { rawValue } -} - -@Model -final class MaintenanceEntry { - var id: UUID - var date: Date - var kindRaw: String - var odometerKM: Double - var note: 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, note: String = "", nextDueKM: Double? = nil, nextDueDate: Date? = nil) { - id = UUID() - self.date = date - kindRaw = kind.rawValue - self.odometerKM = odometerKM - self.note = note - 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 isFullTank: Bool - - init(date: Date = .now, odometerKM: Double, litres: Double, totalCost: Double, isFullTank: Bool) { - id = UUID() - self.date = date - self.odometerKM = odometerKM - self.litres = litres - self.totalCost = totalCost - self.isFullTank = isFullTank - } -} - -@Model -final class RideRecord { - var id: UUID - var startedAt: Date - var endedAt: Date? - var destination: String - var distanceKM: Double - var note: String - - init(startedAt: Date = .now, endedAt: Date? = nil, destination: String = "", distanceKM: Double = 0, note: String = "") { - id = UUID() - self.startedAt = startedAt - self.endedAt = endedAt - self.destination = destination - self.distanceKM = distanceKM - self.note = note - } -} diff --git a/RideDash/Models/Vehicle.swift b/RideDash/Models/Vehicle.swift deleted file mode 100644 index 297d1b9..0000000 --- a/RideDash/Models/Vehicle.swift +++ /dev/null @@ -1,33 +0,0 @@ -import Foundation -import SwiftData - -@Model -final class Vehicle { - var id: UUID - var name: String - var registrationNumber: String - var odometerKM: Double - var insuranceExpiry: Date? - var pollutionCertificateExpiry: Date? - var lastServiceDate: Date? - var isActive: Bool - - init( - name: String, - registrationNumber: String = "", - odometerKM: Double = 0, - insuranceExpiry: Date? = nil, - pollutionCertificateExpiry: Date? = nil, - lastServiceDate: Date? = nil, - isActive: Bool = false - ) { - id = UUID() - self.name = name - self.registrationNumber = registrationNumber - self.odometerKM = odometerKM - self.insuranceExpiry = insuranceExpiry - self.pollutionCertificateExpiry = pollutionCertificateExpiry - self.lastServiceDate = lastServiceDate - self.isActive = isActive - } -} diff --git a/RideDash/NavigationCore/LocationService.swift b/RideDash/NavigationCore/LocationService.swift deleted file mode 100644 index ee03185..0000000 --- a/RideDash/NavigationCore/LocationService.swift +++ /dev/null @@ -1,55 +0,0 @@ -import Combine -import CoreLocation -import Foundation - -@MainActor -final class LocationService: NSObject, ObservableObject, CLLocationManagerDelegate { - @Published private(set) var location: CLLocation? - @Published private(set) var heading: CLHeading? - @Published private(set) var authorizationStatus: CLAuthorizationStatus - @Published private(set) var lastError: String? - - private let manager = CLLocationManager() - - override init() { - authorizationStatus = manager.authorizationStatus - super.init() - manager.delegate = self - manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation - manager.distanceFilter = 2 - manager.activityType = .automotiveNavigation - manager.pausesLocationUpdatesAutomatically = true - } - - func requestPermission() { - manager.requestWhenInUseAuthorization() - } - - func startNavigationUpdates() { - manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation - manager.startUpdatingLocation() - manager.startUpdatingHeading() - } - - func stopNavigationUpdates() { - manager.stopUpdatingLocation() - manager.stopUpdatingHeading() - } - - func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) { - authorizationStatus = manager.authorizationStatus - } - - func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { - guard let latest = locations.last else { return } - location = latest - } - - func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) { - heading = newHeading - } - - func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { - lastError = error.localizedDescription - } -} diff --git a/RideDash/NavigationCore/NavigationDeepLink.swift b/RideDash/NavigationCore/NavigationDeepLink.swift deleted file mode 100644 index e9cac0f..0000000 --- a/RideDash/NavigationCore/NavigationDeepLink.swift +++ /dev/null @@ -1,13 +0,0 @@ -import Foundation - -enum NavigationDeepLink { - static func destination(from url: URL) -> SharedDestination? { - guard url.scheme?.lowercased() == "ridedash" else { return nil } - let components = URLComponents(url: url, resolvingAgainstBaseURL: false) - if url.host == "route", - let value = components?.queryItems?.first(where: { $0.name == "q" || $0.name == "url" })?.value { - return NavigationShareParser.parse(value) - } - return nil - } -} diff --git a/RideDash/NavigationCore/NavigationEngine.swift b/RideDash/NavigationCore/NavigationEngine.swift deleted file mode 100644 index 8a96c63..0000000 --- a/RideDash/NavigationCore/NavigationEngine.swift +++ /dev/null @@ -1,126 +0,0 @@ -import Combine -import CoreLocation -import Foundation -import MapKit - -@MainActor -final class NavigationEngine: ObservableObject { - @Published private(set) var route: MKRoute? - @Published private(set) var destination: MKMapItem? - @Published private(set) var projectionState: ProjectionUIState = .init() - @Published private(set) var isCalculating = false - @Published private(set) var lastError: String? - - private var stepIndex = 0 - - func plan(destinationQuery: String, from origin: CLLocation) async throws { - isCalculating = true - defer { isCalculating = false } - - let searchRequest = MKLocalSearch.Request() - searchRequest.naturalLanguageQuery = destinationQuery - searchRequest.region = MKCoordinateRegion( - center: origin.coordinate, - latitudinalMeters: 100_000, - longitudinalMeters: 100_000 - ) - let searchResponse = try await MKLocalSearch(request: searchRequest).start() - guard let item = searchResponse.mapItems.first else { - throw NavigationEngineError.destinationNotFound - } - - let request = MKDirections.Request() - request.source = MKMapItem(placemark: MKPlacemark(coordinate: origin.coordinate)) - request.destination = item - request.transportType = .automobile - request.requestsAlternateRoutes = false - - let response = try await MKDirections(request: request).calculate() - guard let route = response.routes.first else { - throw NavigationEngineError.routeUnavailable - } - - self.destination = item - self.route = route - stepIndex = firstUsefulStep(in: route.steps) - update(location: origin) - } - - func clearRoute() { - route = nil - destination = nil - stepIndex = 0 - projectionState = .init() - } - - func update(location: CLLocation) { - guard let route else { - projectionState.speedKPH = max(0, location.speed * 3.6) - projectionState.gpsAccuracyMeters = max(0, location.horizontalAccuracy) - return - } - - let steps = route.steps - guard !steps.isEmpty else { return } - stepIndex = min(max(0, stepIndex), steps.count - 1) - - var step = steps[stepIndex] - var distanceToTurn = distance(from: location, toEndOf: step) - if distanceToTurn < 30, stepIndex + 1 < steps.count { - stepIndex += 1 - step = steps[stepIndex] - distanceToTurn = distance(from: location, toEndOf: step) - } - - let laterDistance = steps.dropFirst(stepIndex + 1).reduce(0) { $0 + $1.distance } - let remaining = max(0, distanceToTurn + laterDistance) - let remainingRatio = route.distance > 0 ? remaining / route.distance : 0 - let eta = Date().addingTimeInterval(max(0, route.expectedTravelTime * remainingRatio)) - - projectionState = ProjectionUIState( - maneuver: maneuver(from: step.instructions), - distanceToTurnMeters: Int(distanceToTurn.rounded()), - remainingDistanceMeters: Int(remaining.rounded()), - eta: eta, - roadName: step.instructions.isEmpty ? (destination?.name ?? "Continue") : step.instructions, - speedKPH: max(0, location.speed * 3.6), - gpsAccuracyMeters: max(0, location.horizontalAccuracy), - isRerouting: false, - statusText: location.horizontalAccuracy > 35 ? "GPS accuracy low" : "Navigation" - ) - } - - private func firstUsefulStep(in steps: [MKRoute.Step]) -> Int { - steps.firstIndex(where: { !$0.instructions.isEmpty && $0.distance > 0 }) ?? 0 - } - - private func distance(from location: CLLocation, toEndOf step: MKRoute.Step) -> CLLocationDistance { - guard step.polyline.pointCount > 0 else { return step.distance } - let point = step.polyline.point(at: step.polyline.pointCount - 1).coordinate - return location.distance(from: CLLocation(latitude: point.latitude, longitude: point.longitude)) - } - - private func maneuver(from instructions: String) -> NavigationManeuver { - let text = instructions.lowercased() - if text.contains("u-turn") || text.contains("u turn") { return .uTurn } - if text.contains("roundabout") || text.contains("circle") { return .roundabout } - if text.contains("slight left") || text.contains("keep left") { return .slightLeft } - if text.contains("slight right") || text.contains("keep right") { return .slightRight } - if text.contains("left") { return .turnLeft } - if text.contains("right") { return .turnRight } - if text.contains("arrive") || text.contains("destination") { return .arrive } - return .continueStraight - } -} - -enum NavigationEngineError: LocalizedError { - case destinationNotFound - case routeUnavailable - - var errorDescription: String? { - switch self { - case .destinationNotFound: return "Destination could not be found." - case .routeUnavailable: return "No driving route is available." - } - } -} diff --git a/RideDash/NavigationCore/NavigationShareParser.swift b/RideDash/NavigationCore/NavigationShareParser.swift deleted file mode 100644 index 42a7490..0000000 --- a/RideDash/NavigationCore/NavigationShareParser.swift +++ /dev/null @@ -1,21 +0,0 @@ -import Foundation - -struct SharedDestination: Sendable { - var query: String -} - -enum NavigationShareParser { - static func parse(_ text: String) -> SharedDestination? { - let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) - guard !trimmed.isEmpty else { return nil } - if let url = URL(string: trimmed), let components = URLComponents(url: url, resolvingAgainstBaseURL: false) { - for key in ["q", "query", "destination", "daddr"] { - if let value = components.queryItems?.first(where: { $0.name.lowercased() == key })?.value, - !value.isEmpty { - return SharedDestination(query: value) - } - } - } - return SharedDestination(query: trimmed) - } -} diff --git a/RideDash/ProjectionCore/DashRenderer.swift b/RideDash/ProjectionCore/DashRenderer.swift deleted file mode 100644 index f36a678..0000000 --- a/RideDash/ProjectionCore/DashRenderer.swift +++ /dev/null @@ -1,232 +0,0 @@ -import CoreGraphics -import CoreVideo -import Foundation -import UIKit - -final class DashRenderer { - 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 DashRendererError.pixelBufferCreationFailed(status) - } - - CVPixelBufferLockBaseAddress(buffer, []) - defer { CVPixelBufferUnlockBaseAddress(buffer, []) } - guard let baseAddress = CVPixelBufferGetBaseAddress(buffer) else { - throw DashRendererError.missingBaseAddress - } - - let bytesPerRow = CVPixelBufferGetBytesPerRow(buffer) - guard let context = CGContext( - data: baseAddress, - width: width, - height: height, - bitsPerComponent: 8, - bytesPerRow: bytesPerRow, - space: CGColorSpaceCreateDeviceRGB(), - bitmapInfo: CGBitmapInfo.byteOrder32Little.rawValue | - CGImageAlphaInfo.premultipliedFirst.rawValue - ) else { - throw DashRendererError.contextCreationFailed - } - - context.setFillColor(UIColor.black.cgColor) - context.fill(CGRect(x: 0, y: 0, width: width, height: height)) - context.translateBy(x: 0, y: CGFloat(height)) - context.scaleBy(x: 1, y: -1) - - UIGraphicsPushContext(context) - defer { UIGraphicsPopContext() } - draw(state, in: CGRect(x: 0, y: 0, width: width, height: height)) - return buffer - } - - private func draw(_ state: ProjectionUIState, in bounds: CGRect) { - let safe = bounds.insetBy(dx: 52, dy: 20) - let white = UIColor.white - let secondary = UIColor(white: 0.72, alpha: 1) - let accent = UIColor.systemOrange - - let topFont = UIFont.systemFont(ofSize: 17, weight: .semibold) - state.statusText.draw( - in: CGRect(x: safe.minX, y: safe.minY, width: safe.width, height: 24), - withAttributes: [.font: topFont, .foregroundColor: secondary] - ) - - let arrowRect = CGRect(x: safe.minX + 6, y: 65, width: 88, height: 88) - drawManeuver(state.maneuver, in: arrowRect, color: accent) - - let distanceText = formattedDistance(state.distanceToTurnMeters) - distanceText.draw( - in: CGRect(x: safe.minX + 110, y: 58, width: safe.width - 110, height: 52), - withAttributes: [ - .font: UIFont.monospacedDigitSystemFont(ofSize: 42, weight: .bold), - .foregroundColor: white - ] - ) - - state.roadName.draw( - in: CGRect(x: safe.minX + 110, y: 112, width: safe.width - 115, height: 58), - withAttributes: [ - .font: UIFont.systemFont(ofSize: 20, weight: .medium), - .foregroundColor: white - ] - ) - - let remaining = "Remaining \(formattedDistance(state.remainingDistanceMeters))" - remaining.draw( - in: CGRect(x: safe.minX, y: 204, width: safe.width * 0.55, height: 28), - withAttributes: [ - .font: UIFont.systemFont(ofSize: 16, weight: .medium), - .foregroundColor: secondary - ] - ) - - let speed = "\(Int(state.speedKPH.rounded())) km/h" - speed.draw( - in: CGRect(x: safe.midX, y: 204, width: safe.width * 0.5, height: 28), - withAttributes: [ - .font: UIFont.monospacedDigitSystemFont(ofSize: 17, weight: .semibold), - .foregroundColor: secondary - ] - ) - - if let eta = state.eta { - let formatter = DateFormatter() - formatter.dateFormat = "h:mm a" - let etaText = "ETA \(formatter.string(from: eta))" - etaText.draw( - in: CGRect(x: safe.minX, y: 238, width: safe.width, height: 28), - withAttributes: [ - .font: UIFont.systemFont(ofSize: 16, weight: .semibold), - .foregroundColor: white - ] - ) - } - - if state.isRerouting { - let text = "Rerouting…" - text.draw( - in: CGRect(x: safe.maxX - 120, y: safe.minY, width: 120, height: 24), - withAttributes: [.font: topFont, .foregroundColor: accent] - ) - } - } - - private func drawManeuver(_ maneuver: NavigationManeuver, in rect: CGRect, color: UIColor) { - guard let context = UIGraphicsGetCurrentContext() else { return } - context.saveGState() - defer { context.restoreGState() } - context.setStrokeColor(color.cgColor) - context.setFillColor(color.cgColor) - context.setLineWidth(12) - context.setLineCap(.round) - context.setLineJoin(.round) - - let center = CGPoint(x: rect.midX, y: rect.midY) - let top = rect.minY + 8 - let bottom = rect.maxY - 8 - let left = rect.minX + 8 - let right = rect.maxX - 8 - - switch maneuver { - case .turnLeft, .slightLeft: - context.move(to: CGPoint(x: center.x, y: bottom)) - context.addLine(to: CGPoint(x: center.x, y: center.y)) - context.addLine(to: CGPoint(x: left + 12, y: center.y)) - context.strokePath() - drawArrowHead(at: CGPoint(x: left + 8, y: center.y), pointing: .left, context: context) - case .turnRight, .slightRight: - context.move(to: CGPoint(x: center.x, y: bottom)) - context.addLine(to: CGPoint(x: center.x, y: center.y)) - context.addLine(to: CGPoint(x: right - 12, y: center.y)) - context.strokePath() - drawArrowHead(at: CGPoint(x: right - 8, y: center.y), pointing: .right, context: context) - case .uTurn: - context.addArc(center: CGPoint(x: center.x, y: center.y), radius: 25, startAngle: .pi / 2, endAngle: .pi * 1.8, clockwise: true) - context.strokePath() - drawArrowHead(at: CGPoint(x: center.x - 24, y: center.y + 8), pointing: .down, context: context) - case .roundabout: - context.addEllipse(in: rect.insetBy(dx: 18, dy: 18)) - context.strokePath() - drawArrowHead(at: CGPoint(x: right - 12, y: center.y), pointing: .right, context: context) - case .arrive: - context.fillEllipse(in: CGRect(x: center.x - 16, y: center.y - 16, width: 32, height: 32)) - case .continueStraight: - context.move(to: CGPoint(x: center.x, y: bottom)) - context.addLine(to: CGPoint(x: center.x, y: top + 15)) - context.strokePath() - drawArrowHead(at: CGPoint(x: center.x, y: top + 6), pointing: .up, context: context) - } - } - - private enum ArrowDirection { case up, down, left, right } - - private func drawArrowHead(at point: CGPoint, pointing direction: ArrowDirection, context: CGContext) { - let size: CGFloat = 17 - let path = UIBezierPath() - switch direction { - case .up: - path.move(to: CGPoint(x: point.x, y: point.y - size)) - path.addLine(to: CGPoint(x: point.x - size, y: point.y + size * 0.6)) - path.addLine(to: CGPoint(x: point.x + size, y: point.y + size * 0.6)) - case .down: - path.move(to: CGPoint(x: point.x, y: point.y + size)) - path.addLine(to: CGPoint(x: point.x - size, y: point.y - size * 0.6)) - path.addLine(to: CGPoint(x: point.x + size, y: point.y - size * 0.6)) - case .left: - path.move(to: CGPoint(x: point.x - size, y: point.y)) - path.addLine(to: CGPoint(x: point.x + size * 0.6, y: point.y - size)) - path.addLine(to: CGPoint(x: point.x + size * 0.6, y: point.y + size)) - case .right: - path.move(to: CGPoint(x: point.x + size, y: point.y)) - path.addLine(to: CGPoint(x: point.x - size * 0.6, y: point.y - size)) - path.addLine(to: CGPoint(x: point.x - size * 0.6, y: point.y + size)) - } - path.close() - context.addPath(path.cgPath) - context.fillPath() - } - - private func formattedDistance(_ meters: Int) -> String { - if meters >= 1000 { - return String(format: "%.1f km", Double(meters) / 1000) - } - return "\(max(0, meters)) m" - } -} - -enum DashRendererError: LocalizedError { - case pixelBufferCreationFailed(CVReturn) - case missingBaseAddress - case contextCreationFailed - - var errorDescription: String? { - switch self { - case .pixelBufferCreationFailed(let code): return "Pixel buffer creation failed (\(code))." - case .missingBaseAddress: return "Pixel buffer has no writable base address." - case .contextCreationFailed: return "Could not create dash drawing context." - } - } -} diff --git a/RideDash/ProjectionCore/H264Encoder.swift b/RideDash/ProjectionCore/H264Encoder.swift deleted file mode 100644 index 445061d..0000000 --- a/RideDash/ProjectionCore/H264Encoder.swift +++ /dev/null @@ -1,193 +0,0 @@ -import CoreMedia -import Foundation -import VideoToolbox - -final class H264Encoder { - var onEncodedFrame: ((EncodedH264Frame) -> Void)? - var onError: ((Error) -> Void)? - - private var session: VTCompressionSession? - private let width: Int32 - private let height: Int32 - private let fps: Int32 - private let bitrate: Int - - init(width: Int, height: Int, fps: Double, bitrate: Int) throws { - self.width = Int32(width) - self.height = Int32(height) - self.fps = Int32(max(1, fps.rounded())) - self.bitrate = bitrate - try configure() - } - - deinit { invalidate() } - - func encode(_ pixelBuffer: CVPixelBuffer, presentationTime: CMTime) throws { - guard let session else { throw H264EncoderError.sessionUnavailable } - var flags = VTEncodeInfoFlags() - let status = VTCompressionSessionEncodeFrame( - session, - imageBuffer: pixelBuffer, - presentationTimeStamp: presentationTime, - duration: CMTime(value: 1, timescale: fps), - frameProperties: nil, - sourceFrameRefcon: nil, - infoFlagsOut: &flags - ) - guard status == noErr else { throw H264EncoderError.encodeFailed(status) } - } - - func completeFrames() { - if let session { - VTCompressionSessionCompleteFrames(session, untilPresentationTimeStamp: .invalid) - } - } - - func invalidate() { - if let session { - VTCompressionSessionInvalidate(session) - self.session = nil - } - } - - private func configure() throws { - var created: VTCompressionSession? - let status = VTCompressionSessionCreate( - allocator: kCFAllocatorDefault, - width: width, - height: height, - codecType: kCMVideoCodecType_H264, - encoderSpecification: nil, - imageBufferAttributes: nil, - compressedDataAllocator: nil, - outputCallback: h264OutputCallback, - refcon: Unmanaged.passUnretained(self).toOpaque(), - compressionSessionOut: &created - ) - guard status == noErr, let created else { - throw H264EncoderError.sessionCreationFailed(status) - } - session = created - - set(kVTCompressionPropertyKey_RealTime, value: kCFBooleanTrue) - set(kVTCompressionPropertyKey_AllowFrameReordering, value: kCFBooleanFalse) - set(kVTCompressionPropertyKey_AverageBitRate, value: NSNumber(value: bitrate)) - set(kVTCompressionPropertyKey_ExpectedFrameRate, value: NSNumber(value: fps)) - set(kVTCompressionPropertyKey_MaxKeyFrameInterval, value: NSNumber(value: max(1, fps * 2))) - set(kVTCompressionPropertyKey_ProfileLevel, value: kVTProfileLevel_H264_Baseline_AutoLevel) - - let prepareStatus = VTCompressionSessionPrepareToEncodeFrames(created) - guard prepareStatus == noErr else { - throw H264EncoderError.prepareFailed(prepareStatus) - } - } - - private func set(_ key: CFString, value: CFTypeRef) { - guard let session else { return } - VTSessionSetProperty(session, key: key, value: value) - } - - fileprivate func handle(status: OSStatus, sampleBuffer: CMSampleBuffer?) { - guard status == noErr else { - onError?(H264EncoderError.encodeFailed(status)) - return - } - guard let sampleBuffer, CMSampleBufferDataIsReady(sampleBuffer) else { return } - - let isKeyFrame: Bool = { - guard let attachments = CMSampleBufferGetSampleAttachmentsArray( - sampleBuffer, - createIfNecessary: false - ) as? [[CFString: Any]], let first = attachments.first else { return false } - return first[kCMSampleAttachmentKey_NotSync] == nil - }() - - var nalUnits: [H264NALUnit] = [] - if isKeyFrame, let format = CMSampleBufferGetFormatDescription(sampleBuffer) { - nalUnits.append(contentsOf: parameterSets(from: format)) - } - nalUnits.append(contentsOf: avccNALUnits(from: sampleBuffer)) - - guard !nalUnits.isEmpty else { return } - let pts = CMTimeGetSeconds(CMSampleBufferGetPresentationTimeStamp(sampleBuffer)) - onEncodedFrame?( - EncodedH264Frame( - presentationTime: pts.isFinite ? pts : 0, - isKeyFrame: isKeyFrame, - nalUnits: nalUnits - ) - ) - } - - private func parameterSets(from format: CMFormatDescription) -> [H264NALUnit] { - var result: [H264NALUnit] = [] - for index in 0..<2 { - var pointer: UnsafePointer? - var size = 0 - var count = 0 - var headerLength: Int32 = 0 - let status = CMVideoFormatDescriptionGetH264ParameterSetAtIndex( - format, - parameterSetIndex: index, - parameterSetPointerOut: &pointer, - parameterSetSizeOut: &size, - parameterSetCountOut: &count, - nalUnitHeaderLengthOut: &headerLength - ) - if status == noErr, let pointer, size > 0 { - result.append(H264NALUnit(data: Data(bytes: pointer, count: size))) - } - } - return result - } - - private func avccNALUnits(from sampleBuffer: CMSampleBuffer) -> [H264NALUnit] { - guard let blockBuffer = CMSampleBufferGetDataBuffer(sampleBuffer) else { return [] } - let totalLength = CMBlockBufferGetDataLength(blockBuffer) - guard totalLength > 4 else { return [] } - - var bytes = Data(count: totalLength) - let status = bytes.withUnsafeMutableBytes { destination in - CMBlockBufferCopyDataBytes( - blockBuffer, - atOffset: 0, - dataLength: totalLength, - destination: destination.baseAddress! - ) - } - guard status == kCMBlockBufferNoErr else { return [] } - - var result: [H264NALUnit] = [] - var offset = 0 - while offset + 4 <= bytes.count { - let length = bytes[offset..<(offset + 4)].reduce(0) { ($0 << 8) | Int($1) } - offset += 4 - guard length > 0, offset + length <= bytes.count else { break } - result.append(H264NALUnit(data: bytes.subdata(in: offset..<(offset + length)))) - offset += length - } - return result - } -} - -private let h264OutputCallback: VTCompressionOutputCallback = { refcon, _, status, _, sampleBuffer in - guard let refcon else { return } - let encoder = Unmanaged.fromOpaque(refcon).takeUnretainedValue() - encoder.handle(status: status, sampleBuffer: sampleBuffer) -} - -enum H264EncoderError: LocalizedError { - case sessionCreationFailed(OSStatus) - case prepareFailed(OSStatus) - case encodeFailed(OSStatus) - case sessionUnavailable - - var errorDescription: String? { - switch self { - case .sessionCreationFailed(let code): return "H.264 session creation failed (\(code))." - case .prepareFailed(let code): return "H.264 encoder prepare failed (\(code))." - case .encodeFailed(let code): return "H.264 encode failed (\(code))." - case .sessionUnavailable: return "H.264 encoder session is unavailable." - } - } -} diff --git a/RideDash/ProjectionCore/H264NALUnit.swift b/RideDash/ProjectionCore/H264NALUnit.swift deleted file mode 100644 index 5313566..0000000 --- a/RideDash/ProjectionCore/H264NALUnit.swift +++ /dev/null @@ -1,16 +0,0 @@ -import Foundation - -struct H264NALUnit: Sendable, Hashable { - let data: Data - - var type: UInt8 { data.first.map { $0 & 0x1F } ?? 0 } - var isIDR: Bool { type == 5 } - var isSPS: Bool { type == 7 } - var isPPS: Bool { type == 8 } -} - -struct EncodedH264Frame: Sendable { - let presentationTime: Double - let isKeyFrame: Bool - let nalUnits: [H264NALUnit] -} diff --git a/RideDash/ProjectionCore/ProjectionStreamer.swift b/RideDash/ProjectionCore/ProjectionStreamer.swift deleted file mode 100644 index 2da3957..0000000 --- a/RideDash/ProjectionCore/ProjectionStreamer.swift +++ /dev/null @@ -1,103 +0,0 @@ -import Combine -import CoreMedia -import Foundation - -@MainActor -final class ProjectionStreamer: ObservableObject { - @Published private(set) var isRunning = false - @Published private(set) var encodedFrameCount = 0 - @Published private(set) var sentPacketCount = 0 - @Published private(set) var lastError: String? - - private let transport: DashDatagramTransport - private let configuration: DashProtocolConfiguration - private let renderer: DashRenderer - private let packetizer = RTPPacketizer() - private var encoder: H264Encoder? - private var renderTask: Task? - private var stateProvider: (() -> ProjectionUIState)? - - init( - transport: DashDatagramTransport, - configuration: DashProtocolConfiguration - ) { - self.transport = transport - self.configuration = configuration - renderer = DashRenderer(width: configuration.renderWidth, height: configuration.renderHeight) - } - - func start(stateProvider: @escaping () -> ProjectionUIState) throws { - stop() - self.stateProvider = stateProvider - - let encoder = try H264Encoder( - width: configuration.renderWidth, - height: configuration.renderHeight, - fps: configuration.projectionFPS, - bitrate: configuration.videoBitrate - ) - encoder.onEncodedFrame = { [weak self] frame in - Task { @MainActor in - await self?.handle(frame) - } - } - encoder.onError = { [weak self] error in - Task { @MainActor in self?.lastError = error.localizedDescription } - } - self.encoder = encoder - isRunning = true - - let fps = max(1, configuration.projectionFPS) - let frameDuration = 1.0 / fps - let timescale = Int32(max(1, fps.rounded())) - - renderTask = Task { [weak self] in - guard let self else { return } - var frameIndex: Int64 = 0 - while !Task.isCancelled, self.isRunning { - do { - guard let provider = self.stateProvider, - let encoder = self.encoder else { break } - let pixelBuffer = try self.renderer.render(provider()) - try encoder.encode( - pixelBuffer, - presentationTime: CMTime(value: frameIndex, timescale: timescale) - ) - frameIndex += 1 - } catch { - self.lastError = error.localizedDescription - } - - do { - try await Task.sleep(for: .seconds(frameDuration)) - } catch { - break - } - } - } - } - - func stop() { - isRunning = false - renderTask?.cancel() - renderTask = nil - encoder?.completeFrames() - encoder?.invalidate() - encoder = nil - stateProvider = nil - } - - private func handle(_ frame: EncodedH264Frame) async { - encodedFrameCount += 1 - let packets = packetizer.packetize(frame: frame) - for packet in packets { - do { - try await transport.sendVideo(packet.data) - sentPacketCount += 1 - } catch { - lastError = error.localizedDescription - break - } - } - } -} diff --git a/RideDash/ProjectionCore/ProjectionUIState.swift b/RideDash/ProjectionCore/ProjectionUIState.swift deleted file mode 100644 index 6a09fac..0000000 --- a/RideDash/ProjectionCore/ProjectionUIState.swift +++ /dev/null @@ -1,25 +0,0 @@ -import Foundation - -struct ProjectionUIState: Sendable, Equatable { - var maneuver: NavigationManeuver = .continueStraight - var distanceToTurnMeters: Int = 0 - var remainingDistanceMeters: Int = 0 - var eta: Date? - var roadName: String = "Ready" - var speedKPH: Double = 0 - var gpsAccuracyMeters: Double? - var isRerouting = false - var statusText = "RideDash" - - static let preview = ProjectionUIState( - maneuver: .turnRight, - distanceToTurnMeters: 350, - remainingDistanceMeters: 12_400, - eta: Date().addingTimeInterval(1_800), - roadName: "Continue to destination", - speedKPH: 42, - gpsAccuracyMeters: 5, - isRerouting: false, - statusText: "Navigation" - ) -} diff --git a/RideDash/ProjectionCore/RTPPacketizer.swift b/RideDash/ProjectionCore/RTPPacketizer.swift deleted file mode 100644 index d9cef02..0000000 --- a/RideDash/ProjectionCore/RTPPacketizer.swift +++ /dev/null @@ -1,108 +0,0 @@ -import Foundation - -struct RTPPacket: Sendable { - let sequenceNumber: UInt16 - let timestamp: UInt32 - let marker: Bool - let data: Data -} - -final class RTPPacketizer { - private var sequenceNumber: UInt16 - private let ssrc: UInt32 - private let payloadType: UInt8 - private let maxPayloadSize: Int - - init( - initialSequence: UInt16 = UInt16.random(in: 0...UInt16.max), - ssrc: UInt32 = UInt32.random(in: 1...UInt32.max), - payloadType: UInt8 = 96, - maxPayloadSize: Int = 1_180 - ) { - self.sequenceNumber = initialSequence - self.ssrc = ssrc - self.payloadType = payloadType - self.maxPayloadSize = max(256, maxPayloadSize) - } - - func packetize(frame: EncodedH264Frame) -> [RTPPacket] { - let scaled = max(0, frame.presentationTime) * 90_000 - let timestamp = UInt32(truncatingIfNeeded: UInt64(scaled.rounded())) - var result: [RTPPacket] = [] - - for (nalIndex, nal) in frame.nalUnits.enumerated() { - let isFinalNAL = nalIndex == frame.nalUnits.count - 1 - if nal.data.count <= maxPayloadSize { - result.append(makePacket(payload: nal.data, timestamp: timestamp, marker: isFinalNAL)) - } else { - result.append(contentsOf: fragment(nal: nal, timestamp: timestamp, markerOnLast: isFinalNAL)) - } - } - return result - } - - private func fragment(nal: H264NALUnit, timestamp: UInt32, markerOnLast: Bool) -> [RTPPacket] { - guard let nalHeader = nal.data.first else { return [] } - let payload = nal.data.dropFirst() - let chunkSize = maxPayloadSize - 2 - let fuIndicator = (nalHeader & 0xE0) | 28 - let nalType = nalHeader & 0x1F - - var result: [RTPPacket] = [] - var offset = 0 - while offset < payload.count { - let end = min(offset + chunkSize, payload.count) - let isStart = offset == 0 - let isEnd = end == payload.count - var fuHeader = nalType - if isStart { fuHeader |= 0x80 } - if isEnd { fuHeader |= 0x40 } - - var body = Data([fuIndicator, fuHeader]) - let lower = payload.index(payload.startIndex, offsetBy: offset) - let upper = payload.index(payload.startIndex, offsetBy: end) - body.append(contentsOf: payload[lower.. RTPPacket { - let currentSequence = sequenceNumber - sequenceNumber &+= 1 - - var packet = Data(capacity: 12 + payload.count) - packet.append(0x80) // RTP v2 - packet.append((marker ? 0x80 : 0x00) | (payloadType & 0x7F)) - appendUInt16(currentSequence, to: &packet) - appendUInt32(timestamp, to: &packet) - appendUInt32(ssrc, to: &packet) - packet.append(payload) - - return RTPPacket( - sequenceNumber: currentSequence, - timestamp: timestamp, - marker: marker, - data: packet - ) - } - - private func appendUInt16(_ value: UInt16, to data: inout Data) { - data.append(UInt8((value >> 8) & 0xff)) - data.append(UInt8(value & 0xff)) - } - - private func appendUInt32(_ value: UInt32, to data: inout Data) { - data.append(UInt8((value >> 24) & 0xff)) - data.append(UInt8((value >> 16) & 0xff)) - data.append(UInt8((value >> 8) & 0xff)) - data.append(UInt8(value & 0xff)) - } -} From 3c2578a5857cae7d554dbaae402e00c856eb06f5 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:23:45 +0530 Subject: [PATCH 099/112] docs: add end-to-end manual hardware test guide --- Docs/MANUAL_TEST_GUIDE.md | 267 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 267 insertions(+) create mode 100644 Docs/MANUAL_TEST_GUIDE.md 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. From e0c8f33cae5c0bc120040fb8dfb5b9829ca60b31 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:24:04 +0530 Subject: [PATCH 100/112] docs: mark first hardware beta implementation complete --- Docs/IMPLEMENTATION_STATUS.md | 81 +++++++++++++++++++++++++---------- 1 file changed, 59 insertions(+), 22 deletions(-) diff --git a/Docs/IMPLEMENTATION_STATUS.md b/Docs/IMPLEMENTATION_STATUS.md index e15f7de..24ee83a 100644 --- a/Docs/IMPLEMENTATION_STATUS.md +++ b/Docs/IMPLEMENTATION_STATUS.md @@ -1,33 +1,70 @@ # RideDash Implementation Status -This file tracks code completion independent of CI/CD. Final validation is manual on a physical iPhone and compatible motorcycle dash. +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. -## Implemented +## 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] Ride history +- [x] MapKit route calculation and preview +- [x] CoreLocation live navigation state +- [x] Apple Maps hand-off +- [x] `ridedash://` route deep links +- [x] Share Extension for shared map URLs/text +- [x] Currency / distance preferences + +## Display interoperability stack -- [x] Project skeleton - [x] Hotspot Configuration entitlement -- [x] In-app Wi-Fi join request +- [x] User-approved in-app Wi-Fi join request - [x] Local network path monitoring -- [x] UDP route scaffold -- [x] Diagnostic logging/export +- [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] 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] Manual stop/disconnect recovery paths +- [x] Configurable host/broadcast/ports/FPS/bitrate + +## Hardware validation still required + +The code intentionally keeps firmware-sensitive assumptions configurable. The following cannot be truthfully marked complete until the physical test: + +- [ ] Exact target-firmware endpoint/port validation +- [ ] Authentication success across three 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 -## In progress - -- [ ] Multi-port UDP transport and packet receive stream -- [ ] Protocol framing / K1G-TLV helpers -- [ ] Session state machine -- [ ] Authentication handshake -- [ ] Projection control plane -- [ ] H.264 encoder -- [ ] RTP packetization -- [ ] Projection streamer -- [ ] Dash renderer -- [ ] Navigation state engine -- [ ] Dash input decoder -- [ ] Recovery/reconnect -- [ ] Product UI +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 final integration test is performed manually on the user's owned Guerrilla 450 dash and iPhone. Firmware-specific constants remain configurable until that test is complete. +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. From 5e9e2b99019a5c8b43a8e7351071f18738a16b8e Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:24:38 +0530 Subject: [PATCH 101/112] fix: keep app-managed dash Wi-Fi configuration for ride sessions --- RideDash/DashConnectivity/TripperWiFiManager.swift | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/RideDash/DashConnectivity/TripperWiFiManager.swift b/RideDash/DashConnectivity/TripperWiFiManager.swift index 1758f1b..4d3e41c 100644 --- a/RideDash/DashConnectivity/TripperWiFiManager.swift +++ b/RideDash/DashConnectivity/TripperWiFiManager.swift @@ -45,12 +45,21 @@ final class TripperWiFiManager: ObservableObject, DashWiFiJoining { isWEP: false ) } - configuration.joinOnce = true + + // 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 error { + 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: ()) From f106b36891aa2d4955a09a6f1daa65a4e42d6c5d Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 17:25:51 +0530 Subject: [PATCH 102/112] fix: use control UDP port as diagnostics default --- RideDash/Features/Diagnostics/DiagnosticsView.swift | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/RideDash/Features/Diagnostics/DiagnosticsView.swift b/RideDash/Features/Diagnostics/DiagnosticsView.swift index 6cedcf7..968a235 100644 --- a/RideDash/Features/Diagnostics/DiagnosticsView.swift +++ b/RideDash/Features/Diagnostics/DiagnosticsView.swift @@ -10,7 +10,7 @@ struct DiagnosticsView: View { @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 = 5000 + @AppStorage("dash.test.port") private var dashPort = 2000 @State private var passphrase = "" @@ -112,13 +112,13 @@ struct DiagnosticsView: View { TextField("Display host", text: $dashHost) .textInputAutocapitalization(.never) .autocorrectionDisabled() - TextField("UDP port", value: $dashPort, format: .number) + TextField("UDP control 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") + log.append("Opening UDP control route to \(dashHost):\(dashPort)", category: "udp") } catch { log.append(error.localizedDescription, category: "udp", level: .error) } @@ -134,7 +134,7 @@ struct DiagnosticsView: View { } 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.") + Text("The default is the public-reference control port (2000). This screen is transport-only; use Settings → Connection & Projection for authentication, navigation control and H.264/RTP projection.") } } From cf9f7b5f12c76871d204ddb6aac05a9ce98f66ff Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 19:47:57 +0530 Subject: [PATCH 103/112] feat: harden dash session recovery and input handling --- RideDash/App/DashSessionCoordinator.swift | 187 ++++++++++++++++++---- 1 file changed, 159 insertions(+), 28 deletions(-) diff --git a/RideDash/App/DashSessionCoordinator.swift b/RideDash/App/DashSessionCoordinator.swift index 08541ab..7fe4fcb 100644 --- a/RideDash/App/DashSessionCoordinator.swift +++ b/RideDash/App/DashSessionCoordinator.swift @@ -36,6 +36,9 @@ final class DashSessionCoordinator: ObservableObject { @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 @@ -53,19 +56,41 @@ final class DashSessionCoordinator: ObservableObject { 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( @@ -74,39 +99,33 @@ final class DashSessionCoordinator: ObservableObject { profile: DashProtocolProfile = .publicReference, authTimeout: Duration = .seconds(8) ) async { - disconnect() + 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 } - 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) - } + await establishConnection(authTimeout: authTimeout) } func retryLastConnection() async { - let currentSSID = ssid - let currentHostname = hostname - let currentProfile = profile - guard !currentSSID.isEmpty else { return } - await connect(ssid: currentSSID, hostname: currentHostname, profile: currentProfile) + 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 { @@ -164,6 +183,7 @@ final class DashSessionCoordinator: ObservableObject { projectionHeartbeatTask?.cancel() cancelNavigationKeepAlives() projectionHeartbeatTask = nil + restoreNavigationAfterReconnect = false guard navEntered else { return } state = .stopping @@ -181,13 +201,74 @@ final class DashSessionCoordinator: ObservableObject { } 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 - transport.stop() + if stopTransport { transport.stop() } sequence = 0 modulus = nil exponent = nil @@ -195,8 +276,11 @@ final class DashSessionCoordinator: ObservableObject { authenticatedSession = nil authConfirmed = false navEntered = false + authRejectCount = 0 + consecutiveSendFailures = 0 lastButton = nil - state = .disconnected + lastAcceptedButton = nil + lastAcceptedButtonAt = .distantPast } // MARK: - Receive path @@ -224,27 +308,52 @@ final class DashSessionCoordinator: ObservableObject { 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 - state = .requestingAuthentication + authRejectCount += 1 log.append( - "Dash authentication rejected status=0x\(String(format: "%02X", status))", + "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) @@ -252,9 +361,20 @@ final class DashSessionCoordinator: ObservableObject { } case .button(let button): + let now = Date() + let isRepeat = lastAcceptedButton == button && now.timeIntervalSince(lastAcceptedButtonAt) < buttonDebounceInterval + lastButton = button - log.append("Dash input: \(String(describing: button))", category: "input") - onButton?(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, @@ -297,6 +417,7 @@ final class DashSessionCoordinator: ObservableObject { self.pendingAESKey = nil self.state = .failed(error.localizedDescription) self.log.append(error.localizedDescription, category: "auth", level: .error) + self.scheduleReconnect(reason: error.localizedDescription) } } } @@ -318,7 +439,16 @@ final class DashSessionCoordinator: ObservableObject { private func sendRaw(_ packet: Data) async throws { let patched = try K1GCodec.patchSequence(packet, sequence: sequence) sequence &+= 1 - try await transport.sendControl(patched) + 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 @@ -421,6 +551,7 @@ final class DashSessionCoordinator: ObservableObject { 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") } } From 01d28172bed1001ae6257824c502e7a36cc083da Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 19:48:51 +0530 Subject: [PATCH 104/112] feat: add route deviation detection and recalculation --- RideDash/NavigationCore/NavigationCore.swift | 138 ++++++++++++++++--- 1 file changed, 120 insertions(+), 18 deletions(-) diff --git a/RideDash/NavigationCore/NavigationCore.swift b/RideDash/NavigationCore/NavigationCore.swift index d685d16..f6d8614 100644 --- a/RideDash/NavigationCore/NavigationCore.swift +++ b/RideDash/NavigationCore/NavigationCore.swift @@ -142,11 +142,18 @@ final class NavigationViewModel: ObservableObject { @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 @@ -170,17 +177,8 @@ final class NavigationViewModel: ObservableObject { throw NavigationError.locationUnavailable } - let request = MKDirections.Request() - request.source = MKMapItem(placemark: MKPlacemark(coordinate: originLocation.coordinate)) - request.destination = MKMapItem(placemark: MKPlacemark(coordinate: resolved.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 } - self.route = route - activeStepIndex = firstUsableStep(in: route) - rebuildProjectionState(location: originLocation) + let newRoute = try await directions(from: originLocation, to: resolved) + apply(route: newRoute, from: originLocation) } catch { errorMessage = error.localizedDescription } @@ -190,6 +188,9 @@ final class NavigationViewModel: ObservableObject { route = nil destination = nil activeStepIndex = 0 + recalculationCount = 0 + distanceFromRouteMeters = 0 + errorMessage = nil projectionState = ProjectionUIState() } @@ -231,19 +232,68 @@ final class NavigationViewModel: ObservableObject { 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 rebuildProjectionState(location: CLLocation?) { + 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 + gpsAccuracy: location?.horizontalAccuracy, + statusMessage: forcedStatus ) return } @@ -252,21 +302,30 @@ final class NavigationViewModel: ObservableObject { ? nil : route.steps[min(max(0, activeStepIndex), route.steps.count - 1)] let instruction = (step?.instructions.isEmpty == false) ? (step?.instructions ?? "Continue") : "Continue" - let distance = step.map { Self.formatDistance($0.distance) } ?? "--" - let etaDate = Date().addingTimeInterval(route.expectedTravelTime) + 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: distance, + distanceToManeuver: Self.formatDistance(distanceToStep), eta: etaFormatter.string(from: etaDate), - remainingDistance: Self.formatDistance(route.distance), + remainingDistance: Self.formatDistance(remainingDistance), speedKph: max(0, (location?.speed ?? 0) * 3.6), gpsAccuracy: location?.horizontalAccuracy, isCalibrationGrid: false, - statusMessage: (location?.horizontalAccuracy ?? 0) > 50 ? "GPS accuracy degraded" : nil + statusMessage: status ) } @@ -297,6 +356,49 @@ final class NavigationViewModel: ObservableObject { 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" } From 8cfcbe285b73f2a3412d1a24d7e83f77ba996ddc Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 19:49:59 +0530 Subject: [PATCH 105/112] feat: add device health metrics and local protocol self-check --- .../Diagnostics/DiagnosticsView.swift | 159 +++++++++++++++++- 1 file changed, 156 insertions(+), 3 deletions(-) diff --git a/RideDash/Features/Diagnostics/DiagnosticsView.swift b/RideDash/Features/Diagnostics/DiagnosticsView.swift index 968a235..f185709 100644 --- a/RideDash/Features/Diagnostics/DiagnosticsView.swift +++ b/RideDash/Features/Diagnostics/DiagnosticsView.swift @@ -1,10 +1,13 @@ +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 = "" @@ -13,6 +16,7 @@ struct DiagnosticsView: View { @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 @@ -26,18 +30,23 @@ struct DiagnosticsView: View { 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") @@ -45,6 +54,7 @@ struct DiagnosticsView: View { .onChange(of: transport.state) { _, newValue in log.append("Transport: \(newValue.description)", category: "udp") } + .onChange(of: deviceHealth.thermalStateText) { _, _ in logDeviceHealth() } } private var hardwareSection: some View { @@ -57,6 +67,17 @@ struct DiagnosticsView: View { } } + 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) @@ -112,13 +133,13 @@ struct DiagnosticsView: View { TextField("Display host", text: $dashHost) .textInputAutocapitalization(.never) .autocorrectionDisabled() - TextField("UDP control port", value: $dashPort, format: .number) + 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 control route to \(dashHost):\(dashPort)", category: "udp") + log.append("Opening UDP route to \(dashHost):\(dashPort)", category: "udp") } catch { log.append(error.localizedDescription, category: "udp", level: .error) } @@ -134,7 +155,31 @@ struct DiagnosticsView: View { } header: { Text("UDP diagnostic route") } footer: { - Text("The default is the public-reference control port (2000). This screen is transport-only; use Settings → Connection & Projection for authentication, navigation control and H.264/RTP projection.") + 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.") } } @@ -168,6 +213,114 @@ struct DiagnosticsView: View { 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 { From d225b2b2491ea67d701a75d6bd787d2fedec59fd Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 19:52:24 +0530 Subject: [PATCH 106/112] feat: finish reconnect UI and maintenance reminders --- .../Features/Product/ProductFeatures.swift | 127 +++++++++++++++++- 1 file changed, 121 insertions(+), 6 deletions(-) diff --git a/RideDash/Features/Product/ProductFeatures.swift b/RideDash/Features/Product/ProductFeatures.swift index 1b2088a..567e6ab 100644 --- a/RideDash/Features/Product/ProductFeatures.swift +++ b/RideDash/Features/Product/ProductFeatures.swift @@ -2,6 +2,7 @@ import MapKit import SwiftData import SwiftUI import UIKit +import UserNotifications // MARK: - Local models @@ -203,6 +204,9 @@ struct DashboardView: View { .fill(connectionColor) .frame(width: 12, height: 12) } + if session.reconnectAttempt > 0 { + LabeledContent("Reconnect", value: "\(session.reconnectAttempt)/5") + } } Section("Active vehicle") { @@ -221,6 +225,9 @@ struct DashboardView: View { 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") { @@ -285,7 +292,7 @@ struct RideNavigationView: View { Button { Task { await navigation.calculateRoute() } } label: { - if navigation.isCalculating { + if navigation.isCalculating || navigation.isRecalculating { ProgressView() } else { Image(systemName: "arrow.triangle.turn.up.right.diamond.fill") @@ -307,6 +314,11 @@ struct RideNavigationView: View { 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() } @@ -423,9 +435,18 @@ struct DisplayConnectionView: View { 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)) } @@ -686,6 +707,15 @@ struct GarageView: View { 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) + } } } } @@ -746,22 +776,60 @@ struct AddMaintenanceView: View { @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 { - Picker("Type", selection: $kind) { - ForEach(MaintenanceKind.allCases) { Text($0.rawValue).tag($0) } + 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) + } } - TextField("Odometer km", value: $odometer, format: .number).keyboardType(.decimalPad) - TextField("Notes", text: $notes, axis: .vertical) } .navigationTitle("Maintenance") .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } } ToolbarItem(placement: .confirmationAction) { Button("Save") { - context.insert(MaintenanceRecord(kind: kind, odometerKm: odometer, notes: notes)) + 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() } } @@ -770,6 +838,44 @@ struct AddMaintenanceView: View { } } +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 { @@ -981,11 +1087,20 @@ struct SettingsView: View { .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) + } } } From 626efb1a1cb7521607c24a843d3c6d19adfbf672 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 19:53:01 +0530 Subject: [PATCH 107/112] chore: add app privacy manifest --- RideDash/PrivacyInfo.xcprivacy | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 RideDash/PrivacyInfo.xcprivacy 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 + + + + + From a04c8bedd8de2070911b5ef7def83a0fc0199049 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 19:54:21 +0530 Subject: [PATCH 108/112] chore: bundle privacy manifest --- RideDash.xcodeproj/project.pbxproj | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/RideDash.xcodeproj/project.pbxproj b/RideDash.xcodeproj/project.pbxproj index e1d5719..74434cc 100644 --- a/RideDash.xcodeproj/project.pbxproj +++ b/RideDash.xcodeproj/project.pbxproj @@ -22,6 +22,7 @@ 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 */ @@ -68,6 +69,7 @@ 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 */ @@ -110,6 +112,7 @@ 000000000000000000000016 /* Models */, 000000000000000000000115 /* Info.plist */, 000000000000000000000109 /* RideDash.entitlements */, + 000000000000000000000118 /* PrivacyInfo.xcprivacy */, ); path = RideDash; sourceTree = ""; @@ -298,6 +301,7 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( + 000000000000000000000216 /* PrivacyInfo.xcprivacy in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; From 1ee79fb95ccb51d28e795d6b4b7aa16ed8274fc6 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 19:54:31 +0530 Subject: [PATCH 109/112] docs: add interoperability and trademark notice --- NOTICE | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 NOTICE 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. From 5c559233f94702002b39039391ddc27b89c6e686 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 19:55:26 +0530 Subject: [PATCH 110/112] feat: record rides automatically during projection --- RideDash/App/RootView.swift | 50 +++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/RideDash/App/RootView.swift b/RideDash/App/RootView.swift index 456453f..53e0b7a 100644 --- a/RideDash/App/RootView.swift +++ b/RideDash/App/RootView.swift @@ -1,12 +1,17 @@ +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) { @@ -44,11 +49,56 @@ struct RootView: View { } 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 { From 62cf3b72b1faf0939c3f82be656994acaa6d824c Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 19:56:35 +0530 Subject: [PATCH 111/112] docs: mark remaining code-only work complete --- Docs/IMPLEMENTATION_STATUS.md | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/Docs/IMPLEMENTATION_STATUS.md b/Docs/IMPLEMENTATION_STATUS.md index 24ee83a..a1ef046 100644 --- a/Docs/IMPLEMENTATION_STATUS.md +++ b/Docs/IMPLEMENTATION_STATUS.md @@ -10,18 +10,25 @@ RideDash is **code-complete for the planned first hardware beta**. Final validat - [x] Garage / maintenance history - [x] Fuel logs and full-tank mileage calculation - [x] Expense tracking and CSV export -- [x] Ride history +- [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 @@ -32,6 +39,10 @@ RideDash is **code-complete for the planned first hardware beta**. Final validat - [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 @@ -46,15 +57,29 @@ RideDash is **code-complete for the planned first hardware beta**. Final validat - [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 three cold ignition cycles +- [ ] 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 From 88cb02221e22eb6727f8ddd77616f2b6937ca5d1 Mon Sep 17 00:00:00 2001 From: Rajveer Sharma <109028073+DagerottDev@users.noreply.github.com> Date: Fri, 4 Sep 2026 20:15:06 +0530 Subject: [PATCH 112/112] docs: update project plan with completed beta implementation --- Docs/PROJECT_PLAN.md | 729 +++++++++++++++++++++++-------------------- 1 file changed, 383 insertions(+), 346 deletions(-) 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.