{"id":13496717,"url":"https://github.com/kkonteh97/SwiftOBD2","last_synced_at":"2025-03-28T19:30:50.738Z","repository":{"id":225035725,"uuid":"763871981","full_name":"kkonteh97/SwiftOBD2","owner":"kkonteh97","description":"The versatile OBD2 toolkit for Swift developers.  Diagnose, explore, and build custom vehicle apps with ease. Includes an emulator for streamlined prototyping.","archived":false,"fork":false,"pushed_at":"2024-03-31T03:27:09.000Z","size":410,"stargazers_count":9,"open_issues_count":4,"forks_count":1,"subscribers_count":2,"default_branch":"main","last_synced_at":"2024-03-31T04:23:55.112Z","etag":null,"topics":["elm327","ios","macos","obd2","swift"],"latest_commit_sha":null,"homepage":"","language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/kkonteh97.png","metadata":{"files":{"readme":"Readme.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null}},"created_at":"2024-02-27T04:11:43.000Z","updated_at":"2024-03-31T04:23:57.347Z","dependencies_parsed_at":"2024-03-31T04:23:56.386Z","dependency_job_id":"07989f3a-229c-4d1d-9b9a-d515b3eebaf7","html_url":"https://github.com/kkonteh97/SwiftOBD2","commit_stats":null,"previous_names":["kkonteh97/swiftobd2"],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kkonteh97%2FSwiftOBD2","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kkonteh97%2FSwiftOBD2/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kkonteh97%2FSwiftOBD2/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kkonteh97%2FSwiftOBD2/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/kkonteh97","download_url":"https://codeload.github.com/kkonteh97/SwiftOBD2/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246088387,"owners_count":20721677,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["elm327","ios","macos","obd2","swift"],"created_at":"2024-07-31T19:01:57.791Z","updated_at":"2025-03-28T19:30:50.366Z","avatar_url":"https://github.com/kkonteh97.png","language":"Swift","funding_links":[],"categories":["Swift"],"sub_categories":[],"readme":"![Header](https://github.com/kkonteh97/SwiftOBD2/blob/main/Sources/Assets/github-header-image.png)\n\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/kkonteh97/SwiftOBD2/blob/main/LICENSE) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](http://makeapullrequest.com)  ![Platform](https://img.shields.io/badge/platform-iOS%20%7C%20macOS%20-lightgrey) ![Swift Version](https://img.shields.io/badge/swift-5.0-orange) ![iOS Version](https://img.shields.io/badge/iOS-^14.0-blue) ![macOS Version](https://img.shields.io/badge/macOS-11.0%20%7C%2012.0-blue)\n\n------------\n\n\nSwiftOBD2 is a Swift package designed to simplify communication with vehicles using an ELM327 OBD2 adapter. It provides a straightforward and powerful interface for interacting with your vehicle's onboard diagnostics system, allowing you to retrieve real-time data and perform diagnostics. [Sample App](https://github.com/kkonteh97/SwiftOBD2App).\n\n### Requirements\n\n- iOS 14.0+ / macOS 11.0+\n- Xcode 13.0+\n- Swift 5.0+\n\n### Key Features\n\n* Connection Management:\n    * Establishes connections to the OBD2 adapter via Bluetooth or Wi-Fi.\n    * Handles the initialization of the adapter and the vehicle connection process.\n    * Manages connection states (disconnected, connectedToAdapter, connectedToVehicle).Command Interface: Send and receive OBD2 commands for powerful interaction with your vehicle.\n    \n* Data Retrieval:\n    * Supports requests for real-time vehicle data (RPM, speed, etc.) using standard OBD2 PIDs (Parameter IDs).\n    * Provides functions to continuously poll and retrieve updated measurements.\n    * Can get a list of supported PIDs from the vehicle.\n    \n* Diagnostics:\n    * Retrieves and clears diagnostic trouble codes (DTCs).\n    * Gets the overall status of the vehicle's onboard systems.Sensor Monitoring: Retrieve and view data from various vehicle sensors in real time.\n    \n* Adaptability and Configuration\n    * Can switch between Bluetooth and Wi-Fi communication seamlessly.\n    * Allows for testing and development with a demo mode.\n    \n\n### Roadmap\n\n- [x] Connect to an OBD2 adapter via Bluetooth Low Energy (BLE) \n- [x] Retrieve error codes (DTCs) stored in the vehicle's OBD2 system\n- [x] Retrieve various OBD2 Parameter IDs (PIDs) for monitoring vehicle parameters\n- [x] Retrieve real-time vehicle data (RPM, speed, etc.) using standard OBD2 PIDs\n- [x] Get supported PIDs from the vehicle\n- [x] Clear error codes (DTCs) stored in the vehicle's OBD2 system\n- [ ] Run tests on the OBD2 system\n- [ ] Retrieve vehicle status since DTCs cleared\n- [ ] Connect to an OBD2 adapter via WIFI\n- [ ] Add support for custom PIDs\n    \n    \n### Setting Up a Project\n\n1. Create a New Swift Project:\n    * Open Xcode and start a new iOS project (You can use a simple \"App\" template).\n\n2. Add the SwiftOBD2 Package:\n    * In Xcode, navigate to File \u003e Add Packages...\n    * Enter this repository's URL: https://github.com/kkonteh97/SwiftOBD2/\n    * Select the desired dependency rule (version, branch, or commit).\n\n3. Permissions and Capabilities:\n    * If your app will use Bluetooth, you need to request the appropriate permissions and capabilities:\n        * Add NSBluetoothAlwaysUsageDescription to your Info.plist file with a brief description of why your app needs to use Bluetooth.\n        * Navigate to the Signing \u0026 Capabilities tab in your project settings and add the Background Modes capability. Enable the Uses Bluetooth LE Accessories option.\n        \n### Key Concepts\n\n* SwiftUI \u0026 Combine: Your code leverages the SwiftUI framework for building the user interface and Combine for reactive handling of updates from the OBDService.\n* OBDService: This is the core class within the SwiftOBD2 package. It handles communication with the OBD-II adapter and processes data from the vehicle.\n* OBDServiceDelegate: This protocol is crucial for receiving updates about the connection state and other events from the OBDService.\n* OBDCommand: These represent specific requests you can make to the vehicle's ECU (Engine Control Unit) for data.\n\n### Usage\n\n1. Import and Setup\n    * Begin by importing the necessary modules:\n\n\n```Swift\nimport SwiftUI\nimport SwiftOBD2\nimport Combine\n```\n\n2. ViewModel\n    * Create a ViewModel class that conforms to the ObservableObject protocol. This allows your SwiftUI views to observe changes in the ViewModel.\n    * Inside the ViewModel:\n        * Define a @Published property measurements to store the collected data.\n        * Initialize an OBDService instance, setting the desired connection type (e.g., Bluetooth, Wi-Fi).\n\n3. Connection Handling\n    * Implement the connectionStateChanged method from the OBDServiceDelegate protocol. Update the UI based on connection state changes (disconnected, connected, etc.) or handle any necessary logic.\n    \n4. Starting the Connection\n    * Create a startConnection function (ideally using async/await) to initiate the connection process with the OBD-II adapter. The OBDService's startConnection method will return useful OBDInfo about the vehicle. Like the Supported PIDs, Protocol, etc.\n    \n5. Stopping the Connection\n    * Create a stopConnection function to cleanly disconnect the service.\n    \n6. Retrieving Information\n    * Use the OBDService's methods to retrieve data from the vehicle, such as getting the vehicle's status, scanning for trouble codes, or requesting specific PIDs.\n        * getTroubleCodes: Retrieve diagnostic trouble codes (DTCs) from the vehicle's OBD-II system.\n        * getStatus: Retrieves Status since DTCs cleared.\n\n7. Continuous Updates\n    * Use the startContinuousUpdates method to continuously poll and retrieve updated measurements from the vehicle. This method returns a Combine publisher that you can subscribe to for updates.\n    * Can also add PIDs to the continuous updates using the addPID method.\n    \n### Code Example\n```Swift\nclass ViewModel: ObservableObject {\n    @Published var measurements: [OBDCommand: MeasurementResult] = [:]\n    @Published var connectionState: ConnectionState = .disconnected\n\n    var cancellables = Set\u003cAnyCancellable\u003e()\n    var requestingPIDs: [OBDCommand] = [.mode1(.rpm)] {\n        didSet {\n            addPID(command: requestingPIDs[-1])\n        }\n    }\n    \n    init() {\n        obdService.$connectionState\n            .assign(to: \u0026$connectionState)\n    }\n\n    let obdService = OBDService(connectionType: .bluetooth)\n\n    func startContinousUpdates() {\n        obdService.startContinuousUpdates([.mode1(.rpm)]) // You can add more PIDs\n            .sink { completion in\n                print(completion)\n            } receiveValue: { measurements in\n                self.measurements = measurements\n            }\n            .store(in: \u0026cancellables)\n    }\n\n    func addPID(command: OBDCommand) {\n        obdService.addPID(command)\n    }\n\n    func stopContinuousUpdates() {\n        cancellables.removeAll()\n    }\n\n    func startConnection() async throws  {\n        let obd2info = try await obdService.startConnection(preferedProtocol: .protocol6)\n        print(obd2info)\n    }\n\n    func stopConnection() {\n        obdService.stopConnection()\n    }\n\n    func switchConnectionType() {\n        obdService.switchConnectionType(.wifi)\n    }\n\n    func getStatus() async {\n        let status = try? await obdService.getStatus()\n        print(status ?? \"nil\")\n    }\n\n    func getTroubleCodes() async {\n        let troubleCodes = try? await obdService.scanForTroubleCodes()\n        print(troubleCodes ?? \"nil\")\n    }\n}\n\nstruct ContentView: View {\n    @ObservedObject var viewModel = ViewModel()\n    var body: some View {\n        VStack(spacing: 20) {\n            Text(\"Connection State: \\(viewModel.connectionState.rawValue)\")\n            ForEach(viewModel.requestingPIDs, id: \\.self) { pid in\n                Text(\"\\(pid.properties.description): \\(viewModel.measurements[pid]?.value ?? 0) \\(viewModel.measurements[pid]?.unit.symbol ?? \"\")\")\n            }\n            Button(\"Connect\") {\n                Task {\n                    do {\n                        try await viewModel.startConnection()\n                        viewModel.startContinousUpdates()\n                    } catch {\n                        print(error)\n                    }\n                }\n            }\n            .buttonStyle(.bordered)\n\n            Button(\"Stop\") {\n                viewModel.stopContinuousUpdates()\n            }\n            .buttonStyle(.bordered)\n\n            Button(\"Add PID\") {\n                viewModel.requestingPIDs.append(.mode1(.speed))\n            }\n        }\n        .padding()\n    }\n}\n\n```\n\n### Supported OBD2 Commands\n\nA comprehensive list of supported OBD2 commands will be available in the full documentation (coming soon).\n\n### Important Considerations\n\n* Ensure you have a compatible ELM327 OBD2 adapter.\n* Permissions: If using Bluetooth, your app may need to request Bluetooth permissions from the user.\n* Error Handling:  Implement robust error handling mechanisms to gracefully handle potential communication issues.\n* Background Updates (Optional): If your app needs background OBD2 data updates, explore iOS background fetch capabilities and fine-tune your library and app to work effectively in the background.\n\n\n## Contributing\n\nThis project welcomes your contributions! Feel free to open issues for bug reports or feature requests. To contribute code:\n\n1. Fork the repository.\n2. Create your feature branch.\n3. Commit your changes with descriptive messages.\n4. Submit a pull request for review.\n\n## License\n\nThe Swift OBD package is distributed under the MIT license. See the [LICENSE](https://github.com/kkonteh97/SwiftOBD2/blob/main/LICENSE) file for more details.\n\n------------\n\n##### Give this package a ⭐️ if you find it useful!\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkkonteh97%2FSwiftOBD2","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkkonteh97%2FSwiftOBD2","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkkonteh97%2FSwiftOBD2/lists"}