OBD2 to MQTT Integration: Connect Your Car to Home Assistant

In the realm of smart homes and connected devices, integrating your vehicle data can unlock a new dimension of automation and monitoring. By bridging your car’s On-Board Diagnostics (OBD2) system with the versatile MQTT protocol and your Home Assistant setup, you can gain real-time insights into your vehicle’s performance, diagnostics, and location. This article will guide you through the process of establishing an OBD2 to MQTT link, empowering you to monitor and interact with your car data directly within your smart home ecosystem.

What You Need to Get Started

To embark on this exciting project, you’ll need a few key components. This setup allows you to extract data from your car’s OBD2 port, transmit it wirelessly, and integrate it seamlessly with your Home Assistant dashboard. Here’s a comprehensive list of what you’ll require:

  • Home Assistant with Mosquitto Broker: A functioning Home Assistant instance is the central hub for visualizing and utilizing your car data. Ensure you have the Mosquitto Broker add-on installed and configured to handle MQTT messaging. Mosquitto Broker acts as the intermediary, receiving data from your car and making it available to Home Assistant.
  • (Optional) PlatformIO: If you desire to customize the firmware or build it from source, PlatformIO is a powerful open-source ecosystem for embedded development that simplifies the process of compiling and uploading code to your ESP32 device. While optional for basic setup using pre-built firmware, it’s essential for advanced modifications.
  • (Optional) Node.js and NPM (Node Package Manager): These are needed if you intend to work with the web-based configuration tools or perform more advanced development tasks related to the project. For most users, they are not mandatory for initial setup.
  • ESP32 with SIM800L or A7670: The ESP32 microcontroller serves as the brain of this project. It interfaces with the OBD2 adapter, processes the data, and transmits it over MQTT. The SIM800L or A7670 modules provide cellular connectivity, enabling data transmission even when Wi-Fi is unavailable. The choice between SIM800L and A7670 often depends on network requirements and desired features like GPS.
  • ELM327 OBD Bluetooth Adapter: This adapter is the crucial link between your car’s OBD2 port and the ESP32. It reads diagnostic and performance data from your vehicle’s computer. A Bluetooth-enabled ELM327 adapter is commonly used for wireless communication with the ESP32. Ensure compatibility with your vehicle’s OBD2 protocol.
  • SIM Card: A SIM card with a data plan is necessary for cellular connectivity if you are using a SIM800L or A7670 module. This allows for remote monitoring and data transmission from virtually anywhere with cellular coverage. Consider a cost-effective data plan suitable for IoT applications, like the fraenk SIM mentioned in the original article, or similar providers in your region.
  • A Car: Of course, you’ll need a car with an OBD2 port to extract data from! OBD2 ports are standard on most vehicles manufactured after 1996. Locate the OBD2 port in your car, typically found under the dashboard on the driver’s side.

Supported Devices for OBD2 MQTT

The project is designed to be compatible with a range of ESP32 boards equipped with cellular modules. Here’s a breakdown of supported devices, highlighting key features and considerations:

Product Cellular Module & Environment SSL/TLS Support Case Availability
T-Call SIM800L SIM800L_IP5306_VERSION_20190610, SIM800L_IP5306_VERSION_20200811 ❌ (Limited SSL 2/3, TLS 1.0/1.2) Cases for SIM800L Boards
T-Call SIM800C SIM800L_AXP192_VERSION_20200327, SIM800C_AXP192_VERSION_20200609 ❌ (Limited SSL 2/3, TLS 1.0/1.2) Cases for SIM800L Boards
T-Call A7670 T-Call-A7670X-V1-0, T-Call-A7670X-V1-1 ✅ (Full SSL/TLS Support) Cases with Internal GPS/LTE Antenna, Cases with External GPS/LTE Antenna
T-A7670E/G/SA R2 T-A7670X ✅ (Full SSL/TLS Support) Cases with Battery & Internal GPS/LTE Antenna, Cases with Battery & External GPS/LTE Antenna
T-A7670E/G/SA R2 without GPS T-A7670X-NO-GPS ✅ (Full SSL/TLS Support) Cases with Battery
T-A7670G with GPS Shield T-A7670X-GPS-SHIELD ✅ (Full SSL/TLS Support) Cases with Battery & Internal GPS/LTE Antenna, Cases with Battery & External GPS/LTE Antenna

Key Considerations for Device Selection:

  • Cellular Module: SIM800L is a cost-effective option for basic GSM connectivity, while A7670 series modules offer broader network compatibility (including LTE) and often better GPS capabilities. A7670 modules generally provide faster data speeds and more reliable connections, especially in areas with strong LTE coverage.
  • SSL/TLS Support: If security is paramount, especially when transmitting data over cellular networks, devices with A7670 modules are recommended due to their full SSL/TLS support. SIM800L has limitations in modern SSL/TLS protocols, which might be a concern for secure MQTT communication.
  • GPS: For vehicle tracking and location-based automation, choose a board with integrated GPS or the option to add a GPS shield, like the T-A7670G with GPS Shield.
  • Case Availability: 3D-printable cases are available for various T-Call boards, providing protection and a more finished look for your project. Select a case that suits your chosen board and desired mounting location in your vehicle.

Getting Started with OBD2 MQTT

There are two primary methods to get your OBD2 to MQTT bridge up and running: using the pre-built Web Installer for a quick start or building the firmware yourself using PlatformIO for customization and deeper control.

Upload via Web Installer (ESP Web Tools)

For users who prefer a straightforward and hassle-free approach, the Web Installer is the recommended method. It eliminates the need to set up a development environment and compile code.

  1. Visit the Web Installer: Open your web browser and navigate to the OBD2-MQTT Web Installer.
  2. Connect your ESP32: Put your ESP32 device (T-Call or similar) into flashing mode (refer to your board’s documentation for specific instructions, usually involving holding down a button while connecting to USB).
  3. Select Firmware and Flash: The Web Installer will detect your ESP32. Choose the appropriate firmware version for your board (e.g., for T-Call SIM800L or T-Call A7670) and click “Install.” The installer will automatically download and flash the firmware to your ESP32.
  4. Configuration: Once flashed, the ESP32 will create a Wi-Fi access point. Connect to this Wi-Fi network (SSID will be similar to OBD2-MQTT-). Then, open a browser and go to http://192.168.4.1 to access the configuration interface.

Update Settings, Firmware, and Filesystem

After initial flashing via the Web Installer or if you have built your own firmware, you’ll need to configure the device settings. The web interface provided by the OBD2-MQTT firmware makes this process easy.

  1. Connect to the Access Point: As mentioned above, after booting, the ESP32 creates a Wi-Fi access point (SSID: OBD2-MQTT- followed by device MAC address). Connect your computer or phone to this Wi-Fi network.
  2. Access the Configuration UI: Open a web browser and navigate to http://192.168.4.1. This will open the OBD2-MQTT configuration interface.
  3. Adjust Settings: Within the UI, you can configure various settings:
    • Wi-Fi: Set up the ESP32 to connect to your home Wi-Fi network for internet access (if desired, or for initial setup).
    • Mobile/Cellular: Configure APN, username, and password for your SIM card to enable cellular data connectivity.
    • MQTT: Enter your MQTT broker details: server address, port, username, password, and client ID. Ensure these settings match your Mosquitto Broker configuration in Home Assistant.
    • OBD2: Select the type of ELM327 adapter you are using and optionally choose a specific OBD2 protocol for faster initialization. Auto-detect is usually a good starting point.
    • Sleep Settings (for battery-powered devices): If using a battery-powered ESP32 setup, configure sleep timeouts and durations to conserve power when the ignition is off or data is not actively being transmitted.
  4. Reboot or Update: After making changes, click “Save & Reboot” to apply the settings. The UI also provides options to update the firmware and filesystem if newer versions are available.


The settings interface of the OBD2-MQTT firmware, allowing configuration of Wi-Fi, MQTT, OBD2, and other parameters.


The Over-The-Air (OTA) firmware update interface within the OBD2-MQTT web UI, enabling easy firmware and filesystem upgrades.

Build Firmware from Source (PlatformIO)

For users who require custom modifications or want to build the firmware from source code, PlatformIO provides a robust development environment.

  1. Install PlatformIO: Follow the installation instructions on the PlatformIO website. PlatformIO is available as a plugin for VS Code and other popular IDEs, or as a command-line tool.
  2. Clone the Repository: Download the OBD2-MQTT project source code from the GitHub repository. Use git clone https://github.com/adlerre/obd2-mqtt in your terminal.
  3. Build Firmware: Navigate to the cloned repository in your terminal and use the command pio run [-e OPTIONAL ENV]. Replace OPTIONAL ENV with the specific environment for your board (e.g., T-Call-A7670X-V1-0). This command compiles the firmware and generates firmware.bin in the .pio/build/<env> directory.
  4. Build Filesystem (LittleFS): To build the filesystem image (containing web UI and configuration files), use the command pio run --target buildfs [-e OPTIONAL ENV]. This generates littlefs.bin.

Upload Firmware and Filesystem (PlatformIO)

Once you have built the firmware.bin and littlefs.bin files, you can upload them to your ESP32 using PlatformIO.

  1. Upload Firmware: Use the command pio run --target upload -e <YOUR_ENV> to flash the firmware.bin to your ESP32. Replace <YOUR_ENV> with your board’s environment (e.g., T-Call-A7670X-V1-0).
  2. Upload Filesystem: Uploading the filesystem requires a few steps to preserve settings if you have previously configured the device.
     # Connect to the AP of your ESP32 and save current settings
     curl http://192.168.4.1/api/settings -o settings.json
     pio run --target uploadfs -e <YOUR_ENV>
     # After reboot, connect to the AP again
     curl -X PUT -H "Content-Type: application/json" -d @settings.json http://192.168.4.1/api/settings

    These commands first download your current settings, then upload the new filesystem, and finally restore your saved settings. This ensures you don’t lose your Wi-Fi, MQTT, and other configurations after a filesystem update.

Configuring OBD2 MQTT Settings

The settings page accessible via the web interface is the central point for configuring your OBD2 to MQTT bridge. Let’s delve into the key settings you’ll need to adjust.

  • Wi-Fi Settings: Configure the ESP32 to connect to your local Wi-Fi network. This is primarily needed for initial setup and firmware updates if you prefer Wi-Fi over cellular for these tasks.
  • Mobile Settings: Enter the APN (Access Point Name), username, and password provided by your mobile carrier for the SIM card you are using. Correct mobile settings are essential for establishing a cellular data connection.
  • ELM327 Device: Select the type of ELM327 Bluetooth adapter you are using. The firmware may have specific optimizations or compatibility settings for different adapter types. You can also optionally select a specific OBD2 protocol to speed up the initial connection to your car’s ECU (Engine Control Unit). Leaving it on auto-detect usually works well.
  • MQTT Configuration: This is a critical section. You must accurately configure the MQTT settings to connect to your Mosquitto Broker.
    • MQTT Server: Enter the IP address or hostname of your MQTT broker (e.g., your Home Assistant’s IP address if Mosquitto is running on the same machine).
    • MQTT Port: The standard MQTT port is 1883 (or 8883 for secure connections).
    • MQTT Username and Password: If your MQTT broker requires authentication, enter the username and password.
    • MQTT Client ID: This is a unique identifier for your ESP32 device on the MQTT network. It’s usually auto-generated but can be customized.
  • TLS/SSL for SIM800 Devices: It’s important to note the SSL/TLS limitations when using SIM800 modules. They only support older SSL 2/3 and TLS 1.0/1.2 protocols. Modern MQTT brokers often prefer TLS 1.2 or later for security. If using a SIM800L and requiring secure MQTT, ensure your broker is configured to accept these older protocols. A7670 modules provide full support for modern TLS versions, offering better security.
  • Sleep Timeout and Duration (Battery Devices): If you are powering your ESP32 setup with a battery, configure the automatic sleep timeout and sleep duration. The timeout defines the period of inactivity (no data transmission or ignition off) before the device goes to sleep. The sleep duration sets how long the device remains in a low-power sleep state. Proper sleep configuration is crucial for maximizing battery life in wireless OBD2 monitoring applications.

Configuring Sensors and OBD2 Data Points

The OBD2-MQTT firmware comes with a pre-configured standard profile that includes a wide array of commonly used sensors and diagnostic parameters.

Standard Sensors Profile:

The default sensor profile provides real-time data on various aspects of your vehicle’s performance and status, including:

  • Ambient Temperature
  • Battery Voltage
  • Calculated Average Speed
  • Calculated Fuel Consumption
  • Calculated Fuel Consumption per 100km (or MPG)
  • Calculated Driven Distance
  • Check Engine Light Status
  • Engine Coolant Temperature
  • Engine Load
  • Engine Running Status (Ignition)
  • Fuel Level
  • Fuel Rate
  • Intake Air Temperature
  • Speed (Kilometer per Hour or Miles per Hour)
  • Mass Air Flow (MAF)
  • Odometer (Total Vehicle Mileage)
  • Oil Temperature
  • Pedal Position (Throttle/Accelerator)
  • Engine Revolutions Per Minute (RPM)
  • Throttle Position
  • Top Speed Achieved (potentially, depending on vehicle support)

Diagnostic Output (Standard for All Profiles):

In addition to vehicle-specific sensors, all profiles include diagnostic data from the ESP32 and cellular module itself:

  • CPU Temperature (ESP32)
  • Free Memory (ESP32)
  • GPS Location (Latitude/Longitude – only for A76xx modules with GPS)
  • GSM Location (Cellular Network Location)
  • Signal Quality (Cellular Signal Strength)
  • Uptime (Device Runtime)


Example of OBD2 sensor data displayed in a Home Assistant dashboard, showcasing real-time vehicle parameters.

Exploring More Sensor Profiles:

Beyond the standard profile, you can find additional profiles with different sensor configurations in the profiles directory of the GitHub repository. These profiles may be tailored for specific vehicle types or data monitoring needs.

Customizing OBD States and Sensors

For advanced users, the OBD tab in the web interface allows for fine-grained control over the data points being monitored. You can create custom OBD states to read specific PIDs (Parameter IDs) or perform calculations based on existing sensor data.

Types of Custom OBD States:

There are two main types of custom states:

  • READ: Used to directly read data from OBD2 PIDs.
  • CALC: Used to calculate values based on other READ states or predefined parameters.

Both READ and CALC states can be configured to have a valueType of BOOL, FLOAT, or INT, depending on the nature of the data they represent.


The OBD2 tab in the web interface, showing options for configuring custom OBD states, including READ and CALC types.

Options for Custom OBD States:

Each custom state has several configurable options:

  • enabled: Toggles the state on or off.
  • visible: Determines if the state is displayed in the UI and published via MQTT.
  • Measurement: Indicates if the state represents a physical measurement (for Home Assistant sensor device class assignment).
  • Diagnostic: Specifies if the state should be treated as diagnostic information.
  • Interval: Sets the data update interval in milliseconds. Use -1 for one-time updates (e.g., for retrieving static vehicle information).
  • Name: A unique name for the state (alphanumeric and underscores only). This name is used as the MQTT topic and state identifier.
  • Description: A user-friendly description of the state, displayed in Home Assistant as the entity’s friendly name.
  • Icon: The icon to use for the state in Home Assistant (using Material Design Icons – mdi: prefix is not needed).
  • Sensor Device Class: Assigns a Home Assistant sensor device class (e.g., temperature, voltage, speed, distance). Refer to the Home Assistant Sensor Device Class documentation for available options.
  • Unit: The unit of measurement for the state (e.g., °C, V, km/h, mi). Use standard units or custom units as needed.

READ States: Direct OBD2 PID Reading

READ states are configured to fetch specific data points directly from your car’s OBD2 system using PIDs. You can either use pre-defined internal functions for common PIDs or manually specify the PID codes and data processing parameters.

Example: READ State with Internal Function (Battery Voltage)

{ "type": 0, "valueType": "float", "enabled": true, "visible": true, "interval": 30000, "name": "batteryVoltage", "description": "Battery Voltage", "icon": "battery", "unit": "V", "deviceClass": "voltage", "measurement": true, "diagnostic": false, "readFunc": "batteryVoltage" }

In this example, readFunc": "batteryVoltage" tells the firmware to use an internal function to retrieve the battery voltage PID. This simplifies the configuration for common OBD2 parameters.

Example: READ State with Manual PID Configuration (RPM)

{ "type": 0, "valueType": "int", "enabled": true, "visible": true, "interval": 100, "name": "rpm", "description": "Rounds per minute", "icon": "engine", "measurement": true, "diagnostic": false, "pid": { "service": 1, "pid": 12, "numResponses": 1, "numExpectedBytes": 2, "scaleFactor": "1.0 / 4.0", "bias": 0 } }

For more advanced PIDs or when internal functions are not available, you can manually configure the PID parameters:

  • "service": OBD2 service number (typically 1 for standard PIDs).
  • "pid": The PID code in decimal format (not hexadecimal).
  • "numResponses": The number of expected responses from the ECU.
  • "numExpectedBytes": The number of expected data bytes in the response.
  • "scaleFactor": A mathematical expression to scale the raw PID value.
  • "bias": A bias value to add to the scaled value.

CALC States: Derived Values and Calculations

CALC states enable you to create new sensor values by performing calculations based on existing READ states or other CALC states. This is useful for deriving metrics like fuel consumption, distance traveled, or custom performance indicators.

Example: CALC State for Distance Driven

{ "type": 1, "valueType": "float", "enabled": true, "visible": true, "interval": 100, "name": "distanceDriven", "description": "Calculated driven distance", "icon": "map-marker-distance", "unit": "mi", "deviceClass": "distance", "measurement": true, "diagnostic": false, "expr": "$distanceDriven + ($speed.ov + $speed) / 2 / 3600 * ($millis - $distanceDriven.lu) / 1000", "value": { "func": "toMiles" } }

In this example, the expr field contains a mathematical expression to calculate the distance driven. It uses variables like $distanceDriven (previous distance value), $speed (current speed), $speed.ov (previous speed value), $millis (current timestamp), and $distanceDriven.lu (last update timestamp of distance). The value.func": "toMiles" part converts the calculated distance from kilometers to miles.

Expression Syntax and Variables:

Expressions in CALC states support standard mathematical operators (+, -, *, /, %, ^), binary operators (&, |), and references to other states using the $ prefix followed by the state name (e.g., $speed, $engineTemperature).

Available Variables for State References:

  • $millis: Current timestamp in milliseconds.
  • $var: Current value of the referenced state $var.
  • $var.ov: Previous value of state $var.
  • $var.pu: Previous update timestamp of state $var.
  • $var.lu: Last update timestamp of state $var.
  • $var.a, $var.b, $var.c, $var.d: Individual bytes of an INT state (byte access).

Built-in Mathematical and Utility Functions:

Expressions also support a range of built-in functions:

  • Mathematical Functions (single parameter): sin, cos, tan, asin, acos, atan, sinh, cosh, tanh, asinh, acosh, atanh, ln, log, exp, sqrt, sqr, round, int.
  • Mathematical Functions (two parameters): min, max.
  • Utility Functions:
    • afRatio: Air-fuel ratio calculation based on fuel type.
    • density: Fuel density calculation based on fuel type.
    • numDTCs: Number of Diagnostic Trouble Codes (DTCs) – requires calling monitor status first (see default profile example).

Value Formatting:

The value section of a CALC state allows you to format the calculated value using printf-style formatting strings or built-in formatting functions.

Example: Value Formatting with printf and Built-in Functions

  • printf format: "format": "%.2f" (formats a float value to 2 decimal places).
  • Built-in functions:
    • "func": "toBitStr": Formats an integer as a bit string.
    • "func": "toMiles": Converts kilometers to miles.
    • "func": "toGallons": Converts liters to gallons.
    • "func": "toMPG": Converts liters per 100km to miles per gallon.

By leveraging custom OBD states, expressions, and formatting options, you can tailor the OBD2-MQTT system to monitor a wide range of vehicle parameters and create derived data points that are relevant to your specific needs and vehicle.

Conclusion: Unleashing Vehicle Data in Your Smart Home

Integrating OBD2 data into your Home Assistant setup via MQTT opens up a world of possibilities for vehicle monitoring, automation, and smart home integration. From real-time dashboards displaying key vehicle metrics to automated actions triggered by diagnostic events or location data, the “Obd2 Mqtt” bridge empowers you to harness the wealth of information available from your car’s onboard systems.

Whether you are tracking fuel efficiency, monitoring vehicle health, or simply interested in visualizing your driving data within your smart home environment, this project provides a robust and customizable foundation. By following this guide and exploring the advanced configuration options, you can create a truly connected car experience that enhances your smart home ecosystem and provides valuable insights into your vehicle’s operation.

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 *