SDK v0.1 · read-only

API reference

ภาษาไทย

Every export of @smongrot/sdk and smongrot_sdk: types, defaults, and a minimal call.

Open a session with connect. Do not construct Session yourself (in Dart the constructor is private). Names match across languages except the rows below.

JavaScript Dart
Package @smongrot/sdk smongrot_sdk
Error SmongrotError extends Error SmongrotException implements Exception
live() async generator Stream<LiveFrame>
LiveFrame.at epoch milliseconds (number) DateTime
Stop live() break, or signal: AbortSignal break, cancel the subscription, or await stream.first
DTC status status: 'beta' and beta: true beta getter is true. No status field.
Timing override partial object, merged onto DEFAULT_TIMING a Timing(...) instance
API base constant DEFAULT_API_BASE defaultApiBase
Bundled spec SPEC spec
Bench replies BENCH_SESSION benchSession
Close the HTTP helper none api.close()
No fetch at startup throws NO_FETCH does not apply (http is a dependency)

core.* in JavaScript is the same functions Dart exports at the top level (import 'package:smongrot_sdk/smongrot_sdk.dart').

connect

connect(transport: Transport, opts?: ConnectOptions): Promise<Session>
Future<Session> connect(Transport transport, {
  bool matchV2 = false,
  String? makerHint,
  FutureOr<ModelInfo?> Function(String ecmId)? lookupModel,
  Timing? timing,
  Sleep? sleep,
  DateTime Function()? now,
})

Wakes the ECU, sends StartComm, waits for any liveness reply, sends StartDiag. Returns at state === 'ready'.

Throws ECU_SILENT after wakeTries (default 4). Throws NO_WAKE when a JS transport has neither wake nor setBreak.

const s = await connect(transport, { makerHint: 'keihin' });
final s = await connect(transport, makerHint: 'keihin');

ConnectOptions / named arguments

Name Type Default
matchV2 boolean false Use match_v2 rules where the live spec has them. Leave off. A frame that matches only that way marks v2_provisional fields as provisional.
makerHint 'keihin' | 'shindengen' unset Used for the fault-code decoder and for detect().mismatch. Does not force a live profile.
lookupModel (ecmId: string) => ModelInfo | null unset Optional. The session never opens a socket itself. A throw inside the hook becomes model: null.
timing partial Timing (JS) / Timing (Dart) defaults below Overrides bring-up and poll timing.
sleep JS (ms: number) => Promise<void> / Dart Future<void> Function(Duration) real timer Tests pass a no-op.
now JS () => number / Dart DateTime Function() Date.now / DateTime.now Clock for timeouts and LiveFrame.at.

Session

state is 'idle' | 'waking' | 'ready' | 'live' | 'closed'. Read it. Do not assign it.

identify, detect, live and dtc.read require 'ready', otherwise BAD_STATE.

identify() → Identity

Sends 72 07 72 00 00 05 10 up to 3 times, 300 ms apart. Falls back to the ECM-ID captured from StartDiag. Then, if lookupModel is set and an id was found, calls it once. The result is cached on the session.

const id = await s.identify();
id.ecmId;     // "0104780D01" | null
id.source;    // "id_frame" | "start_diag" | null
id.model;     // ModelInfo | null
final id = await s.identify();
id.ecmId;
id.model?.model;

Identity

Field Type
ecmId string | null 10 upper-case hex, or null
ecmIdBytes number[] | null / List<int>? the same 5 bytes, or null
source 'id_frame' | 'start_diag' | null which frame produced ecmId
model ModelInfo | null from lookupModel, else null

ModelInfo

Field Type
model string? rider-facing name. From the API it may be Thai and has no year.
maker 'keihin' | 'shindengen'?
partCode string? full part code when it matches NNNNN-… (drives the DTC maker rule)
ecuCode string? full part code as the API sent it, e.g. 38770-K03-H01
liveProfile string? suggestion, often null. live() detects the profile anyway.
ecmId string? the id the API answered for
verified boolean true if this ECM-ID was confirmed on a real box. modelInfoFromApi sets false when the API did not send true. Dart's constructor defaults to false.

detect() → Detected | null

Probes 0x17, then 0x13, then 0x11. Null means no live table answered.

const d = await s.detect();
d?.profile;    // "t17.sub8"
d?.method;     // "probed" | "generic"
d?.mismatch;   // boolean

Detected

Field Type
profile string profile id
method 'probed' | 'generic'
mismatch boolean maker hint and profile maker both set and different. Never true for a generic profile.

live(options?) → frames

One primary table read per frame, then at most one due secondary. Does not end until you stop it. The first call also runs identify() (cached if you already did).

live(o?: { profile?: string; signal?: AbortSignal; onFrame?: (f: LiveFrame) => void }): AsyncGenerator<LiveFrame>
Stream<LiveFrame> live({String? profile, void Function(LiveFrame f)? onFrame})
Option Default
profile detect A known id skips detection. Unknown id throws BAD_PROFILE.
signal none JS only. When aborted, the loop ends without throwing.
onFrame none Called with the same object that is yielded, before the yield.

Throws LIVE_UNSUPPORTED if detection finds nothing. Throws BAD_PROFILE on an unknown id. After the loop, state is 'ready' again unless you close()d.

for await (const f of s.live()) {
  const rpm = f.fields.rpm;
  if (rpm?.status === 'ok') console.log(rpm.value);
  break;
}
await for (final f in s.live()) {
  final rpm = f.fields['rpm']!;
  if (rpm.ok) print(rpm.value);
  break;
}

LiveFrame

Field JS Dart
at number (ms) DateTime clock from now
profile string string profile id
primaryOk boolean boolean false → primary fields are absent this frame, not last frame's values
match boolean boolean the profile's match rules hold on the data collected so far
engine 'running' | 'off' | 'unknown' String (getter) off = injector 0 ms and ignition 0°. With the engine off, rpm and temperature are not real values (a Keihin box shows about 17,500 rpm and −30 °C), so hide them. unknown = those two fields were not read. Also core.engineState(fields) / engineState(fields).
fields Record<string, Reading> Map<String, Reading> every field of the profile, every frame

Reading

Field Type
status 'ok' | 'absent' | 'invalid' absent is missing. It is not 0.
value number? / double? present only when ok
prov 'bench' | 'field' | 'reference' | 'provisional' not a status
source string? table id of the winning source, only when ok

Dart: reading.ok is status == 'ok'.

dtc.read(options?) → DtcResult

dtc.read(o?: { maker?: string }): Promise<DtcResult>
Future<DtcResult> read({String? maker})

Three reads, 72 05 74 01/02/03, 60 ms apart. maker overrides the hint for this call only. Requires ready.

const dtc = await s.dtc.read();
dtc.beta;        // true
dtc.outcome;     // "faults" | "clean" | "unreadable" | "failed"

DtcResult

Field Type
beta true always
status 'beta' JS only
outcome 'faults' | 'clean' | 'unreadable' | 'failed' see Concepts
reason 'no_reply' | 'maker_unknown' | 'bad_payload' | null why there are no codes. maker_unknown: the box answered with data but its maker is not known, so the codes are not decoded. Pass an API key (smongrotApi), or dtc.read({ maker: 'keihin' }) if you know the box. Null when faults or clean.
maker string | null the hint used, or null
codes DtcCode[] empty unless outcome is faults
replies { sub: number, hex: string }[] all three subs. hex is upper-case, space-separated, "" if silent. Dart: a record ({int sub, String hex}).

DtcCode

Field Type
label string Honda blink form, e.g. 7-1
meaning string | null English sensor name, plus , signal too low / , signal too high for codes 1, 7, 8, 9, 54 when the sub is 1 or 2. Null if the code is not in the table.
critical boolean true for codes 12, 33, 52
benchConfirmed boolean true only for 7-1 and 8-1

close() → Promise<void>

Sets state to 'closed' and closes the transport if it has close. Safe to call from finally. Any later call that talks to the ECU throws CLOSED.

await s.close();

Timing

interface Timing {
  wakeLowMs: number; wakeIdleMs: number; wakeTries: number;
  commandQuietMs: number; commandTimeoutMs: number;
  tableQuietMs: number; tableTimeoutMs: number;
  ecmIdTries: number; ecmIdGapMs: number; dtcGapMs: number;
  liveTickUnitMs: number; liveTargetTickMs: number; liveMinGapMs: number;
}
const DEFAULT_TIMING: Readonly<Timing>;
class Timing {
  Timing({int? wakeLowMs, int? wakeIdleMs, int wakeTries = 4, /* same fields */});
}
Field Default
wakeLowMs 70
wakeIdleMs 130
wakeTries 4
commandQuietMs 120
commandTimeoutMs 2000
tableQuietMs 120
tableTimeoutMs 500
ecmIdTries 3
ecmIdGapMs 300
dtcGapMs 60
liveTickUnitMs 300
liveTargetTickMs 150
liveMinGapMs 60

Dart has no DEFAULT_TIMING constant. Timing() applies these defaults. Timing(wakeTries: 6) overrides one field.

await connect(transport, { timing: { wakeTries: 6 } });
await connect(transport, timing: Timing(wakeTries: 6));

Transport

You implement this to add a cable. The port is already 10400 8N1. The session strips the echo.

interface Transport {
  write(bytes: Uint8Array): Promise<void>;
  read(timeoutMs: number): Promise<Uint8Array | null>;
  flush?(): Promise<void>;
  wake?(lowMs: number): Promise<void>;
  setBreak?(on: boolean): Promise<void>;
  close?(): Promise<void>;
}
abstract class Transport {
  Future<void> write(Uint8List bytes);
  Future<Uint8List?> read(Duration timeout);
  Future<void> flush();                 // default: no-op
  bool get hasAtomicWake;               // default false
  Future<void> wake(Duration low);      // used only when hasAtomicWake
  Future<void> setBreak(bool on);       // fallback wake
  Future<void> close();
}
Member
write raw bytes, including checksum
read next received chunk, or null on timeout. JS takes milliseconds. Dart takes a Duration.
flush drop pending received bytes. Called before every request.
wake hold the line LOW for the given time, timed on the adapter. Preferred.
setBreak true drives LOW, false releases. Fallback when there is no wake.
close release the port

Dart calls wake only when hasAtomicWake is true. The default setBreak throws UnsupportedError, not NO_WAKE. JS throws NO_WAKE when both are missing.

ChunkQueue

FIFO used by the adapters. push(chunk) ignores empty chunks. read returns the next chunk or null at the timeout. clear() drops what is queued. close() makes further reads return null.

const q = new ChunkQueue();
q.push([0x02, 0x04]);
await q.read(50);
final q = ChunkQueue();
q.push([0x02, 0x04]);
await q.read(const Duration(milliseconds: 50));

Errors

class SmongrotError extends Error { code: string }
class SmongrotException implements Exception { final String code; final String message; }

Session: ECU_SILENT, BAD_STATE, LIVE_UNSUPPORTED, BAD_PROFILE, CLOSED, NO_WAKE, FRAME_NOT_ALLOWED (the SDK refused to send a frame outside its read-only allowlist), RESPONSE_TOO_LARGE (the device sent more than 4 KB for one reply). Adapters: BAD_PORT, PORT_OPEN, WRITE_FAILED. API helper: NO_API_KEY, and JS NO_FETCH. API_* codes go to onError only. Cause and fix: Troubleshooting.

try { await connect(transport); }
catch (e) { if (e instanceof SmongrotError && e.code === 'ECU_SILENT') console.error(e.message); }
try { await connect(transport); }
on SmongrotException catch (e) { if (e.code == 'ECU_SILENT') print(e.message); }

Model API

smongrotApi / SmongrotApi

smongrotApi(opts: {
  apiKey: string;
  baseUrl?: string;          // default DEFAULT_API_BASE
  fetch?: typeof fetch;
  timeoutMs?: number;        // default 5000
  onError?: (e: SmongrotError) => void;
}): { baseUrl: string; lookupModel(ecmId: string): Promise<ModelInfo | null> }
class SmongrotApi {
  SmongrotApi({
    required String apiKey,
    String baseUrl = defaultApiBase,
    http.Client? client,
    Duration timeout = const Duration(seconds: 5),
    void Function(SmongrotException e)? onError,
  });
  final String baseUrl;
  Future<ModelInfo?> lookupModel(String ecmId);
  void close();
}

SmongrotApi smongrotApi({required String apiKey, String baseUrl = defaultApiBase, http.Client? client,
    Duration timeout = const Duration(seconds: 5), void Function(SmongrotException e)? onError});

DEFAULT_API_BASE / defaultApiBase is https://api.smongrot.com/v1. Trailing slashes are stripped.

lookupModel never throws. 404 (unknown ECU) returns null and does not call onError. Other failures call onError and return null. The id must be 10 hex characters or onError gets API_BAD_INPUT.

Throws NO_API_KEY if apiKey is empty. JS also throws NO_FETCH when no fetch exists.

const api = smongrotApi({ apiKey: process.env.SMONGROT_API_KEY, onError: (e) => console.warn(e.code) });
const s = await connect(transport, { lookupModel: api.lookupModel });
final api = SmongrotApi(apiKey: myKey, onError: (e) => print(e.code));
final s = await connect(transport, lookupModel: api.lookupModel);
api.close();

modelInfoFromApi(data) → ModelInfo | null

Maps an API data object (ecm_id, maker, model, ecu_code, live_profile, verified). Returns null when none of model, ecu_code, maker is usable. maker is lower-cased and kept only if it is keihin or shindengen.

modelInfoFromApi({ ecm_id: '0101880D01', maker: 'Keihin', model: 'เวฟ 110i', ecu_code: '38770-K03-H01', verified: true });
modelInfoFromApi({'ecm_id': '0101880D01', 'maker': 'Keihin', 'model': 'เวฟ 110i', 'ecu_code': '38770-K03-H01', 'verified': true});

Cable adapters (JavaScript)

openWebSerial(port) → Promise<Transport>

openWebSerial(port: SerialPort): Promise<Transport>

Opens a Web Serial port at 10400 8N1, no flow control. port comes from navigator.serial.requestPort() and must not already be open. Wake is setBreak for 70 ms. close() cancels the reader and closes the port. A browser failure rejects with DOMException, not SmongrotError.

const s = await connect(await openWebSerial(await navigator.serial.requestPort()));

fromSerialPort(port, opts?) → Promise<Transport>

fromSerialPort(port: SerialPort, o?: { wake?: (lowMs: number) => Promise<void>; closeStream?: boolean }): Promise<Transport>

Wraps a serialport SerialPort. Opens it if needed. Rejects BAD_PORT when the value is not a SerialPort, baud is set and is not 10400, or the frame is not 8N1. Wake is port.set({ brk }) for 70 ms, unless you pass wake. closeStream defaults to closing the port on close().

serialport is an optional peer. Install it yourself. This package does not import it.

import { SerialPort } from 'serialport';
const port = new SerialPort({ path: '/dev/cu.usbserial-XXXX', baudRate: 10400, autoOpen: false });
const s = await connect(await fromSerialPort(port));

fromDuplex(stream, opts?) → Transport

fromDuplex(stream: Duplex, o?: {
  setBreak?: (on: boolean) => Promise<void>;
  wake?: (lowMs: number) => Promise<void>;
  closeStream?: boolean;   // default true (stream.destroy() on close)
}): Transport

Any Node Duplex already at 10400 8N1. Does not check the baud. Without wake or setBreak, connect throws NO_WAKE. write rejects with the stream's error, not a SmongrotError.

const t = fromDuplex(stream, { setBreak: (on) => new Promise((ok, no) => port.set({ brk: on }, (e) => e ? no(e) : ok())) });

Cable adapters (Dart)

Published separately so the core stays pure Dart. Both set 10400 8N1 and no flow control.

LibSerialPortTransport (smongrot_sdk_libserialport)

Desktop Windows, macOS, Linux, via flutter_libserialport. Re-exports SerialPort.

Member
LibSerialPortTransport.open(name) opens read/write, sets 10400 8N1. Throws PORT_OPEN.
LibSerialPortTransport.fromOpenPort(port) wraps a port you already opened. Sets 10400 8N1.
LibSerialPortTransport.configureKLine(port) baud 10400, 8 data bits, no parity, 1 stop bit, no flow control
setBreak(on) OS break. Throws NO_WAKE if the driver refuses.
write throws WRITE_FAILED if not every byte is accepted (write timeout 1000 ms)

Wake is a 70 ms break. There is no hasAtomicWake.

import 'package:smongrot_sdk_libserialport/smongrot_sdk_libserialport.dart';

print(SerialPort.availablePorts);
final s = await connect(LibSerialPortTransport.open('/dev/cu.usbserial-XXXX'));

UsbSerialTransport (smongrot_sdk_usb_serial)

Android USB-OTG, via usb_serial. Re-exports UsbSerial, UsbPort, UsbDevice.

static Future<UsbSerialTransport> open(UsbPort port, {Future<void> Function(Duration low)? atomicWake})

Throws PORT_OPEN if port.open() returns false. Sets DTR and RTS low. hasAtomicWake is true: wake calls atomicWake when you passed one, otherwise emulatedWake (about 45 ms LOW).

import 'package:smongrot_sdk_usb_serial/smongrot_sdk_usb_serial.dart';

final devices = await UsbSerial.listDevices();
final port = await devices.first.create();
final s = await connect(await UsbSerialTransport.open(port!));

emulatedWake / emulatedWakeBaud / kLineBaud

Dart core, for people writing an adapter.

kLineBaud 10400
emulatedWakeBaud(lowMs) round(9000 / lowMs) clamped to 200..600. For 70 ms that is 129, clamped to 200.
emulatedWake(lowMs, {setBaud, write, sleep}) switch to that baud, write one 0x00, wait ceil(10000 / baud) + 60 ms, restore 10400. A driver that rejects the low baud skips the pulse. The line is always restored.
await emulatedWake(
  70,
  setBaud: (baud) async { /* switch your chip, including back to 10400 */ },
  write: (bytes) async { /* write these bytes */ },
);

setBaud is Future<void> Function(int baud). write is Future<void> Function(Uint8List bytes). sleep defaults to Future.delayed.

Test double

FakeEcuTransport

A scripted ECU. read never waits on a timer: the next chunk, or null at once. Pass sleep: async () => {} (JS) or sleep: (_) async {} (Dart) to connect so the test does not wait out the 70 ms and 130 ms.

new FakeEcuTransport(o?: {
  replies?: Record<string, string | null | ((tx: number[]) => string | null)>;
  raw?: Record<string, string>;
  bench?: boolean;      // default true
  echo?: boolean;       // default true
  chunkSize?: number;   // default 0 = one chunk
})
FakeEcuTransport({
  Map<String, String?> replies = const {},
  Map<String, String> raw = const {},
  bool bench = true,
  bool echo = true,
  int chunkSize = 0,
})
replies request hex → reply hex sent after the echo. null means silent. JS values may be a function of the tx bytes. Dart values are strings only.
raw request hex → the exact read-back, not run through the echo rule
bench preload BENCH_SESSION / benchSession (StartComm, liveness, StartDiag, ECM-ID). identify() then returns 0104780D01.
writes hex of every frame written
badChecksumWrites subset whose checksum was wrong
wakes JS: number[] of low-ms. Dart: List<Duration>.

A bench-only fake has no live table. live() throws LIVE_UNSUPPORTED until replies contains one. The reply used in the quickstart decodes rpm as 3566.

const s = await connect(new FakeEcuTransport(), { sleep: async () => {} });
console.log((await s.identify()).ecmId);   // 0104780D01
final s = await connect(FakeEcuTransport(), sleep: (_) async {});
print((await s.identify()).ecmId);

SPEC / spec

The bundled level-1 spec: kline, live, dtc. Normative text is the JSON published next to these docs. SPEC is also core.SPEC in JavaScript.

SPEC.kline.physical.baud;    // 10400
spec['kline']['physical']['baud'];    // 10400

Protocol helpers (core.* / top-level Dart)

Pure functions. No I/O. Prefer connect for a bike. Use these to test a frame or to build your own tool on the same rules.

fromHex(s) → bytes

'72 07 72 17 00 0F' → [0x72, 0x07, 0x72, 0x17, 0x00, 0x0F]. Whitespace-only → [].

core.fromHex('72 05 71 00 18');
fromHex('72 05 71 00 18');

toHex(bytes) → string

Upper-case, space-separated. toHex([0x72, 0x07]) → '72 07'.

checksum(body) → number

(0x100 − (sum mod 256)) mod 256, masked to 8 bits.

core.checksum(core.fromHex('72 07 72 17 00 0F'));   // 0xEF

isValidFrame(frame) → boolean

True when the frame is non-empty and its bytes sum to 0 mod 256.

validReplyLength(raw, p) → number | null

Length L of a valid frame starting at p, or null. L = raw[p+1], L >= 4, the frame fits, the bytes sum to 0 mod 256.

peelEcho(raw, tx) → { echo, distorted, reply }

Echo-strip one read-back: returns the echo, whether it was distorted, and the reply bytes.

core.peelEcho(core.fromHex('72 05 00 F0 99 02 04 00 FA'), core.fromHex('72 05 00 F0 99'));
// { echo: true, distorted: false, reply: [0x02, 0x04, 0x00, 0xFA] }

ecmIdFrom(raw) → string | null

10 upper-case hex from a reply, or null. Prefers 02 0B 72 00 00, else 02 0F 71 00.

extractData(reply, request, headerLen, dataLen) → bytes | null

Data bytes of the last checksum-valid 02 L <service> <table> frame. Null when the frame is missing or shorter than dataLen.

normalizeEcmId(s) → string

Removes whitespace and upper-cases. '01 04780d01' → '0104780D01'.

profiles() / profiles

JS: core.profiles() returns the profile array. Dart: profiles is a getter of List<Profile> (Profile is Map<String, dynamic>).

profileById(id) → profile | null

The profile object, or null. JS: core.profileById('t17.sub8').

tableDef(profile, id) / primaryTable(profile)

Dart only. The table object inside a profile, and the primary one. JS reads profile.tables[id] and profile.tables[profile.primary] on the object from profileById.

profileMatches(profile, data, matchV2?) → boolean

data is { tableId: bytes }. JS: core.profileMatches(p, data, false). Dart: profileMatches(p, data, matchV2: false).

decodeLive(profile, data, { ecmId?, matchV2? }) → fields

Same shape as LiveFrame.fields.

const p = core.profileById('generic.t17');
core.decodeLive(p, { t17: core.fromHex('0D EE 00 00 FF FF FF FF FF FF 00 00 00 00 00') });

makerForPartCode(partCode) → 'keihin' | 'shindengen' | null

38770-… → keihin. 30400-… → shindengen. Anything else, including null, → null.

core.makerForPartCode('38770-K03-H01');   // "keihin"

probeTables() → { table, def }[]

Probe order. table is the byte 23, 19, 17 (0x17, 0x13, 0x11). def is that profile's primary table object (request, reply_header_len, data_len).

chooseProfile(table, data, { makerHint?, matchV2? }) → detection | null

JS returns { profile, method, mismatch } where profile is the profile object, or null. Dart returns Detected?, where profile is the id string. session.detect() returns the id in both languages. table is the byte (23, 19 or 17). data is the primary table's bytes.

const c = core.chooseProfile(0x17, bytes, { makerHint: 'keihin' });
c?.profile.id;
final c = chooseProfile(0x17, bytes, makerHint: 'keihin');
c?.profile;    // the id

dtcPayloadOf(reply, sub?) → bytes | null

Payload of the last valid 02 … 74 frame. sub when passed must match the reply's sub byte.

decodeDtcPayload(payload) → string[] | null

Labels, or null when the payload is unreadable. Empty list means no codes in this payload.

decodeDtcReplies(replies, subs?) → string[] | null

Union of labels, or null if any reply is unreadable. subs must have one entry per reply when you pass it.

describeDtc(label) → meaning | null

JS returns { meaning, critical, benchConfirmed } or null when the code is not in the table. Dart returns a DtcCode whose meaning is null in that case (the label is kept).

core.describeDtc('7-1');
// { meaning: "engine temperature sensor, signal too low", critical: false, benchConfirmed: true }
describeDtc('7-1').meaning;

Next: Identify and API key