DEV Community

Cover image for obd2_kit: talk to ELM327 OBD-II adapters from Dart over any transport
Abdeldjalil Chougui
Abdeldjalil Chougui

Posted on Originally published at abdeldjalilchougui.biz

obd2_kit: talk to ELM327 OBD-II adapters from Dart over any transport

Reading data from a car looks simple on paper. You plug a small ELM327 adapter into the OBD-II port, send 010C, and get the engine speed back. In practice the adapter is a text terminal with its own habits: it echoes your commands, prints SEARCHING... while it looks for the bus, answers in several small chunks, and reports errors as plain words such as NO DATA or BUS BUSY. Replies can come from several ECUs at once, and a long reply such as the VIN is split over several frames.

On top of that, the link to the adapter is different in every app: Bluetooth SPP, BLE UART, Wi-Fi TCP or USB serial.

obd2_kit is a Dart library that handles the protocol side and leaves the link to you. It works over any byte transport and covers the adapter session, the SAE J1979 services, multi-ECU and multi-frame replies, and live polling.

What it does

The ELM327 session. Elm327 runs the init sequence (ATZ, ATE0, ATL0, ATS0, ATH1 or ATH0, ATAT1, ATSP0), then sends a 0100 request that runs the protocol search, and reads the protocol the adapter found with ATDPN. It waits for the > prompt, also when a reply arrives in many small chunks, and removes the command echo, SEARCHING... and BUS INIT: ...OK. Error replies become an ElmErrorException carrying an ElmError value, so you match on a type instead of comparing strings.

Commands go through a FIFO queue that sends one at a time. Each command has a timeout and can take an ObdCancelToken. A queued command that is cancelled is never sent. A running command that times out or is cancelled is interrupted: the session sends one byte, waits for the prompt, and then goes on, so a late reply is never matched to the next command.

The J1979 services. ObdClient covers these modes:

  • Mode 01, current data: readPid returns the reply from the lowest ECU id, readPidAll returns the replies from every ECU, and supportedPids walks the bitmaps at 00, 20, 40, 60, 80, A0 and C0.
  • Mode 02, freeze frame, including PID 02 (the code that stored the frame).
  • Mode 03 stored codes, Mode 07 pending codes and Mode 0A permanent codes, grouped by ECU.
  • Mode 04, clear codes. It runs only with clearDtcs(confirm: true).
  • Mode 09: VIN, calibration IDs, ECU name and the supported PIDs.

Frames. parseObdLines reads replies with headers on: 11-bit CAN (7E8 ...), 29-bit CAN, and the three header bytes plus checksum of ISO 9141-2, ISO 14230-4 KWP and SAE J1850. Replies from several ECUs are separated by their id. It reassembles ISO 15765-2 single, first and consecutive frames per ECU and checks the sequence numbers, including the wrap from F to 0. With headers off, it reads the ELM's own multi-frame layout. Replies are parsed with spaces on or off.

Typed PID values. decodePid returns a NumericValue (a value and an ObdUnit), a MonitorStatusValue, an ObdStandardValue, a SupportedPidsValue, a DtcValue, or a RawValue for PIDs the package does not decode. The decoded list includes PID 01 (MIL, code count and readiness monitors), engine load, coolant temperature, fuel trims, RPM, speed and many more; the README has the full list.

Trouble codes. Dtc decodes and parses P, C, B and U codes such as P0133, sorts them into generic, manufacturer or reserved using the SAE J2012 ranges, and gives the P0 subsystem group (misfire, fuel and air metering, and so on).

Live monitoring. ObdMonitor polls a set of PIDs, each at its own interval, and emits a Stream<PidReading>. Only one request is in flight at a time. The most overdue PID goes next, and ties go round-robin, so every PID gets its turn when the adapter is slower than the rates you asked for. Request errors are emitted as stream errors and polling continues.

How to use it

Add it from GitHub:

dependencies:
  obd2_kit:
    git: https://github.com/AbdeldjalilChougui/obd2_kit
Enter fullscreen mode Exit fullscreen mode

The package ships a TCP transport for Wi-Fi dongles in package:obd2_kit/io.dart. Most of them listen on 192.168.0.10:35000:

import 'package:obd2_kit/io.dart';
import 'package:obd2_kit/obd2_kit.dart';

Future<void> main() async {
  final transport = await TcpObdTransport.connect('192.168.0.10', 35000);
  final elm = Elm327(transport);
  final info = await elm.initialize(); // headers on, automatic protocol
  print('${info.banner} on ${info.protocol?.description}');

  final obd = ObdClient(elm);
  final rpm = await obd.readPid(Pids.engineRpm);
  print(rpm.value); // e.g. "1726 rpm"

  for (final dtc in (await obd.readStoredDtcs()).all) {
    print('${dtc.code} ${dtc.category.name}');
  }
  print('VIN ${await obd.readVin()}');

  final monitor = ObdMonitor(obd, const [
    PidSchedule(Pids.engineRpm, Duration(milliseconds: 200)),
    PidSchedule(Pids.coolantTemperature, Duration(seconds: 5)),
  ]);
  final sub = monitor.readings.listen((r) => print(r));
  await Future<void>.delayed(const Duration(seconds: 10));
  await sub.cancel();
  await elm.close();
}
Enter fullscreen mode Exit fullscreen mode

For Bluetooth, BLE or USB, you implement ObdTransport. It is a small interface with three members: input, write and close.

class StreamTransport implements ObdTransport {
  StreamTransport(this.input, this._sink);

  @override
  final Stream<List<int>> input;
  final StreamSink<List<int>> _sink;

  @override
  Future<void> write(List<int> bytes) async => _sink.add(bytes);

  @override
  Future<void> close() async => _sink.close();
}
Enter fullscreen mode Exit fullscreen mode

Clearing codes needs an explicit confirmation, and clearDtcs() throws an ArgumentError without it. That is on purpose: clearing turns off the MIL and resets every readiness monitor, and the vehicle can then fail an emissions inspection until it has been driven through its monitors again.

Clone adapters

Most cheap adapters are ELM327 clones, and the session handles a list of their known behaviours. Some examples from the README:

  • A clone that reports v1.5, a version Elm Electronics never released, sets ElmInfo.isKnownCloneVersion to true. A clone can also report a real version, so false proves nothing.
  • ATAT1 and ATS0 are optional in initialize(), because some clones answer ? to them. readVoltage() returns null when ATRV is answered with ?.
  • NUL bytes and garbage around ATZ are removed, and ATZ is retried once after a timeout, for adapters that drop the first command.
  • The echo line is removed from every reply, also when the adapter keeps echoing after ATE0.
  • ObdMonitor(minGap: ...) adds a pause between requests for clones that misbehave when commands follow each other with no pause.

Things to know

  • No DTC descriptions are included. The README explains why: no list of generic P0xxx description texts was found under a licence compatible with MIT. The package decodes codes and sorts them by category, and you plug in texts you are licensed to use with DtcDescriptionProvider or MapDtcDescriptions.
  • One PID per Mode 01 request. CAN allows up to six, but that is not used, for compatibility with legacy buses and clones.
  • Legacy protocols are supported only as far as the ELM327 shows them. The last byte is treated as the checksum and removed without being checked.
  • Headers off means replies from several ECUs cannot be told apart. The default is headers on.
  • Covered modes are 01, 02, 03, 04, 07, 09 and 0A. Modes 05, 06 and 08, and manufacturer-specific services, are not covered.
  • Some PIDs stay raw. Fuel system status (PID 03), the oxygen sensor PIDs (14 to 1B) and other PIDs outside the decoded list return a RawValue.
  • What was tested. The tests use a scripted fake adapter whose replies are modelled on the datasheet examples. The package has not been tested against every clone.

The package contains no copied dataset. The PID formulas, the PID 1C labels and the DTC ranges were written from the public standards listed in the README (the ELM327 datasheet, SAE J1979, SAE J2012 and ISO 15765).

Why I built it

An app that reads a car needs two separate things: a link to the adapter, and code that understands what the adapter says. The second part is the same for every app, and it is where the details pile up: the prompt, the echo, the clone quirks, multi-frame replies, several ECUs answering one request, a timed-out command whose late reply must not be taken for the next one.

I wanted that part as one library that does not care how the bytes travel. With ObdTransport as the only contact point, the same session, parser and polling scheduler work over Wi-Fi, Bluetooth, BLE or USB, and the whole thing can be tested with a scripted fake adapter instead of a car.

Get the code

The source, the full PID list, the clone quirk table and the tests are on GitHub: https://github.com/AbdeldjalilChougui/obd2_kit. It's MIT licensed. Issues and pull requests are welcome.


Originally published at abdeldjalilchougui.biz.

Top comments (0)