Skip to content

Repository files navigation

react-native-obd2-reader

npm version npm downloads license GitHub

A high-performance, full-featured OBD-II (On-Board Diagnostics) reader library for React Native (Android & iOS). Connects to ELM327 Bluetooth adapters (RFCOMM/SPP) to read live sensor gauges, scan & clear Diagnostic Trouble Codes (DTCs), record trip analytics, and execute custom vehicle PIDs.

Replicates and extends all non-UI capabilities from the open-source Java android-obd-reader / obd-java-api into an idiomatic TypeScript/JavaScript API.


Features

  • 🏎️ Live Engine Diagnostics: Real-time polling for Speed, RPM, Coolant Temp, Engine Load, MAF, Throttle, Fuel Levels, Battery Voltage, Runtime, and 40+ standard Mode 01 PIDs.
  • 🛠️ Diagnostic Trouble Codes (DTCs): Read confirmed (Mode 03), pending (Mode 07), and permanent (Mode 0A) trouble codes. Includes built-in dictionary with 5,000+ standard SAE definitions (P0xxx, P1xxx, P2xxx, Bxxxx, Cxxxx, Uxxxx).
  • 🧹 Clear Trouble Codes: Reset ECU trouble codes and turn off the Check Engine Light (MIL) via Mode 04 (04 / AT PC).
  • ELM327 Protocol Auto-Configuration: Automated handshake and protocol selection (ATZ $\to$ ATE0 $\to$ ATL0 $\to$ ATS0 $\to$ ATST $\to$ ATSP).
  • 🔄 Built-in Mock Gateway: Simulator mode for building and testing React Native UI on emulators without physical OBD-II hardware.
  • 📊 Trip Log & CSV Exporter: Track max speed, max RPM, duration, and export sensor logs to CSV format identical to LogCSVWriter.
  • 📐 Metric & Imperial Support: Automatic conversion between km/h $\leftrightarrow$ mph, °C $\leftrightarrow$ °F, kPa $\leftrightarrow$ PSI, L/h $\leftrightarrow$ GPH.
  • 🧩 Custom PID Engine: Easily create custom PID commands with custom byte formulas for manufacturer-specific ECUs (Toyota, Ford, GM, VW, BMW, etc.).

Installation

Install from npm:

npm install react-native-obd2-reader
# or
yarn add react-native-obd2-reader

Android Setup

Add Bluetooth permissions to your android/app/src/main/AndroidManifest.xml:

<!-- Legacy Bluetooth permissions for Android 11 (API 30) and below -->
<uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<!-- Android 12+ (API 31+) Bluetooth permissions -->
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" android:usesPermissionFlags="neverForLocation" />

Note on Android 12+ (API 31+): Ensure your app requests runtime permission for PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT and PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN before connecting.


Quick Start

1. Discover Paired Bluetooth Devices & Connect

import { NativeBridge, OBDGateway } from 'react-native-obd2-reader';

// 1. Get list of bonded ELM327 Bluetooth devices
const devices = await NativeBridge.getBondedDevices();
console.log('Paired devices:', devices);

const elmDevice = devices.find(
  (d) => d.name.toLowerCase().includes('obd') || d.name.toLowerCase().includes('elm')
);

if (elmDevice) {
  // 2. Instantiate gateway
  const gateway = new OBDGateway({
    bluetoothDeviceAddress: elmDevice.address,
    protocol: 'AUTO',       // Automatic protocol selection
    useImperial: false,     // true for mph, °F, PSI
    pollIntervalMs: 1000,   // Polling frequency in ms
  });

  // Listen to connection status updates
  gateway.onStatus((event) => {
    console.log(`Status: ${event.status} - ${event.message}`);
  });

  // Listen to live polled sensor data
  gateway.onData((result) => {
    console.log(`${result.name}: ${result.formatted} (Raw: ${result.rawResponse})`);
  });

  // 3. Connect & start auto-polling
  await gateway.connect();
  gateway.startPolling();
}

2. Read Specific PIDs On-Demand

import {
  OBDGateway,
  RPMCommand,
  SpeedCommand,
  EngineCoolantTemperatureCommand,
  VinCommand,
  ModuleVoltageCommand,
} from 'react-native-obd2-reader';

const gateway = new OBDGateway({ bluetoothDeviceAddress: '00:1D:A5:00:00:00' });
await gateway.connect();

// Read Engine RPM
const rpm = await gateway.executeCommand(new RPMCommand());
console.log('RPM:', rpm.value, rpm.unit); // 2150 RPM

// Read Vehicle Speed
const speed = await gateway.executeCommand(new SpeedCommand());
console.log('Speed:', speed.value, speed.unit); // 85 km/h

// Read Coolant Temperature
const coolant = await gateway.executeCommand(new EngineCoolantTemperatureCommand());
console.log('Coolant:', coolant.formatted); // 88°C

// Read VIN (Vehicle Identification Number)
const vin = await gateway.executeCommand(new VinCommand());
console.log('VIN:', vin.value); // 1HGCR2F83HA000001

3. Scan & Clear Diagnostic Trouble Codes (DTCs)

import { OBDGateway } from 'react-native-obd2-reader';

const gateway = new OBDGateway({ bluetoothDeviceAddress: '00:1D:A5:00:00:00' });
await gateway.connect();

// 1. Scan DTCs
const { confirmed, pending } = await gateway.readTroubleCodes();

console.log('Confirmed Trouble Codes:');
confirmed.value.forEach((dtc) => {
  console.log(`[${dtc.code}] (${dtc.type}): ${dtc.description}`);
  // Example: [P0300] (Powertrain): Random/Multiple Cylinder Misfire Detected
});

// 2. Clear Trouble Codes & Reset Check Engine Light (MIL)
const resetResult = await gateway.clearTroubleCodes();
console.log('Reset status:', resetResult.formatted);

4. Simulator / Mock Mode (No Hardware Required)

You can build and test your entire user interface without an OBD-II adapter by enabling mockMode: true:

import { OBDGateway } from 'react-native-obd2-reader';

const gateway = new OBDGateway({
  mockMode: true, // Enables full ELM327 simulation
  pollIntervalMs: 800,
});

gateway.onData((res) => {
  // Receives realistic simulated RPM, speed, temperature, MAF, and load
  console.log(`[SIMULATOR] ${res.name}: ${res.formatted}`);
});

await gateway.connect();
gateway.startPolling();

Interactive Mock CLI (Terminal Testing)

You can launch the interactive mock console directly from your terminal to test any command or view live streams:

npm run cli
# or
npx react-native-obd2-reader-cli

Inside the CLI prompt:

obd-mock> rpm
  Command:     01 0C (ENGINE_RPM)
  Raw Response: 41 0C 1D 88
  Parsed Value: 1890
  Formatted:    1890RPM

obd-mock> dtc
  Trouble Codes Breakdown:
    • [P0300] (Powertrain): Random/Multiple Cylinder Misfire Detected
    • [P0171] (Powertrain): System Too Lean

obd-mock> poll     # Starts live streaming
obd-mock> stop     # Stops live streaming

5. Custom PIDs & Formulas

Define custom PIDs for proprietary manufacturer parameters (e.g. transmission fluid temp, hybrid battery cell voltages):

import { OBDGateway, CustomObdCommand } from 'react-native-obd2-reader';

const transmissionTempCmd = new CustomObdCommand({
  command: '22 1E 01', // Mode 22 enhanced PID
  name: 'TRANS_TEMP',
  unit: '°C',
  calculationFn: (bytes, raw) => {
    // Custom formula: (Byte D * 256 + Byte E) / 10 - 40
    if (bytes.length >= 5) {
      return ((bytes[3] * 256) + bytes[4]) / 10 - 40;
    }
    return 0;
  },
  formattedFn: (value, unit) => `${value.toFixed(1)}${unit}`,
});

const result = await gateway.executeCommand(transmissionTempCmd);
console.log('Transmission Temp:', result.formatted);

6. Trip Analytics & CSV Recording

import { TripLog, CSVLogger, OBDGateway } from 'react-native-obd2-reader';

const tripLog = TripLog.getInstance();
const csvLogger = new CSVLogger();

// Start a new trip
const currentTrip = tripLog.startTrip();

const gateway = new OBDGateway({ bluetoothDeviceAddress: '...' });
gateway.onReading((reading) => {
  // Accumulate reading into CSV format
  csvLogger.addReading(reading);
});

// After driving:
const completedTrip = tripLog.endTrip();
console.log('Max Speed:', completedTrip.getSpeedMax(), 'km/h');
console.log('Max RPM:', completedTrip.getEngineRpmMax());
console.log('Total Runtime:', completedTrip.getEngineRuntime());

// Export CSV content
const csvData = csvLogger.getCSVContent();

Supported OBD-II Commands & PIDs

Command Class Mode / PID Description Metric Unit Imperial Unit
RPMCommand 01 0C Engine RPM RPM RPM
SpeedCommand 01 0D Vehicle Speed km/h mph
OdometerCommand 01 A6 Total Vehicle Odometer Distance km mi
EngineCoolantTemperatureCommand 01 05 Engine Coolant Temp °C °F
OilTempCommand 01 5C Engine Oil Temperature °C °F
AirIntakeTemperatureCommand 01 0F Intake Air Temp (IAT) °C °F
AmbientAirTemperatureCommand 01 46 Ambient Air Temperature °C °F
ChargeAirCoolerTempCommand 01 76 Charge Air Cooler Temp (CACT) °C °F
ExhaustGasTempBank1Command 01 77 Exhaust Gas Temperature Bank 1 (EGT) °C °F
ExhaustGasTempBank2Command 01 78 Exhaust Gas Temperature Bank 2 (EGT) °C °F
CatalystTempB1S1Command 01 3C Catalyst Temp (Bank 1, Sensor 1) °C °F
TransmissionActualGearCommand 01 A4 Current Gear & Actual Gear Ratio string string
BoostPressureCommand 01 70 Turbo / Supercharger Boost Pressure kPa PSI
TurbochargerRpmCommand 01 74 Turbocharger RPM RPM RPM
DpfDifferentialPressureCommand 01 79 DPF Differential Pressure kPa PSI
DpfTemperatureCommand 01 7A Diesel Particulate Filter (DPF) Temp °C °F
DefLevelCommand 01 85 Diesel Exhaust Fluid (DEF/AdBlue) Level % %
DefConcentrationCommand 01 9B DEF (AdBlue) Concentration % % %
ExhaustFlowRateCommand 01 9E Engine Exhaust Flow Rate kg/h lb/h
ActualEngineTorqueCommand 01 62 Actual Engine Torque % % %
DriverDemandTorqueCommand 01 61 Driver's Demand Engine Torque % % %
EngineReferenceTorqueCommand 01 63 Engine Reference Torque Nm lb-ft
EngineFrictionTorqueCommand 01 8E Engine Friction Percent Torque % %
LoadCommand 01 04 Calculated Engine Load % %
AbsoluteLoadCommand 01 43 Absolute Load Value % %
ThrottlePositionCommand 01 11 Throttle Position % %
RelativeThrottlePositionCommand 01 45 Relative Throttle Position % %
MassAirFlowCommand 01 10 Mass Air Flow Rate (MAF) g/s g/s
FuelLevelCommand 01 2F Fuel Tank Level % %
FuelTrimCommand 01 06-09 Short / Long Term Fuel Trim % %
FuelPressureCommand 01 0A Fuel Pressure (Gauge) kPa PSI
FuelRailPressureCommand 01 23 Fuel Rail Pressure (Direct Injection) kPa PSI
FuelRailPressureVacuumCommand 01 22 Fuel Rail Pressure (Vacuum) kPa PSI
IntakeManifoldPressureCommand 01 0B Intake Manifold Absolute Pressure (MAP) kPa PSI
BarometricPressureCommand 01 33 Absolute Barometric Pressure kPa PSI
TimingAdvanceCommand 01 0E Timing Advance ° °
FuelInjectionTimingCommand 01 5D Fuel Injection Timing ° °
RuntimeCommand 01 1F Time Since Engine Start s (hh:mm:ss) s (hh:mm:ss)
DistanceMILOnCommand 01 21 Distance with MIL On km mi
DistanceSinceCodesClearedCommand 01 31 Distance Since Codes Cleared km mi
DtcNumberCommand 01 01 MIL status & DTC Count count count
ModuleVoltageCommand 01 42 ECU Module Voltage V V
ReadVoltageCommand AT RV Adapter / Battery Voltage V V
AirFuelRatioCommand 01 44 Air-Fuel Ratio (AFR) :1 :1
EquivalentRatioCommand 01 44 Equivalence Ratio (Lambda) λ λ
FindFuelTypeCommand 01 51 Fuel Type (Gasoline, Diesel, Hybrid, etc.) string string
ConsumptionRateCommand 01 5E Engine Fuel Rate L/h gal/h
CylinderFuelRateCommand 01 A2 Cylinder Fuel Rate mg/stroke mg/stroke
CommandedEGRCommand 01 2C Commanded EGR % %
EGRErrorCommand 01 2D EGR Error % %
EthanolPercentageCommand 01 52 Ethanol Fuel % % %
HybridBatteryRemainingCommand 01 5B Hybrid Battery Life Remaining % %
O2SensorVoltageCommand 01 14-1B Oxygen Sensor Voltage & Trim (B1-B2) V V
O2WidebandVoltageCommand 01 24-2B Wideband O2 Lambda & Voltage ratio ratio
O2WidebandCurrentCommand 01 34-3B Wideband O2 Lambda & Current mA mA
FreezeFrameDtcCommand 02 02 Freeze Frame Trigger DTC string string
OnBoardMonitoringCommand 06 00 Mode 06 On-Board Monitoring Tests Array Array
TroubleCodesCommand 03 Diagnostic Trouble Codes (Confirmed) Array Array
PendingTroubleCodesCommand 07 Diagnostic Trouble Codes (Pending) Array Array
PermanentTroubleCodesCommand 0A Diagnostic Trouble Codes (Permanent) Array Array
ResetTroubleCodesCommand 04 Clear DTCs and Reset MIL boolean boolean
VinCommand 09 02 Vehicle Identification Number (VIN) string string
CalibrationIdCommand 09 04 Calibration ID (CALID) string string
CalibrationVerificationNumberCommand 09 06 Calibration Verification Numbers (CVN) string string
EcuNameCommand 09 0A ECU Name string string

Supported OBD-II Protocols

  • AUTO: Automatic protocol search (Recommended)
  • SAE_J1850_PWM: 41.6 kbaud (Ford)
  • SAE_J1850_VPW: 10.4 kbaud (GM)
  • ISO_9141_2: 5 baud init, 10.4 kbaud (Chrysler, European, Asian)
  • ISO_14230_4_KWP_5BAUD: KWP2000 (5 baud init)
  • ISO_14230_4_KWP_FAST: KWP2000 (fast init)
  • ISO_15765_4_CAN_11BIT_500K: CAN (11 bit ID, 500 kbaud)
  • ISO_15765_4_CAN_29BIT_500K: CAN (29 bit ID, 500 kbaud)
  • ISO_15765_4_CAN_11BIT_250K: CAN (11 bit ID, 250 kbaud)
  • ISO_15765_4_CAN_29BIT_250K: CAN (29 bit ID, 250 kbaud)
  • SAE_J1939_CAN: Commercial vehicle CAN

License

Apache License 2.0 - See LICENSE for details.