Examples
Runnable recipes. Each one uses only exported functions. A missing field is never shown as 0.
Shared rules:
- Read
valueonly whenstatus === 'ok'(Dart:reading.ok). close()in afinally, including whenconnectsucceeded and a later call threw.- Call
dtc.read()only whilestateisready. Stoplive()first. - Fault codes are beta. Show
outcomeas-is. Do not clear them.
Key ON, engine off, cable on the diagnostic connector. Install steps are on the JavaScript and Dart quickstarts.
Node CSV logger
npm i @smongrot/sdk serialport
node logger.mjs /dev/cu.usbserial-XXXX
// logger.mjs
import { createWriteStream } from 'node:fs';
import { SerialPort } from 'serialport';
import { connect, fromSerialPort } from '@smongrot/sdk';
const path = process.argv[2];
if (!path) {
console.log('usage: node logger.mjs <port>');
for (const p of await SerialPort.list()) console.log(' ', p.path, p.manufacturer ?? '');
process.exit(1);
}
const port = new SerialPort({
path,
baudRate: 10400,
dataBits: 8,
stopBits: 1,
parity: 'none',
autoOpen: false,
});
const t = await fromSerialPort(port);
const out = createWriteStream('live.csv');
out.write('t_ms,profile,rpm,ect,eot,batt\n');
const t0 = Date.now();
let n = 0;
let s;
const cell = (f, key) => (f.fields[key]?.status === 'ok' ? f.fields[key].value : '');
try {
s = await connect(t);
for await (const f of s.live()) {
out.write(`${Date.now() - t0},${f.profile},${cell(f, 'rpm')},${cell(f, 'ect')},${cell(f, 'eot')},${cell(f, 'batt')}\n`);
if (++n === 50) break;
}
} finally {
if (s) await s.close();
else await t.close();
out.end();
}
ect and eot are different fields. One of them is empty on any given profile. An empty cell means absent or invalid, not zero. The npm package also ships examples/node-serialport.mjs, which prints a few frames and the fault codes.
Browser live gauge
Desktop Chrome or Edge. The page must be https or localhost. requestPort() has to run inside the click.
<!doctype html>
<meta charset="utf-8">
<button id="go">Connect</button>
<button id="stop">Stop</button>
<p id="rpm">—</p>
<script type="module">
import { connect, openWebSerial } from '@smongrot/sdk';
document.querySelector('#go').onclick = async () => {
const ac = new AbortController();
document.querySelector('#stop').onclick = () => ac.abort();
const port = await navigator.serial.requestPort();
const s = await connect(await openWebSerial(port));
try {
for await (const f of s.live({ signal: ac.signal })) {
const rpm = f.fields.rpm;
document.querySelector('#rpm').textContent =
rpm?.status === 'ok' ? String(Math.round(rpm.value)) : '—';
}
} finally {
await s.close();
}
};
</script>
Aborting the signal ends the loop without throwing. close() then releases the port. Serve the file from a bundler that resolves @smongrot/sdk. Do not put an API key in this page.
Flutter desktop live screen
flutter pub add smongrot_sdk smongrot_sdk_libserialport
import 'package:flutter/material.dart';
import 'package:smongrot_sdk/smongrot_sdk.dart';
import 'package:smongrot_sdk_libserialport/smongrot_sdk_libserialport.dart';
void main() {
final ports = SerialPort.availablePorts;
runApp(MaterialApp(
home: ports.isEmpty
? const Scaffold(body: Center(child: Text('No serial port')))
: LiveScreen(portName: ports.first),
));
}
class LiveScreen extends StatefulWidget {
const LiveScreen({super.key, required this.portName});
final String portName;
@override
State<LiveScreen> createState() => _LiveScreenState();
}
class _LiveScreenState extends State<LiveScreen> {
String _rpm = '—';
@override
void initState() {
super.initState();
_run();
}
Future<void> _run() async {
final t = LibSerialPortTransport.open(widget.portName);
Session? s;
try {
s = await connect(t);
await for (final f in s.live()) {
if (!mounted) break;
final rpm = f.fields['rpm']!;
setState(() => _rpm = rpm.ok ? rpm.value!.round().toString() : '—');
}
} finally {
if (s != null) {
await s.close();
} else {
await t.close();
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(body: Center(child: Text(_rpm, style: const TextStyle(fontSize: 64))));
}
}
LibSerialPortTransport.open is synchronous and throws PORT_OPEN (a SmongrotException) when the path cannot be opened. rpm.ok is status == 'ok'. Leaving the screen makes mounted false; the next frame breaks the loop and finally closes the port.
Android OTG
flutter pub add smongrot_sdk smongrot_sdk_usb_serial
Call this from a button. create() shows the USB permission dialog and returns null if the rider denies it.
import 'package:smongrot_sdk/smongrot_sdk.dart';
import 'package:smongrot_sdk_usb_serial/smongrot_sdk_usb_serial.dart';
Future<void> readOnce() async {
final devices = await UsbSerial.listDevices();
if (devices.isEmpty) return;
final port = await devices.first.create();
if (port == null) return;
final t = await UsbSerialTransport.open(port);
Session? s;
try {
s = await connect(t);
final id = await s.identify();
print(id.ecmId ?? '—');
final f = await s.live().first;
final rpm = f.fields['rpm']!;
print(rpm.ok ? rpm.value : '—');
} finally {
if (s != null) {
await s.close();
} else {
await t.close();
}
}
}
live().first cancels the stream after one frame, which returns the session to ready. The wake on this adapter is the short low-baud pulse unless you pass atomicWake:
await UsbSerialTransport.open(port, atomicWake: myFtdiBitBang);
myFtdiBitBang is Future<void> Function(Duration low) and must hold K-Line LOW for low (70 ms) on the chip.
Reading fault codes (beta)
Stop live data first. Only Keihin payloads are decoded. beta is always true. critical is true for codes 12, 33 and 52 — the spec's note for those is that the engine may not run right and should be checked soon. benchConfirmed is true only for 7-1 and 8-1. Anything else is a hint. meaning is null when the label is not in the table.
async function showFaults(s) {
// s.state must be 'ready'. Do not call this from inside live().
const dtc = await s.dtc.read();
if (dtc.outcome !== 'faults') {
console.log(dtc.outcome); // clean | unreadable | failed
return;
}
for (const c of dtc.codes) {
console.log(c.label, c.meaning ?? '', c.critical ? 'critical' : '', c.benchConfirmed ? 'bench' : 'hint');
}
}
Future<void> showFaults(Session s) async {
final dtc = await s.dtc.read();
if (dtc.outcome != 'faults') {
print(dtc.outcome);
return;
}
for (final c in dtc.codes) {
print('${c.label} ${c.meaning ?? ''} ${c.critical ? 'critical' : ''} ${c.benchConfirmed ? 'bench' : 'hint'}');
}
}
unreadable means the bytes did not parse, or the box is not Keihin and the payload was not all zeros. Show that word. Do not replace it with an empty list. There is no clear function.
dtc.read(maker: 'keihin') (Dart) or dtc.read({ maker: 'keihin' }) (JS) overrides the hint. Use it only when you know the maker. A wrong hint on a Shindengen box will try the Keihin decoder and likely return unreadable.
Model name from the API key
The key is free. One session calls the API at most once, inside the first identify(). Live data never uses the network. transport below is any open Transport from the recipes above.
import { connect, smongrotApi } from '@smongrot/sdk';
const api = smongrotApi({
apiKey: process.env.SMONGROT_API_KEY,
onError: (e) => console.warn(e.code, e.message),
});
const s = await connect(transport, { lookupModel: api.lookupModel });
try {
const id = await s.identify();
console.log(id.ecmId); // from the box, offline
console.log(id.model?.model ?? '—'); // may be Thai; null if no key, 404, or offline
console.log(id.model?.maker, id.model?.ecuCode);
} finally {
await s.close();
}
import 'dart:io';
import 'package:smongrot_sdk/smongrot_sdk.dart';
final key = Platform.environment['SMONGROT_API_KEY'];
final api = key == null ? null : SmongrotApi(apiKey: key, onError: (e) => print('${e.code} ${e.message}'));
final s = await connect(transport, lookupModel: api?.lookupModel);
try {
final id = await s.identify();
print(id.ecmId);
print(id.model?.model ?? '—');
} finally {
await s.close();
api?.close();
}
In a browser, do not ship the key. Run the GET on your server and pass your own lookupModel(ecmId) that returns a ModelInfo or null. Any function with that shape works. See Identify and API key.
No bike
FakeEcuTransport answers scripted frames and does not sleep. The default bench trace identifies as 0104780D01. Add the live-table reply or live() throws LIVE_UNSUPPORTED.
import { connect, FakeEcuTransport } from '@smongrot/sdk';
const fake = new FakeEcuTransport({
replies: {
'72 07 72 17 00 0F EF': '02 15 72 17 00 0D EE 67 45 F8 0A FF FF FF FF 7D 0C 0D A8 55 28',
},
});
const s = await connect(fake, { sleep: async () => {} });
for await (const f of s.live()) {
console.log(f.fields.rpm.value); // 3566
break;
}
await s.close();
final fake = FakeEcuTransport(replies: {
'72 07 72 17 00 0F EF': '02 15 72 17 00 0D EE 67 45 F8 0A FF FF FF FF 7D 0C 0D A8 55 28',
});
final s = await connect(fake, sleep: (_) async {});
print((await s.live().first).fields['rpm']!.value); // 3566.0
await s.close();
Next: API reference