OBD2 API: A Lightweight Kotlin Library for Vehicle Diagnostics

Looking to integrate OBD2 functionality into your Kotlin projects? The Kotlin OBD API is a lightweight, developer-centric library designed to simplify querying and parsing OBD-II commands. Built with pure Kotlin, this API is platform-agnostic, offering a straightforward interface for seamless vehicle communication and diagnostics. Whether you’re developing Android apps for car diagnostics, building车载信息娱乐系统 (in-car entertainment systems), or creating custom automotive tools, this API provides the foundational components you need to interact with your vehicle’s OBD2 system effortlessly.

This flexible Obd2 Api empowers developers to utilize any connection interface—be it Bluetooth, Wi-Fi, or USB. By default, it leverages an ObdDeviceConnection that takes InputStream and OutputStream as parameters. This means if your chosen connection method can provide these streams, you’re all set to start leveraging the power of OBD2 data in your applications. Get ready to “hack your car” and unlock a wealth of vehicle data with this user-friendly Kotlin OBD2 API! 🚙

Installation

Setting up the Kotlin OBD API in your project is a breeze, with support for popular build tools like Gradle and Maven, as well as manual JAR installation. Choose the method that best suits your project setup and dive into vehicle diagnostics quickly.

Gradle

For Gradle-based projects, integrating the OBD2 API is just a few steps. First, ensure that you have the JitPack repository configured in your root build.gradle file. Add the following repository configuration within the repositories block:

repositories {
    // ... other repositories
    maven { url 'https://jitpack.io' }
}

Once the repository is configured, add the Kotlin OBD API dependency to your module’s build.gradle file within the dependencies block. This line will fetch and include the latest version of the API into your project:

dependencies {
    // ... other dependencies
    implementation 'com.github.eltonvs:kotlin-obd-api:1.3.0' // Kotlin OBD API
}

With these additions to your Gradle files, your project is now ready to utilize the Kotlin OBD2 API for vehicle diagnostics and data retrieval. Gradle will handle the dependency resolution and download, making the integration process smooth and efficient.

Maven

Maven users can also easily incorporate the Kotlin OBD API into their projects. Similar to Gradle, this involves adding the JitPack repository to your project’s pom.xml file. Locate the <repositories> section and add the following repository entry:

<repositories>
    <repository>
        <id>jitpack.io</id>
        <url>https://jitpack.io</url>
    </repository>
</repositories>

After configuring the repository, include the Kotlin OBD API dependency in the <dependencies> section of your pom.xml. This dependency declaration specifies the group ID, artifact ID, and version of the library:

<dependencies>
    <dependency>
        <groupId>com.github.eltonvs</groupId>
        <artifactId>kotlin-obd-api</artifactId>
        <version>1.3.0</version>
    </dependency>
</dependencies>

By adding these XML snippets to your pom.xml, Maven will manage the download and inclusion of the Kotlin OBD2 API into your project. Maven users can now leverage this powerful library for OBD-II communication and vehicle data analysis within their applications.

Manual

For those who prefer a manual approach or are working with build systems outside of Gradle or Maven, the Kotlin OBD API can be integrated by directly including the JAR file. You can download the pre-built JAR file from the GitHub releases page of the Kotlin OBD API repository.

Once downloaded, simply add the JAR file to your project’s classpath. This method is straightforward and provides full control over library inclusion, especially useful in more customized build environments or when direct file management is preferred. Ensure the JAR file is correctly placed in your project’s library directory and included in your build path to enable access to the OBD2 API functionalities.

Basic Usage

Once you’ve installed the Kotlin OBD2 API, you can quickly start sending OBD-II commands and receiving vehicle data. The core component for interaction is the ObdDeviceConnection. To instantiate this, you’ll need to obtain InputStream and OutputStream objects from your chosen connection interface (like Bluetooth or Wi-Fi OBD2 adapters).

// Create ObdDeviceConnection instance
val obdConnection = ObdDeviceConnection(inputStream, outputStream)

With an ObdDeviceConnection instance ready, you can execute OBD-II commands using the .run() method. This method accepts an ObdCommand instance as a parameter. The .run() method also offers optional parameters: useCache (defaults to false) and delayTime (defaults to 0).

// Retrieving OBD Speed Command
val response = obdConnection.run(SpeedCommand())

// Using cache (use with caution) for VIN command
val cachedResponse = obdConnection.run(VINCommand(), useCache = true)

// Command with a delay time - waits 500ms after execution for RPM command
val delayedResponse = obdConnection.run(RPMCommand(), delayTime = 500L)

The .run() method returns an ObdResponse object, which encapsulates the results of the OBD-II command execution. This response object contains valuable information about the command and the vehicle’s reply.

The ObdResponse object provides the following attributes, giving you structured access to the command execution results:

Attribute Type Description
command ObdCommand The original ObdCommand instance that was executed.
rawResponse ObdRawResponse Contains the raw data directly received from the vehicle’s ECU.
value String The parsed and formatted value extracted from the raw response.
unit String The unit of measurement for the parsed value (e.g., “Km/h”, “RPM”).

Delving deeper into the raw response, the ObdRawResponse object holds the unprocessed data and timing details:

Attribute Type Description
value String The raw hexadecimal string received from the OBD-II interface.
elapsedTime Long The time taken (in milliseconds) for the command to be sent and the response received.
processedValue String The raw hexadecimal value, cleaned of whitespace, colons, and other noise characters.
bufferedValue IntArray The raw hexadecimal value represented as an array of integers.

This structured response system allows developers to easily access both the processed and raw data from OBD-II commands, facilitating a wide range of vehicle diagnostic and monitoring applications.

Diagram showing the process of sending OBD-II commands and receiving responses using the Kotlin OBD2 API.

Extending the Library

The Kotlin OBD2 API is designed to be extensible, allowing you to easily add support for custom OBD-II commands beyond the built-in set. To create a custom command, you simply need to create a new Kotlin class that extends the ObdCommand class and override a few key properties and methods.

Here’s a template demonstrating how to create a CustomCommand:

class CustomCommand : ObdCommand() {
    // Required properties
    override val tag = "CUSTOM_COMMAND" // Unique tag for logging and identification
    override val name = "Custom Command" // Human-readable name for the command
    override val mode = "01"            // OBD-II service mode (e.g., "01" for current data)
    override val pid = "FF"             // Parameter ID (PID) for the command within the mode

    // Optional properties and handler
    override val defaultUnit = ""        // Default unit for the command's value (if applicable)
    override val handler = { response: ObdRawResponse ->
        // Custom logic to parse the raw response and extract the value
        "Calculations to parse value from ${response.processedValue}"
    }
}

In your custom command class, you are required to override the following properties:

  • tag: A unique string identifier for your command, useful for logging and debugging.
  • name: A descriptive, human-readable name for the command.
  • mode: The OBD-II service mode your command belongs to (e.g., “01” for showing current data, “03” for trouble codes). Refer to OBD-II standards for modes.
  • pid: The Parameter ID (PID) which specifies the data you are requesting within the given mode. OBD-II PID specifications are essential for defining this.

Optionally, you can override:

  • defaultUnit: If your command returns a value with a specific unit (like temperature in Celsius or speed in km/h), specify it here.
  • handler: This is a lambda function that takes an ObdRawResponse as input. Within this handler, you implement the custom logic to parse the processedValue from the raw response and return the extracted, meaningful value as a String. This is where the command-specific data interpretation happens.

By creating custom command classes and defining the parsing logic within the handler, you can extend the Kotlin OBD2 API to support virtually any OBD-II PID and tailor it to your specific vehicle diagnostic needs. This extensibility makes the API highly adaptable and powerful for advanced OBD2 interactions.

Commands

The Kotlin OBD2 API comes pre-equipped with support for a wide array of standard OBD-II commands, covering common vehicle sensors and diagnostic information. Below is a selection of the main supported commands. For a comprehensive list, refer to the SUPPORTED_COMMANDS.md file in the repository.

Key Supported OBD2 Commands:

  • Basic Vehicle Data:

    • Vehicle Speed (SpeedCommand)
    • Engine RPM (RPMCommand)
    • Throttle Position (ThrottlePositionCommand)
    • Engine Run Time (EngineRunTimeCommand)
    • Fuel Level Input (FuelLevelCommand)
  • Diagnostic Trouble Codes (DTCs):

    • DTC Number (DTCNumberCommand) – Counts stored DTCs.
    • Trouble Codes (TroubleCodesCommand) – Retrieves current, pending, and permanent DTCs.
    • MIL Status (MilOnOffCommand) – Checks if the Malfunction Indicator Lamp (MIL) is ON or OFF.
  • Engine and Fuel System:

    • Fuel Pressure (FuelPressureCommand)
    • Timing Advance (TimingAdvanceCommand)
    • Intake Air Temperature (IntakeAirTemperatureCommand)
    • Mass Air Flow Rate (MAF) (MassAirFlowCommand)
  • Vehicle Identification:

    • Vehicle Identification Number (VIN) (VINCommand)

Important Note: Command support can vary significantly between vehicle makes and models. Not all vehicles support every OBD-II command. Always consult your vehicle’s documentation or perform compatibility checks to determine which commands are supported by your specific car before relying on them in your application. The SUPPORTED_COMMANDS.md file provides details on the implemented commands within this API, but real-world vehicle support is hardware and ECU dependent.

Contributing

We warmly welcome contributions to the Kotlin OBD2 API! If you have ideas for improvements, new features, or have identified a bug, please feel free to contribute. Whether you want to add support for more OBD-II commands, enhance the API’s functionality, or improve documentation, your contributions are valuable.

To contribute:

  1. Fork the repository on GitHub.
  2. Create a new branch with a descriptive name for your feature or fix.
  3. Implement your changes, ensuring to follow the project’s coding style and guidelines.
  4. Write tests for your changes.
  5. Submit a pull request with a clear description of your contribution.

For feature requests or bug reports, please open an issue on the GitHub repository. Let’s collaborate to make this OBD2 API even better for the community!

Versioning

This project adheres to Semantic Versioning. We use SemVer to ensure clarity and predictability in our release cycle. For details on available versions, please check the tags on this repository. Versioning helps developers understand the nature of changes in each release and manage dependencies effectively.

Authors

The Kotlin OBD2 API is brought to you by a community of developers. See the full list of contributors who have participated in this project. We appreciate everyone who has helped make this API a valuable tool for OBD-II interaction.

License

This project is licensed under the Apache License 2.0. See the LICENSE file for full license details. The Apache 2.0 license is a permissive open-source license that allows for broad usage, modification, and distribution, both for commercial and non-commercial purposes.

Acknowledgments

We extend our gratitude to the open-source community and all individuals who have contributed to the development, testing, and improvement of the Kotlin OBD2 API. Your support and contributions are highly appreciated.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *