A cheap ELM327 adapter, Chrome, and two browser APIs are enough to read engine fault codes without installing anything. The protocol part is small; most of the code deals with how real adapters and real browsers misbehave, and that part is what this post covers.
Disclosure: I built diagnost.net, and everything below comes from its client-side code (elm.js, obd.js, kline.js). It is served to every visitor, so you can check any snippet against the live page at https://diagnost.net/connect. The code comments are in Russian; I paraphrase them here.
Browser support, up front
| Adapter type | Works in the browser? | API |
|---|---|---|
| USB ELM327 (CH340 or FTDI chip) | Yes, Chrome / Edge | Web Serial |
| Bluetooth LE ELM327 (BLE 4.0+) | Yes, Chrome / Edge | Web Bluetooth |
| Classic Bluetooth ELM327 (SPP) | No | — |
| WiFi ELM327 | No | — |
Platforms: Windows, macOS, Linux, Android. Safari and Firefox don't expose these APIs. On iPhone, no browser can reach either Bluetooth or USB, because the restriction is in iOS itself, so Chrome on iOS is in the same position as Safari.
One contract, two transports
The page has two transports: elm.js talks to an ELM327 over USB or BLE, and kline.js talks to the car directly over K-line through a dumb USB cable (more on that later). Both expose the same function:
query([sid, pid, ...]) -> Promise<[[0x41, pid, data...], [0x43, ...], ...]>
Frames come back already stripped of headers and checksums. The OBD-II layer (obd.js) — reading stored codes (mode 03), pending codes (07), freeze frame (02), sensors (01), VIN (09), clearing codes (04) — is written once and doesn't know what sits under it. If you build anything on top of serial hardware, this split is worth copying: all of the hardware-specific pain stays below one interface.
Web Serial
The picker needs a fresh user gesture
navigator.serial.requestPort() only opens if it's called during a user activation. That sounds trivial until you do async work first. The page probes the adapter at several baud rates, which can take a while, and if it then decides to show the picker, the gesture has expired and you get a SecurityError.
Two rules came out of that:
// elm.js, start() — simplified
var picked = null;
if (kind === 'usb' && all) {
// call the picker synchronously in the click handler, BEFORE tearing down the old session
try { picked = Promise.resolve(navigator.serial.requestPort()); } catch (e) { picked = Promise.reject(e); }
picked.catch(function () { });
}
var prev = cur ? stopCur() : null;
(prev ? prev.then(function () { return open(kind, all, picked); }) : open(kind, all, picked))
First, when the user clicks "pick another adapter", the picker is requested synchronously, before awaiting anything. Second, if the page discovers late that it needs a picker, it doesn't try to open one; it shows a button, and that new click provides a fresh gesture.
For repeat visits the page calls navigator.serial.getPorts() and opens previously granted ports without asking again. If that list is empty, getPorts() returns quickly enough that requestPort() is still inside the same gesture.
Also note: in Firefox and other browsers with a stubbed implementation, navigator.serial may exist while the picker throws NotSupportedError. Feature-detecting the object isn't enough; handle that error as "not supported".
open() succeeds at any baud rate
This one costs time if you don't know it. port.open({ baudRate }) resolves at any speed, because the USB-serial driver doesn't check it. ELM327 clones differ: most cheap ones run at 38400, firmware 1.5+ and OBDLink at 115200, very old ones at 9600. The only reliable test is to send ATZ and wait for the > prompt.
// elm.js — simplified
var USB_BAUD = [38400, 115200, 9600];
function probePort(port, i, heard) {
if (i >= USB_BAUD.length) return Promise.reject(mkErr(heard ? 'NotElm' : 'NoAnswer', 'no ELM prompt'));
return port.open({ baudRate: USB_BAUD[i] })
.then(function () { var link = serialIo(port); return link.send('ATZ', 2500).then(function () { return link; }); })
.catch(/* close, wait 200 ms, try the next rate */);
}
heard tracks whether anything at all arrived from the port. "Silence" and "something answered, but not an ELM" lead to different messages for the user.
Reading is a plain pump loop on port.readable.getReader(), decoding with TextDecoder and feeding a buffer. One detail matters: everything in the buffer before a new command starts is discarded. Otherwise a late tail from the previous attempt (for example, garbage from the wrong baud rate) gets attributed to the next command, and every response after that is off by one.
Closing a port takes five steps
If a write is still pending, the writer stays locked, releaseLock() doesn't free the stream, port.close() rejects, and the next connection attempt hits the same port as "busy". The close sequence that works:
// elm.js, serialIo().close() — simplified
var CLOSE_STEP_MS = 1500;
function step(name, f) {
return Promise.race([
new Promise(function (ok) { ok(f()); }),
wait(CLOSE_STEP_MS).then(function () { throw new Error('timeout'); })
]).catch(function (e) { bad.push(name + ': ' + ((e && e.message) || e)); });
}
closeP = step('abort', function () { return writer.abort(); }) // drop unsent, reject pending
.then(function () { return step('cancel', function () { return reader.cancel(); }); })
.then(function () { return step('unlockR', function () { reader.releaseLock(); }); })
.then(function () { return step('unlockW', function () { writer.releaseLock(); }); })
.then(function () { return step('close', function () { return port.close(); }); });
Every step has a time cap, because waiting for a flush that never comes is how tabs hang. A failure of port.close() itself is not hidden: the promise rejects, since the port may still be open. The page also releases the port on pagehide.
Error names, and what they actually mean
The DOMException name is the main signal you get, and some names are ambiguous:
| Error | Meaning in practice |
|---|---|
NotFoundError |
User closed the picker or nothing matched. On desktop, often a missing CH340 / CP210x / FTDI driver. |
SecurityError |
Picker called without a live user gesture. |
NotSupportedError |
Stubbed Web Serial (e.g. Firefox). |
InvalidStateError ("already open") |
This page still holds the port from the previous session. Waiting 600 ms and retrying fixes it. |
NetworkError ("Failed to open serial port") |
Port held by another program, cable unplugged, or a driver failure — Chrome reports all three the same way. |
The last row matters for UX. Telling the user "close the other program" on NetworkError would be wrong whenever the cable had simply been pulled, so the page only says "busy" when that's proven (InvalidStateError) and shows a neutral "couldn't open the port" otherwise.
Web Bluetooth
There is no standard BLE serial profile
Every ELM327 BLE clone hides its serial channel behind a vendor service. Web Bluetooth only lets you access services you listed up front, so the list doubles as optionalServices — without it getPrimaryServices() returns nothing:
// elm.js — simplified
var BT_SERVICES = [0xFFF0, 0xFFE0, 0x18F0, 0xFFE5, 0xFFB0,
'6e400001-b5a3-f393-e0a9-e50e24dcca9e' /* + full 128-bit forms of fff0/ffe0/18f0 */];
var req = all
? { acceptAllDevices: true, optionalServices: BT_SERVICES }
: { filters: [{ services: [0xFFF0] }, { services: [0xFFE0] }, { services: [0x18F0] }]
.concat(BT_NAMES.map(function (n) { return { namePrefix: n }; })), // 'OBD', 'ELM', 'Vgate', 'vLinker', ...
optionalServices: BT_SERVICES };
After connecting, the page walks the services (known ELM services first, so it doesn't latch onto some unrelated pair) and picks the first characteristic with notify/indicate plus the first with write/writeWithoutResponse. It writes with writeValueWithResponse if the characteristic supports write, otherwise writeValueWithoutResponse.
If the adapter is paired with the operating system, the browser won't see it in the picker. Users have to remove the pairing first.
getPrimaryServices() can hang forever
Some cheap BLE clones advertise a service that never returns its characteristics (on KONNWEI adapters it's 180A, Device Information). Chrome walks every service on the device, gets stuck on the broken one, and the getPrimaryServices() promise never settles — no resolve, no reject. Without a guard the page showed "Connecting to the car…" forever.
So every BLE step gets its own timeout:
// elm.js — simplified
function stage(p, ms, what) {
return Promise.race([p, new Promise(function (_, reject) {
setTimeout(function () { var e = new Error(what); e.name = 'BtStage'; reject(e); }, ms);
})]);
}
stage(device.gatt.connect(), 20000, 'connect')
.then(function (gatt) { return stage(gatt.getPrimaryServices(), 25000, 'services'); })
// per service: stage(svc.getCharacteristics(), 15000, 'chars').catch(() => {}) — a broken service must not stop the loop
// then: stage(notif.startNotifications(), 12000, 'notify')
A BtStage error gets its own message: the adapter responded but didn't give the browser its service list, so try USB or another adapter.
Late promises from abandoned attempts
Once a stage times out, the underlying gatt.connect() may still resolve later. And for the same adapter, the browser hands back the same BluetoothDevice and the same GATT server object. If the user retried in the meantime, a late disconnect() from the old attempt would kill the new session. The page stores the owner of each GATT server in a WeakMap keyed by device.gatt, and only the latest attempt is allowed to disconnect.
The opposite also needs handling: on every failure after connect(), the page has to call gatt.disconnect() explicitly. Otherwise the tab keeps holding the adapter, and the next attempt, from this page or from another program, can't get it.
A prompt-terminated protocol on top of async I/O
ELM327 speaks text: send 0100\r, receive lines, and a > means "ready for the next command". Sounds like a simple request/response queue. On BLE it isn't, because the notification with the answer can arrive before the writeValue promise resolves. The first version treated > as "done" and sent the next command while the previous write was still in flight. Chrome replied with GATT operation already in progress.
The fix is to queue whole transactions and treat a command as finished only when both events have happened:
// elm.js, elmWaiters() — simplified
var j = {
start: function () {
to = setTimeout(function () { fin(new Error('timeout ' + cmd), null, true); }, ms || 8000);
write(new TextEncoder().encode(cmd + '\r')).then(
function () { wrote = true; if (has) fin(null, ans); }, // write confirmed
function (e) { fin(e, null, true); });
},
got: function (chunk) { if (has) return; has = true; ans = chunk; if (wrote) fin(null, chunk); } // '>' seen
};
The same queue serves both Web Serial (writer.write) and Web Bluetooth (writeValue*), so USB gets the same guarantee for free.
The true passed to fin() on timeout or write failure is the other half. After a timeout you don't know whether the command reached the adapter or whether its answer is still coming; on BLE the write may still be sitting in the stack. If you send the next command, it may receive the previous answer. So the link is marked failed: the active command and the whole queue are rejected with LinkFailed, new send() calls reject immediately, and nothing more is written. Only a new connection recovers. The UI catches LinkFailed, stops live polling, and says the connection was lost. I prefer that to "wait for silence and continue", which gives you data shifted by one response.
Timeouts: 8 s per command, 12 s for long OBD requests, and 30 s for the first 0100, because after ATSP0 the adapter cycles through protocols and that can take up to about 20 s. If the AT commands passed but 0100 timed out, the adapter is alive and the car is silent (ignition off, usually), and the user is told exactly that.
Parse line by line
The response parser splits into lines first, drops status words (SEARCHING..., NO DATA, ERROR, ...), and only then converts hex. On K-line each ECU answers on its own line; on CAN a long response arrives as 0:, 1:, ... chunks preceded by a length line. An early version glued lines together, and on a real BMW E46 the genuine codes P0313, P0171 and P0174 came out as P1301, C3101 and C3443. Wrong parsing here doesn't crash; it produces believable, non-existent fault codes.
Each code is two bytes: the top two bits pick the letter (P, C, B, U), the rest are digits. On CAN there's also a count byte right after the service ID, so the protocol number from ATDPN decides the offset. The page then fetches short descriptions for the found codes and links each one to its own page, like https://diagnost.net/codes/P0420.
One more rule: if the car answered nothing at all, the code list is "not read", not "no faults". A green "all clear" on a silent ECU would be false.
Bit-banging a 5-baud init with setSignals()
Some users plug in a BMW K+DCAN cable instead of an ELM327. It's a transparent USB↔K-line adapter: no AT commands, and since K-line is half-duplex, the cable echoes back every byte you send. ATZ comes back as ATZ at every baud rate. That echo is how the page recognizes the cable.
Web Serial turns out to be enough to drive K-line directly: it supports 10400 baud, and port.setSignals({ break: true }) pulls the line low. ISO 9141-2 starts with the ECU address 0x33 sent at 5 bits per second — 200 ms per bit — using break as the zero level:
// kline.js — simplified
function until(t) { // wait until an absolute performance.now() mark
var lead = t - performance.now() - 8;
return (lead > 0 ? sleep(lead) : Promise.resolve()).then(function () {
while (performance.now() < t) { /* spin the last few ms */ }
});
}
var bits = [0, 1, 1, 0, 0, 1, 1, 0, 0, 1]; // 0x33: start bit, 8 data bits LSB-first, stop bit
var t0 = performance.now() + 20;
bits.forEach(function (bit, i) {
p = p.then(function () { return until(t0 + i * 200); })
.then(function () { return port.setSignals({ break: bit === 0 }); });
});
// then: ECU sends 0x55 sync + two key bytes, we answer with the inverted second key byte,
// ECU answers 0xCC (inverted address)
setTimeout drifts by milliseconds, so the code sleeps until 8 ms before the mark and spins the rest. Per the measurement in the code comments, setSignals costs about 0.3 ms and the spin keeps precision under 1 ms.
Two browser-level surprises from this path:
-
FTDI goes deaf after a break. Through Web Serial, an FTDI chip sometimes stops transmitting after
setSignals({ break }), and occasionally mid-session too. The only cure found is closing and reopening the port, which takes about 12 ms, so the reopen is built into the init itself, at the start of the stop bit. A watchdog sends an echo probe before requests after idle periods and reopens or re-initializes when the echo is missing. - "End of response" is a timeout. There's no prompt on raw K-line; a response ends after 150 ms of silence. The echo of your own request arrives first and gets trimmed byte by byte.
ISO 9141-2 via 5-baud init was verified on a real E46. The KWP2000 fast-init path exists but hasn't been tested on a car yet. All of this only applies to K-line cars, roughly pre-2007; D-CAN over a browser serial port isn't possible.
Pitfalls, collected
-
open()resolves at any baud rate; only a protocol-level handshake proves the speed. - The picker dies with
SecurityErrorafter async work; call it synchronously or offer a new button. -
NetworkErroronopen()doesn't mean "busy";InvalidStateErrormeans your own page still holds the port. - A double click during connect opened the same port twice, got "busy", and the failed attempt's cleanup closed the working link. Disable the buttons while connecting and fully release the previous session first.
- A pending write blocks
port.close(); abort the writer first and cap every close step. - Users may have several granted ports (for example, a K+DCAN cable and a real ELM327). The page tries them all and reports the most informative error: "not an ELM" over "busy" over "failed to open" over "silent".
- BLE: list your services in
optionalServices, put a timeout on every GATT step, and never trust a late promise from an abandoned attempt. - BLE: the answer can beat the write confirmation; wait for both before sending the next command.
- A paired BLE adapter is invisible to the browser.
- Parse device output line by line; a one-byte shift produces plausible, wrong data.
What a browser can't do
- WiFi adapters. A web page can't open a raw network socket to a device. This applies to every browser.
- Classic Bluetooth (SPP). Web Bluetooth is BLE only; a classic ELM327 never shows up in the picker.
- iOS. No Web Serial, no Web Bluetooth, in any browser.
- Anything beyond standard OBD-II. The page reads what the OBD-II modes expose: engine codes, freeze frame, sensors, readiness monitors, VIN. Polling every control unit (ABS, airbags, transmission, body) is done by a separate Windows program, which also handles WiFi and classic Bluetooth adapters.
Takeaways
Web Serial and Web Bluetooth are usable for real hardware today, in Chromium browsers. Budget most of your time for the edges: which errors are ambiguous, which promises never settle, and which events arrive out of order. One design decision I would repeat: making error types specific — "adapter silent", "car silent", "not an ELM", "port held by this page" — because each one tells the user to do something different.
Top comments (0)