# smongrot SDK — llms-full.txt GENERATED by tools/build_llms_full.mjs from site/*.md, spec/*.json and vectors/. Do not edit. Level 1 = read-only Honda K-Line diagnostics. The JSON spec below is normative; prose is a guide. ============================================================================== # FILE: site/llms.txt ============================================================================== # smongrot SDK > Read-only (level 1) Honda motorcycle ECU diagnostics over a K-Line cable: ECU identity, live engine data, stored fault codes (beta). Machine-readable spec + golden test vectors; SDKs in JavaScript (npm `@smongrot/sdk`) and Dart (pub `smongrot_sdk`), MIT, v0.1. Source of truth is the JSON spec. An implementation is correct only if it passes every vector in `vectors/`. ## Rules an implementation MUST follow - K-Line 10400 baud 8N1. Strip the TX echo from every read-back (spec/kline.json `echo_strip`). - Checksum = (0x100 − (sum mod 256)) mod 256; always mask to 8 bits (a body summing to 0x100 has checksum 0x00). Never a plain sum. - Wake = LOW 70 ms timed atomically on the adapter, then 130 ms idle. Retry wake + StartComm + liveness up to 4 times. - Send StartDiag `72 05 71 00 18` before any live table read. - Take reply data only from the LAST checksum-valid `02 L ` frame; a reply shorter than the table's data_len is no data. - A missing or sentinel value is "absent", never 0; an out-of-range value is "invalid" and is never replaced by a fallback source. - Keep each value's provenance (bench / field / reference / provisional); do not hide "provisional". - Fault codes are beta: decode only Keihin boxes; anything that does not parse is "unreadable", never guessed. - Level 1 sends no write, erase or state-changing frame (no DTC clear). Never call a network from the decoder. - The model name is optional and comes from `GET https://api.smongrot.com/v1/ecu/identify?ecm=<10 hex>` with a free API key. A failed lookup gives model null and never breaks identify, live data or fault codes. ## Platforms (v0.1) - Cable only: desktop Chrome / Edge (WebSerial), Node (`serialport`), Flutter desktop (`smongrot_sdk_libserialport`), Android USB-OTG (`smongrot_sdk_usb_serial`). - Not yet: iOS (no USB serial on iOS) and the SMR Bluetooth board, both in v0.2. ## Spec - [spec/kline.json](https://developers.smongrot.com/spec/kline.json): wire, wake, session, checksum, echo strip, timing - [spec/live.json](https://developers.smongrot.com/spec/live.json): live data profiles, extraction, value rule, detection - [spec/dtc.json](https://developers.smongrot.com/spec/dtc.json): fault-code read and decode (beta) - [spec/board-ble.json](https://developers.smongrot.com/spec/board-ble.json): SMR board BLE, level-1 commands only (board support is v0.2) - JSON Schemas: [common.schema.json](https://developers.smongrot.com/spec/schema/common.schema.json), [kline.schema.json](https://developers.smongrot.com/spec/schema/kline.schema.json), [live.schema.json](https://developers.smongrot.com/spec/schema/live.schema.json), [dtc.schema.json](https://developers.smongrot.com/spec/schema/dtc.schema.json), [board-ble.schema.json](https://developers.smongrot.com/spec/schema/board-ble.schema.json); vector suites use `vectors-.schema.json` in the same folder ## Vectors - [vectors/checksum.json](https://developers.smongrot.com/vectors/checksum.json), [vectors/echo.json](https://developers.smongrot.com/vectors/echo.json), [vectors/session.json](https://developers.smongrot.com/vectors/session.json) - Live: [vectors/live/extract.json](https://developers.smongrot.com/vectors/live/extract.json), [vectors/live/detect.json](https://developers.smongrot.com/vectors/live/detect.json), [vectors/live/t17.sub8.json](https://developers.smongrot.com/vectors/live/t17.sub8.json), [vectors/live/t17.sub4.json](https://developers.smongrot.com/vectors/live/t17.sub4.json), [vectors/live/t13.type7.json](https://developers.smongrot.com/vectors/live/t13.type7.json), [vectors/live/t11.type1.json](https://developers.smongrot.com/vectors/live/t11.type1.json), [vectors/live/generic.t17.json](https://developers.smongrot.com/vectors/live/generic.t17.json) - [vectors/dtc.json](https://developers.smongrot.com/vectors/dtc.json) ## Docs Read in this order: - [Overview](https://developers.smongrot.com/docs): what v0.1 is, three things to build, 60-second quickstart, platforms, what it does not do - [Concepts](https://developers.smongrot.com/docs/concepts): session lifecycle, ECM-ID, live profiles, field status (`ok` / `absent` / `invalid`), makers, timing - [Hardware](https://developers.smongrot.com/docs/hardware): K-Line cable, connector signals, FTDI VCP, 10400 8N1, Android OTG, why iOS has no cable - [Safety](https://developers.smongrot.com/docs/safety): read-only frames, absent is not 0, provisional values, beta fault codes - [Quickstart: JavaScript](https://developers.smongrot.com/docs/quickstart-js): browser WebSerial and Node `serialport` - [Quickstart: Dart](https://developers.smongrot.com/docs/quickstart-dart): Flutter desktop (`smongrot_sdk_libserialport`) and Android OTG (`smongrot_sdk_usb_serial`) - [Examples](https://developers.smongrot.com/docs/examples): Node CSV logger, browser gauge, Flutter live screen, Android OTG, DTC read, API key - [Identify and API key](https://developers.smongrot.com/docs/identify): ECM-ID offline, model name via `GET /v1/ecu/identify`, errors that do not break identify - [API reference](https://developers.smongrot.com/docs/api): every exported function, type, option and error, JS and Dart - [Protocol overview](https://developers.smongrot.com/docs/protocol): wire format, wake, session bytes, live extraction, fault-code reads - [Troubleshooting](https://developers.smongrot.com/docs/troubleshooting): every `code` (`ECU_SILENT`, `API_*`, …) with cause and fix, plus look-alike symptoms - [FAQ](https://developers.smongrot.com/docs/faq): free MIT SDK, free API key, 1000 requests/day, commercial use, privacy, v0.2 roadmap ## Optional - [llms-full.txt](https://developers.smongrot.com/llms-full.txt): every doc and spec file in one text, generated ## ภาษาไทย (Thai) - [llms.txt](https://developers.smongrot.com/th/llms.txt) - [llms-full.txt](https://developers.smongrot.com/th/llms-full.txt) ============================================================================== # FILE: site/index.md ============================================================================== # smongrot SDK [ภาษาไทย](th/index.md) > Read-only Honda motorcycle ECU diagnostics over a USB K-Line cable: who the box is, live engine data, and stored fault codes (beta). v0.1 talks to Keihin and Shindengen ECUs from JavaScript (`@smongrot/sdk`) and Dart (`smongrot_sdk`). Both are MIT. The cable session never writes the ECU. ```sh npm i @smongrot/sdk # JavaScript (browser + Node) dart pub add smongrot_sdk # Dart / Flutter ``` ## What you can build - **Shop diagnostic tool.** On a workshop PC, open a session, show the ECM-ID and model name, a few live gauges, and stored fault codes as a hint. - **Fleet dashboard.** Each bike reports its ECM-ID and a handful of live fields. Pass a free API key when you want the model name on the card. Live numbers stay on the device. - **Data logger.** Poll `live()` and append rpm, temperature and battery to a file. A missing field is a blank cell. Rpm `0` with the engine off is a real reading. ## 60-second quickstart Key ON (engine off is fine). Plug an FTDI or KKL K-Line cable into the bike's diagnostic connector. Desktop Chrome or Edge, from a button click (WebSerial needs a user gesture, on https or localhost): ```js import { connect, openWebSerial } from '@smongrot/sdk'; document.querySelector('button').onclick = async () => { const port = await navigator.serial.requestPort(); const s = await connect(await openWebSerial(port)); try { console.log((await s.identify()).ecmId); // 10 hex, read from the box for await (const f of s.live()) { const rpm = f.fields.rpm; console.log(rpm?.status === 'ok' ? rpm.value : '—'); break; } } finally { await s.close(); } }; ``` Node, Flutter desktop and Android use the same `connect` / `identify` / `live` / `close` calls with a different transport. See [Quickstart: JavaScript](https://developers.smongrot.com/docs/quickstart-js) and [Quickstart: Dart](https://developers.smongrot.com/docs/quickstart-dart). ## Platform support | Platform | How it connects | v0.1 | |---|---|---| | Desktop browser (Chrome / Edge) | USB cable, WebSerial (`openWebSerial`) | yes | | Node (Windows / macOS / Linux) | USB cable, `serialport` (`fromSerialPort`) | yes | | Flutter / Dart desktop | USB cable, `smongrot_sdk_libserialport` | yes | | Android (Flutter) | USB-OTG cable, `smongrot_sdk_usb_serial` | yes | | iOS | no USB-serial access, so no cable | v0.2, SMR board over BLE | | SMR board (any phone) | Bluetooth LE | v0.2 | Phone browsers do not have WebSerial. Use the Android or desktop row. | Feature | Needs | |---|---| | ECM-ID, live data, fault codes | the cable only; works offline | | Model name on `identify()` | a free API key ([Identify and API key](https://developers.smongrot.com/docs/identify)) | | Fault codes | beta: Keihin boxes are decoded; anything unclear is `unreadable` | ## Hardware you need An FTDI or KKL **K-Line** cable, and the bike's **12 V with the key ON**. The ECU is powered by the bike, not by USB. Serial settings are **10400 8N1**. Details, drivers and the Android / iOS limits: [Hardware](https://developers.smongrot.com/docs/hardware). ## What v0.1 does not do - It does not write, erase or change the ECU. - It does not read the full ROM. - It does not clear fault codes (that also resets learned values). - It does not talk to the immobilizer. Those stay out of this SDK. Later levels that need the SMR board are not here. ## Pages | Page | | |---|---| | [Concepts](https://developers.smongrot.com/docs/concepts) | session, ECM-ID, live fields, makers, timing | | [Hardware](https://developers.smongrot.com/docs/hardware) | cable, connector, drivers, 10400 8N1, Android, iOS | | [Safety](https://developers.smongrot.com/docs/safety) | what v0.1 sends, and what a missing value means | | [Quickstart: JavaScript](https://developers.smongrot.com/docs/quickstart-js) | browser (WebSerial) and Node | | [Quickstart: Dart](https://developers.smongrot.com/docs/quickstart-dart) | Flutter desktop and Android | | [Examples](https://developers.smongrot.com/docs/examples) | CSV logger, gauge, Flutter, DTC, API key | | [API reference](https://developers.smongrot.com/docs/api) | every export, with types and defaults | | [Identify and API key](https://developers.smongrot.com/docs/identify) | ECM-ID, model name, the free key | | [Protocol overview](https://developers.smongrot.com/docs/protocol) | what goes on the wire | | [Troubleshooting](https://developers.smongrot.com/docs/troubleshooting) | every error code, and the look-alike symptoms | | [FAQ](https://developers.smongrot.com/docs/faq) | price, license, privacy, roadmap | | [llms.txt](https://developers.smongrot.com/llms.txt) · [llms-full.txt](https://developers.smongrot.com/llms-full.txt) | for AI coding tools | The normative spec is [kline](https://developers.smongrot.com/spec/kline.json), [live](https://developers.smongrot.com/spec/live.json), [dtc](https://developers.smongrot.com/spec/dtc.json) and [board-ble](https://developers.smongrot.com/spec/board-ble.json) (board support is v0.2). An implementation is correct only if it passes the published vectors listed in [llms.txt](https://developers.smongrot.com/llms.txt). Next: [Concepts](https://developers.smongrot.com/docs/concepts) ============================================================================== # FILE: site/concepts.md ============================================================================== # Concepts [ภาษาไทย](th/concepts.md) > How a level-1 session moves, what an ECM-ID is, and why a missing live value is not 0. ## Session lifecycle `connect(transport)` is the only way to open a session. It runs wake, StartComm, liveness and StartDiag, then returns with `state === 'ready'`. You call `identify()`, `live()` and `dtc.read()` after that. `close()` drops the port. ``` App Cable / ECU |-- connect() ------------------------------------------->| | wake: line LOW 70 ms, release, idle 130 ms | | StartComm FE 04 72 8C (reply not required) | | liveness first non-empty reply means "up" | | 72 05 00 F0 99 | | 72 05 71 00 18 | | 7E 06 01 01 00 7A | |<------------------------ any reply --------------------| | StartDiag 72 05 71 00 18 | |<------------------------ 02 0F 71 00 <5-byte id> .. ----| | | | state is now "ready" | |-- identify() ------------------------------------------>| | 72 07 72 00 00 05 10 up to 3 tries, 300 ms apart | |<------------------------ 02 0B 72 00 00 <5 bytes> ck ---| |-- live() or dtc.read() (not at the same time) ------>| |<------------------------ frames -----------------------| |-- close() --------------------------------------------->| | state is "closed" | ``` If no liveness probe answers, `connect` repeats wake + StartComm + liveness, up to **4** times, then throws `ECU_SILENT`. StartDiag is required: without it the live tables stay silent. `connect` sends it for you. `state` is `idle`, then `waking`, then `ready`. `live()` moves it to `live` and back to `ready` when the loop ends. `identify`, `detect`, `live` and `dtc.read` all require `ready`. Stop the live loop before reading fault codes. `identify()` remembers its result; a second call does not touch the bus. ## ECM-ID The ECM-ID is **5 bytes**, shown as **10 upper-case hex** characters, for example `0104780D01`. `identify()` prefers the dedicated ID frame. If that frame never arrives it uses the ID carried in the StartDiag reply (`source` is `id_frame`, `start_diag`, or `null`). The ID is not a model name. The name, maker and part code come only from `lookupModel` (see [Identify and API key](https://developers.smongrot.com/docs/identify)). Live data and fault codes do not need it. ## Live profiles `live()` with no `profile` probes tables **`0x17`, then `0x13`, then `0x11`** (2 tries each) and picks a layout. Pass `profile` only when you already know the id. | Profile | Maker | Fields | |---|---|---| | `t17.sub8` | Keihin | `rpm`, `tps_v`, `tps`, `ect`, `batt`, `inj_ms`, `ign`, `ltft`, `o2r` | | `t17.sub4` | Shindengen | `rpm`, `tps_v`, `tps`, `eot`, `batt`, `inj_ms`, `ign` | | `t13.type7` | Keihin | `rpm`, `tps`, `ect`, `batt`, `inj_ms`, `ign`, `o2r` | | `t11.type1` | Keihin | `rpm`, `tps`, `ect`, `batt`, `inj_ms`, `ign`, `o2r` | | `generic.t17` | either | `rpm`, `tps`, `inj_ms`, `ign` | `generic.t17` is the fallback when table `0x17` answers but neither sub-layout matches. It only has the fields that match on both makers, so temperature and battery are absent on purpose. Each value is `raw × scale + add` over big-endian bytes. Scales live in [spec/live.json](https://developers.smongrot.com/spec/live.json). The SDK does not emit `o2_v`. If you want a voltage for display, `o2r × 0.0195` when `o2r` is `ok`. That conversion is provisional, and a narrowband sensor says rich or lean, not an air-fuel number. `detect()` returns `{ profile, method, mismatch }` or `null`. `method` is `probed` or `generic`. `mismatch` is true when a maker hint and the profile maker are both set and differ. The observed layout still wins. ## Field status Every field is reported on every frame, even when its table did not answer. | `status` | Meaning | What to show | |---|---|---| | `ok` | `value` is a number | the number | | `absent` | not in this frame | `—` | | `invalid` | out of range, or two sources disagree | `—`, not the raw number | `absent` is the "missing" case. It is **not 0**. A sentinel (for example temperature byte `0xFF`, or a battery byte `0`) is `absent`. A table that has not been read yet is `absent`. A field that does not exist on this profile is `absent`. Substituting 0 paints a dead sensor as a real zero. Rpm has no sentinel, so it is always `status: 'ok'` when its table answers, even with the engine off. With the key ON and the engine off, a box can report `0` **or a meaningless number**: a bench Keihin K03-H01 gave about 17,500 rpm and −30 °C engine temperature. Use `frame.engine`: `'off'` (injector 0 ms and ignition 0°) means rpm and temperature are not real values. Hide them or show "engine off". `prov` is separate from `status`. It is `bench` (measured on a real ECU), `field` (consistent in field logs, not meter-checked), `reference` (from the reference decoder only), or `provisional` (one sample or an inference). Show a `provisional` value, and do not let it make a decision on its own. Battery on the Shindengen layout is provisional. `prov` is not a status: do not test `status === 'provisional'`. In Dart, `reading.ok` is `status == 'ok'`. In JavaScript, test `reading.status === 'ok'` before using `value`. A frame with `primaryOk: false` failed the primary table read. Those fields are `absent` for this tick. The SDK does not reuse the previous number. ## Makers | Maker | Part code starts with | Fault codes in v0.1 | |---|---|---| | `keihin` | `38770-` | decoded (beta) | | `shindengen` | `30400-` | same reads, but a non-zero payload is `unreadable` | `makerHint` on `connect`, or `model.maker` / `model.partCode` after `identify()`, selects the decoder. Unknown maker plus a non-zero payload is `unreadable` with `reason: 'maker_unknown'`. All-zero payloads are `clean` for either maker. The SDK never guesses a code. ## Timing Defaults (`DEFAULT_TIMING` in JavaScript, `new Timing()` in Dart). Override a field only when you mean to. | | Default | |---|---| | Wake LOW / idle after wake | 70 ms / 130 ms | | Wake tries (wake + StartComm + liveness) | 4 | | ECM-ID tries / gap | 3 / 300 ms | | Command quiet / timeout | 120 ms / 2000 ms | | Live-table quiet / timeout | 120 ms / 500 ms | | Gap between fault-code reads | 60 ms | | Live tick unit (how often a secondary table is due) | 300 ms | | Target gap between live frames / minimum gap | 150 ms / 60 ms | A read ends after `quiet` milliseconds of silence, or at `timeout`, whichever comes first. A timeout does not throw. You get an empty reply, and the field or the DTC outcome says so. The primary live table is read every frame. At most one secondary table (`o2r` on `t20`, Shindengen battery on `d0`) is read per frame, so those fields are `absent` on the first frames. That is the poll schedule, not a failed sensor. Next: [Hardware](https://developers.smongrot.com/docs/hardware) ============================================================================== # FILE: site/hardware.md ============================================================================== # Hardware [ภาษาไทย](th/hardware.md) > What to plug in: a K-Line cable, key ON, 10400 8N1, and which phone can open it. ## Choosing a cable You need a **USB K-Line (KKL) cable** built on an FTDI, CP210x or CH340 chip. It must speak **10400 baud 8N1** and be able to hold the line LOW for the wake (a serial-break, or an FTDI bit-bang). A plain USB-UART with no K-Line transceiver will not work: the bus is one wire, half-duplex, and the cable echoes every byte you send. The session strips that echo. Prefer an FTDI cable when you can. A bit-bang of TXD LOW for 70 ms is the wake the bench uses; a Shindengen box that was just switched to key ON answers that on the first try. OS break (what the desktop adapters do) is 70 ms and is enough for Keihin. The Android adapter cannot bit-bang, so its wake is shorter (see below). The bike supplies the ECU. USB power on the computer side does not. ## Connector The Honda diagnostic connector carries three signals the cable needs. Match the cable's leads to those signals. This page does not publish a pin diagram. | Signal | Role | |---|---| | K-Line | the single ISO 9141 data wire | | GND | bike ground, common with the cable ground | | +12 V | bike battery. Present with the key ON. Powers the ECU. | Key ON, engine off, is the normal workshop state. Key OFF means the ECU is unpowered and `connect` ends in `ECU_SILENT`. ## Serial settings | Setting | Value | |---|---| | Baud | 10400 | | Data bits | 8 | | Parity | none | | Stop bits | 1 | | Flow control | none | The shipped adapters set this. If you open the port yourself and pass it to `fromSerialPort`, the baud must be 10400 and the frame 8N1, or you get `BAD_PORT`. `fromDuplex` does not check: set the port before you wrap it. Idle level on the bus is high. ## Drivers | OS | What you install | |---|---| | Windows | The chip's Virtual COM Port driver. FTDI cables use FTDI VCP. The port shows up as `COM3` (the number varies). | | macOS | Nothing for a genuine FTDI FT232: the system driver does 10400. Open `/dev/cu.usbserial-…`, not the `tty` node. | | Linux | The kernel driver (`ftdi_sio` for FTDI) creates `/dev/ttyUSB0`. The user needs permission on that node (group `dialout` on most distros). | CP210x and CH340 cables need that vendor's driver on the desktop. Unplug other serial devices while you find the path. `SerialPort.list()` (Node) and `SerialPort.availablePorts` (Flutter desktop) print it. ## Android (USB-OTG) The phone must be the USB host. Use an OTG adapter. A charge-only cable enumerates nothing. `smongrot_sdk_usb_serial` speaks FTDI, CP210x, CH34x and CDC. `UsbSerial.listDevices()` then `device.create()` asks for permission; call `create()` from a running screen (a button), not during process start. The chip has no break control. The adapter wakes by dropping to a low baud and sending one `0x00`, which holds the line LOW for **about 45 ms**, then returns to 10400. Most Keihin boxes answer it. A Shindengen box fresh off key ON may ignore it; `connect` still tries 4 times. If you have a native FTDI bit-bang, pass it as `atomicWake` and the adapter uses that instead. ## Why iOS cannot use a cable iOS does not give an app a USB-serial port, so no K-Line cable can be opened. v0.2 reaches the bike through the SMR board over Bluetooth LE, which works on iOS. There is no iOS cable adapter in v0.1. Next: [Safety](https://developers.smongrot.com/docs/safety) ============================================================================== # FILE: site/safety.md ============================================================================== # Safety [ภาษาไทย](th/safety.md) > v0.1 only reads. It does not write the ECU, read the full ROM, or clear fault codes. **v0.1 is read-only (level 1).** The SDK sends only these frames: the wake pulse, StartComm, liveness, StartDiag, the ECM-ID read, live table reads, and the three fault-code reads. It has no function that writes, erases or changes anything in the ECU, and it does not read the full ROM. Clearing fault codes is not included, because it also resets learned values. The SDK can only send the read frames listed in the spec: an allowlist is enforced at the single write point, and any other frame is refused (`FRAME_NOT_ALLOWED`) before it reaches the cable. On connect it sends a standard "tester present" keep-alive frame (`7E 06 01 01 00 7A`, a liveness probe in spec/kline.json), which does not change ECU memory. Writing, erasing and clearing fault codes are not possible through this SDK. - A value that is not there is **absent**, never 0. Show "—". - A `provisional` value (for example some battery readings) must not drive a decision on its own. Ask the rider to confirm it. - Fault codes are **beta**. Only Keihin boxes are decoded. Show them as a hint and keep the "unreadable" result honest. - Live tables answer only after StartDiag. A box that is silent after wake is "no answer", not "broken". The only network call is the optional model lookup (`smongrotApi`), which sends just the ECM-ID. Live data and fault codes never touch the network. **Levels 2–3 (coming later)** add full read and ECU write. They run only through the smongrot SMR board, with a server-signed ticket for each write and every safety gate on the board. They are not part of this SDK. Next: [Quickstart: JavaScript](https://developers.smongrot.com/docs/quickstart-js) ============================================================================== # FILE: site/quickstart-js.md ============================================================================== # Quickstart: JavaScript [ภาษาไทย](th/quickstart-js.md) > Install `@smongrot/sdk` and open a read-only session from a desktop browser or from Node. Cable and drivers: [Hardware](https://developers.smongrot.com/docs/hardware). Longer recipes: [Examples](https://developers.smongrot.com/docs/examples). ```sh npm i @smongrot/sdk ``` ESM, zero runtime dependencies, MIT. Node ≥ 18, or desktop Chrome / Edge (WebSerial). Key ON (engine off is fine), cable on the bike's diagnostic connector. ## Browser ```js import { connect, openWebSerial } from '@smongrot/sdk'; button.onclick = async () => { const port = await navigator.serial.requestPort(); const s = await connect(await openWebSerial(port)); const { ecmId } = await s.identify(); for await (const f of s.live()) { const rpm = f.fields.rpm; show(rpm?.status === 'ok' ? rpm.value : '—'); // never show 0 for a missing value } }; ``` ## Node `serialport` is an optional peer dependency; install it yourself. ```sh npm i @smongrot/sdk serialport ``` ```js import { SerialPort } from 'serialport'; import { connect, fromSerialPort } from '@smongrot/sdk'; const port = new SerialPort({ path: '/dev/cu.usbserial-XXXX', baudRate: 10400, autoOpen: false }); const s = await connect(await fromSerialPort(port)); console.log(await s.identify()); console.log(await s.dtc.read()); // beta: result.beta === true await s.close(); ``` The package ships a runnable `examples/node-serialport.mjs`. Any other Duplex stream at 10400 8N1 works with `fromDuplex(stream, { setBreak | wake })`. ## Model name Add a free API key to get the model name in `identify()` (see [Identify and API key](https://developers.smongrot.com/docs/identify)): ```js import { smongrotApi } from '@smongrot/sdk'; const api = smongrotApi({ apiKey: process.env.SMONGROT_API_KEY }); const s = await connect(transport, { lookupModel: api.lookupModel }); ``` ## Test without a bike ```js 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); break; } // 3566 ``` Next: [Quickstart: Dart](https://developers.smongrot.com/docs/quickstart-dart) ============================================================================== # FILE: site/quickstart-dart.md ============================================================================== # Quickstart: Dart [ภาษาไทย](th/quickstart-dart.md) > Install `smongrot_sdk` and open a read-only session on Flutter desktop or Android. Cable and drivers: [Hardware](https://developers.smongrot.com/docs/hardware). Longer recipes: [Examples](https://developers.smongrot.com/docs/examples). ```sh dart pub add smongrot_sdk flutter pub add smongrot_sdk_libserialport # desktop cable flutter pub add smongrot_sdk_usb_serial # Android USB-OTG cable ``` `smongrot_sdk` is pure Dart (no Flutter needed, compiles for web), MIT. The cable transports are separate small packages so the core has no native code. ## Desktop (Windows / macOS / Linux) ```dart import 'package:smongrot_sdk/smongrot_sdk.dart'; import 'package:smongrot_sdk_libserialport/smongrot_sdk_libserialport.dart'; print(SerialPort.availablePorts); final s = await connect(LibSerialPortTransport.open('/dev/cu.usbserial-XXXX')); final id = await s.identify(); await for (final f in s.live()) { final rpm = f.fields['rpm']!; print(rpm.ok ? rpm.value : '—'); // never show 0 for a missing value } ``` ## Android (USB-OTG) ```dart import 'package:smongrot_sdk/smongrot_sdk.dart'; import 'package:smongrot_sdk_usb_serial/smongrot_sdk_usb_serial.dart'; final devices = await UsbSerial.listDevices(); final port = await devices.first.create(); // Android asks for USB permission final s = await connect(await UsbSerialTransport.open(port!)); final dtc = await s.dtc.read(); // beta: dtc.beta == true await s.close(); ``` `usb_serial` cannot hold the line LOW directly, so the Android adapter sends a short low-baud pulse instead (about 45 ms). Most Keihin boxes answer it; a Shindengen box fresh off key-ON may not, and `connect` retries 4 times. If you have a native FTDI bit-bang helper, pass it as `atomicWake`. iOS has no USB-serial access; iOS support comes in v0.2 with the SMR board. ## Model name ```dart final api = SmongrotApi(apiKey: myKey); final s = await connect(transport, lookupModel: api.lookupModel); ``` See [Identify and API key](https://developers.smongrot.com/docs/identify). ## Test without a bike ```dart 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 ``` Next: [Examples](https://developers.smongrot.com/docs/examples) ============================================================================== # FILE: site/examples.md ============================================================================== # Examples [ภาษาไทย](th/examples.md) > Runnable recipes. Each one uses only exported functions. A missing field is never shown as 0. Shared rules: - Read `value` only when `status === 'ok'` (Dart: `reading.ok`). - `close()` in a `finally`, including when `connect` succeeded and a later call threw. - Call `dtc.read()` only while `state` is `ready`. Stop `live()` first. - Fault codes are beta. Show `outcome` as-is. Do not clear them. Key ON, engine off, cable on the diagnostic connector. Install steps are on the [JavaScript](https://developers.smongrot.com/docs/quickstart-js) and [Dart](https://developers.smongrot.com/docs/quickstart-dart) quickstarts. ## Node CSV logger ```sh npm i @smongrot/sdk serialport node logger.mjs /dev/cu.usbserial-XXXX ``` ```js // 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 '); 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. ```html

—

``` 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 ```sh flutter pub add smongrot_sdk smongrot_sdk_libserialport ``` ```dart 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 createState() => _LiveScreenState(); } class _LiveScreenState extends State { String _rpm = '—'; @override void initState() { super.initState(); _run(); } Future _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 ```sh 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. ```dart import 'package:smongrot_sdk/smongrot_sdk.dart'; import 'package:smongrot_sdk_usb_serial/smongrot_sdk_usb_serial.dart'; Future 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`: ```dart await UsbSerialTransport.open(port, atomicWake: myFtdiBitBang); ``` `myFtdiBitBang` is `Future 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. ```js 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'); } } ``` ```dart Future 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. ```js 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(); } ``` ```dart 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](https://developers.smongrot.com/docs/identify). ## 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`. ```js 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(); ``` ```dart 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](https://developers.smongrot.com/docs/api) ============================================================================== # FILE: site/identify.md ============================================================================== # Identify and API key [ภาษาไทย](th/identify.md) > Read the ECM-ID from the box offline, and optionally resolve the model name with a free API key. `identify()` reads the **ECM-ID** from the box: 5 bytes, shown as 10 hex characters (for example `0101880D01`). That needs only the cable and works offline. The **model name** (and maker, ECU code, suggested live profile) comes from the smongrot API. It needs a free API key from https://developers.smongrot.com. Without a key nothing breaks: live data and fault codes work the same, and `model` is `null`. ## JavaScript ```js import { connect, smongrotApi } from '@smongrot/sdk'; const api = smongrotApi({ apiKey: process.env.SMONGROT_API_KEY }); const s = await connect(transport, { lookupModel: api.lookupModel }); const id = await s.identify(); console.log(id.ecmId); // "0101880D01", read from the box console.log(id.model?.model ?? '—'); // model name (may be Thai), or "—" if unknown / offline / no key ``` ## Dart ```dart final api = SmongrotApi(apiKey: myKey); final s = await connect(transport, lookupModel: api.lookupModel); final id = await s.identify(); print(id.ecmId); print(id.model?.model ?? '—'); ``` ## What `model` holds | Field | | |---|---| | `model` | model name as riders know it. It can be in Thai and has no model year. | | `maker` | `keihin` or `shindengen` (also picks the fault-code decoder) | | `ecuCode` | full part code, e.g. `38770-K03-H01` (also set as `partCode`) | | `liveProfile` | suggested live profile id. Often `null`; `live()` detects the profile on its own, so you never need it. | | `verified` | `true` if this ECM-ID was confirmed on a real box | | `ecmId` | the ECM-ID the API answered for | Example `data`: `{"ecm_id": "0101880D01", "maker": "keihin", "model": "", "ecu_code": "38770-K03-H01", "live_profile": null, "verified": true}`. ## The request `GET https://api.smongrot.com/v1/ecu/identify?ecm=<10 hex>` with `Authorization: Bearer `. Success is `{ "data": { "ecm_id", "maker", "model", "ecu_code", "live_profile", "verified" } }`; errors are `{ "error": { "code", "message", "docs_url" } }`. Only the ECM-ID is sent. ## Errors never break identify `lookupModel` never throws. An unknown ECU (404), a bad key, a rate limit, a timeout (5 s default, `timeoutMs` / `timeout`) or no network all give `model: null`. To see why, pass `onError`: ```js smongrotApi({ apiKey, onError: (e) => console.warn(e.code, e.message) }); ``` Codes: `API_UNAUTHORIZED`, `API_RATE_LIMITED`, `API_NETWORK`, `API_ERROR`, `API_BAD_RESPONSE`, `API_BAD_INPUT`. A missing key is a programming error and throws `NO_API_KEY` when you create the helper, not during identify. ## Keep the key private Do not put the key in a public web page. In a browser app, call the API from your own server and pass your own `lookupModel(ecmId)` to `connect`; any function returning `{ model, maker, ... }` or `null` works. Next: [Protocol overview](https://developers.smongrot.com/docs/protocol) ============================================================================== # FILE: site/api.md ============================================================================== # API reference [ภาษาไทย](th/api.md) > 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.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` ```ts connect(transport: Transport, opts?: ConnectOptions): Promise ``` ```dart Future connect(Transport transport, { bool matchV2 = false, String? makerHint, FutureOr 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`. ```js const s = await connect(transport, { makerHint: 'keihin' }); ``` ```dart 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` / Dart `Future 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. ```js const id = await s.identify(); id.ecmId; // "0104780D01" | null id.source; // "id_frame" | "start_diag" | null id.model; // ModelInfo | null ``` ```dart 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?` | 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. ```js 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). ```ts live(o?: { profile?: string; signal?: AbortSignal; onFrame?: (f: LiveFrame) => void }): AsyncGenerator ``` ```dart Stream 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. ```js for await (const f of s.live()) { const rpm = f.fields.rpm; if (rpm?.status === 'ok') console.log(rpm.value); break; } ``` ```dart 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` | `Map` | 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` ```ts dtc.read(o?: { maker?: string }): Promise ``` ```dart Future read({String? maker}) ``` Three reads, `72 05 74 01/02/03`, 60 ms apart. `maker` overrides the hint for this call only. Requires `ready`. ```js 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](https://developers.smongrot.com/docs/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` 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`. ```js await s.close(); ``` ## Timing ```ts 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; ``` ```dart 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. ```js await connect(transport, { timing: { wakeTries: 6 } }); ``` ```dart 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. ```ts interface Transport { write(bytes: Uint8Array): Promise; read(timeoutMs: number): Promise; flush?(): Promise; wake?(lowMs: number): Promise; setBreak?(on: boolean): Promise; close?(): Promise; } ``` ```dart abstract class Transport { Future write(Uint8List bytes); Future read(Duration timeout); Future flush(); // default: no-op bool get hasAtomicWake; // default false Future wake(Duration low); // used only when hasAtomicWake Future setBreak(bool on); // fallback wake Future 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. ```js const q = new ChunkQueue(); q.push([0x02, 0x04]); await q.read(50); ``` ```dart final q = ChunkQueue(); q.push([0x02, 0x04]); await q.read(const Duration(milliseconds: 50)); ``` ## Errors ```ts class SmongrotError extends Error { code: string } ``` ```dart 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](https://developers.smongrot.com/docs/troubleshooting). ```js try { await connect(transport); } catch (e) { if (e instanceof SmongrotError && e.code === 'ECU_SILENT') console.error(e.message); } ``` ```dart try { await connect(transport); } on SmongrotException catch (e) { if (e.code == 'ECU_SILENT') print(e.message); } ``` ## Model API ### `smongrotApi` / `SmongrotApi` ```ts 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 } ``` ```dart 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 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. ```js const api = smongrotApi({ apiKey: process.env.SMONGROT_API_KEY, onError: (e) => console.warn(e.code) }); const s = await connect(transport, { lookupModel: api.lookupModel }); ``` ```dart 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`. ```js modelInfoFromApi({ ecm_id: '0101880D01', maker: 'Keihin', model: 'เวฟ 110i', ecu_code: '38770-K03-H01', verified: true }); ``` ```dart modelInfoFromApi({'ecm_id': '0101880D01', 'maker': 'Keihin', 'model': 'เวฟ 110i', 'ecu_code': '38770-K03-H01', 'verified': true}); ``` ## Cable adapters (JavaScript) ### `openWebSerial(port) → Promise` ```ts openWebSerial(port: SerialPort): Promise ``` 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`. ```js const s = await connect(await openWebSerial(await navigator.serial.requestPort())); ``` ### `fromSerialPort(port, opts?) → Promise` ```ts fromSerialPort(port: SerialPort, o?: { wake?: (lowMs: number) => Promise; closeStream?: boolean }): Promise ``` 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. ```js 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` ```ts fromDuplex(stream: Duplex, o?: { setBreak?: (on: boolean) => Promise; wake?: (lowMs: number) => Promise; 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`. ```js 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`. ```dart 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`. ```dart static Future open(UsbPort port, {Future 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). ```dart 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. | ```dart await emulatedWake( 70, setBaud: (baud) async { /* switch your chip, including back to 10400 */ }, write: (bytes) async { /* write these bytes */ }, ); ``` `setBaud` is `Future Function(int baud)`. `write` is `Future 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. ```ts new FakeEcuTransport(o?: { replies?: Record string | null)>; raw?: Record; bench?: boolean; // default true echo?: boolean; // default true chunkSize?: number; // default 0 = one chunk }) ``` ```dart FakeEcuTransport({ Map replies = const {}, Map 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`. | 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. ```js const s = await connect(new FakeEcuTransport(), { sleep: async () => {} }); console.log((await s.identify()).ecmId); // 0104780D01 ``` ```dart 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. ```js SPEC.kline.physical.baud; // 10400 ``` ```dart 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 → `[]`. ```js core.fromHex('72 05 71 00 18'); ``` ```dart 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. ```js 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. ```js 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
` 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` is `Map`). ### `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`. ```js 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. ```js 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. ```js const c = core.chooseProfile(0x17, bytes, { makerHint: 'keihin' }); c?.profile.id; ``` ```dart 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). ```js core.describeDtc('7-1'); // { meaning: "engine temperature sensor, signal too low", critical: false, benchConfirmed: true } ``` ```dart describeDtc('7-1').meaning; ``` Next: [Identify and API key](https://developers.smongrot.com/docs/identify) ============================================================================== # FILE: site/protocol.md ============================================================================== # Protocol overview (level 1) [ภาษาไทย](th/protocol.md) > Level-1 K-Line: 10400 8N1, wake, session, checksum, live tables, and fault-code reads. Full rules: [kline](https://developers.smongrot.com/spec/kline.json), [live](https://developers.smongrot.com/spec/live.json), [dtc](https://developers.smongrot.com/spec/dtc.json). ## Wire - ISO 9141 K-Line: one wire, half-duplex, **10400 baud 8N1**. - The cable **echoes** every byte you send before the ECU answers. Strip it (exact copy, or a copy with bits only cleared when a valid reply follows). - Frame: `[header][total length incl. checksum][service][args…][checksum]`. Requests start `0x72` (or `0xFE` for StartComm); replies start `0x02`. - **Checksum** = `(0x100 − (sum of bytes mod 256)) mod 256`. A valid frame sums to 0 mod 256. A plain sum is wrong. Example: `72 07 72 17 00 0F` → `EF`. ## Session 1. Wake: line LOW for **70 ms**, timed atomically, then idle 130 ms. 2. StartComm `FE 04 72 8C` (a reply is not required). 3. Liveness: `72 05 00 F0 99`, then `72 05 71 00 18`, then `7E 06 01 01 00 7A`. The first one that gets any reply means the session is up. Retry wake 1–3 up to 4 times. 4. StartDiag `72 05 71 00 18` (required before the live tables answer). 5. ECM-ID `72 07 72 00 00 05 10` → `02 0B 72 00 00 <5 bytes> ck`. Up to 3 tries, 300 ms apart. Fall back to the ID inside the StartDiag reply. ## Live data Read `72 07 72
00 ck` and cut the data bytes from the last valid `02 L 72
` frame. Each field is `raw × scale + add` over big-endian bytes, with sentinels (absent), ranges (invalid), clamps, per-ECM-ID sources and fallback chains. Every value carries a provenance: bench / field / reference / provisional. Five layouts exist (`t17.sub8` Keihin, `t17.sub4` Shindengen, `t13.type7`, `t11.type1`, `generic.t17`). The SDK detects the layout by probing tables `0x17 → 0x13 → 0x11`. ## Fault codes (beta) `72 05 74 01/02/03` → `02 0C 74 ck`. The payload is a `00` lead byte followed by (code, sub) pairs, read as Honda blink codes such as `7-1`. Only Keihin boxes are decoded. If anything does not parse, the result is "unreadable", never a guess. Next: [Troubleshooting](https://developers.smongrot.com/docs/troubleshooting) ============================================================================== # FILE: site/troubleshooting.md ============================================================================== # Troubleshooting [ภาษาไทย](th/troubleshooting.md) > Every error `code` the SDK throws or reports, what caused it, and what to change. JavaScript throws `SmongrotError` (`e.code`, `e.message`). Dart throws `SmongrotException` (same fields). Catch those two types. A model lookup never throws: `lookupModel` returns `null` and, except for "unknown ECU", calls `onError`. ```js try { const s = await connect(transport); } catch (e) { if (e instanceof SmongrotError) console.error(e.code, e.message); else throw e; } ``` ```dart try { final s = await connect(transport); } on SmongrotException catch (e) { print('${e.code} ${e.message}'); } ``` Adapter and browser failures sometimes reject with the underlying error and no `code` (a DOMException from WebSerial, a stream error from `fromDuplex`). Handle `SmongrotError` first, then the rest. ## Session ### `ECU_SILENT` No liveness reply after 4 wakes (LOW 70 ms, idle 130 ms, StartComm, three probes). The message is `no answer after wake (key ON? cable on the DLC?)`. **Cause.** Key OFF, cable on the wrong plug, wrong serial port, baud not 10400, or a wake the box ignored. **Fix.** Key ON. Confirm the port path. See [Hardware](https://developers.smongrot.com/docs/hardware). Then retry. A Shindengen box just switched to key ON often needs an atomic 70 ms wake (FTDI bit-bang); the Android pulse is about 45 ms and the desktop adapters use an OS break. `connect` already retries 4 times. That 4 is the default. Call `connect` again, or pass a higher `wakeTries`, when you have a reason. ### `BAD_STATE` The call does not match `session.state`. The message is `session is , needs `. **Cause.** `identify`, `detect`, `live` or `dtc.read` while state is not `ready`. The usual case is calling `dtc.read()` or a second `live()` from inside the live loop (`state` is `live`). Also: using the session before `connect` resolves, or after `close()`. **Fix.** `await` `connect` first. Break the live loop (or abort the signal / cancel the Dart subscription) and wait until it finishes. `state` returns to `ready`. Then read fault codes. Do not assign `state` yourself. ### `LIVE_UNSUPPORTED` `live()` probed `0x17`, `0x13` and `0x11` and no table returned data. **Cause.** The session is up, but this box did not answer a live table. Also a cable that dies after wake, or a table timeout (500 ms) on a very slow link. **Fix.** Stay on this session and call `identify()` — if the ECM-ID arrives, the bus is fine and this box has no level-1 live table (`detect()` returns `null`). If the ID is null too, fix the cable and reconnect. Do not fill the screen with zeros. ### `BAD_PROFILE` `live({ profile })` was given an id that is not in the spec. **Cause.** A typo, or a `liveProfile` string from the API that this SDK build does not contain. The API suggestion is often `null` anyway. **Fix.** Omit `profile` and let `live()` detect. Valid ids: `t17.sub8`, `t17.sub4`, `t13.type7`, `t11.type1`, `generic.t17`. ### `CLOSED` Any call that talks to the ECU after `close()`. **Cause.** A live loop or a late `identify` still running when you closed, or a second call on the same session. **Fix.** Drop the session. `connect` a new one. `close()` is final. ### `NO_WAKE` **Cause.** JavaScript: the transport has neither `wake(lowMs)` nor `setBreak(on)`. Dart desktop: the driver refused the break (`break on/off refused by the driver`). **Fix.** Use a shipped adapter, or implement `wake` (preferred) or `setBreak` on your transport. A `fromDuplex` stream needs `{ setBreak }` or `{ wake }` in the options. Passing `wake` to `fromSerialPort` uses that instead of the break. ### `FRAME_NOT_ALLOWED` **Cause.** Something tried to send a frame that is not in the SDK's read-only allowlist (session start, ECM ID read, keep-alive, live tables, fault-code read). The SDK refuses before anything reaches the cable. **Fix.** Nothing to fix in normal use: the public API only sends allowed frames. Writing, erasing and clearing fault codes are not possible through this SDK. ### `RESPONSE_TOO_LARGE` **Cause.** The device sent more than 4 KB for a single reply. A real ECU never does this at 10400 baud; it points to a wrong port, a faulty adapter or a device that is not an ECU. **Fix.** Check the port and the cable, then `connect` again. ## Adapters ### `BAD_PORT` `fromSerialPort` only. The value is not a `serialport` `SerialPort`, the baud is set and is not 10400, or the frame is not 8N1. **Fix.** `new SerialPort({ path, baudRate: 10400, dataBits: 8, stopBits: 1, parity: 'none', autoOpen: false })`. Leave baud unset only if you truly have not opened it yet; a wrong baud is rejected. ### `PORT_OPEN` Dart adapters. Desktop: `LibSerialPortTransport.open` could not open the path. Android: `UsbSerialTransport.open` got `false` from `port.open()` (permission denied or unplugged). **Fix.** Desktop: path from `SerialPort.availablePorts`, and permission on the device node. Android: call `device.create()` so the permission dialog can show, then `open` the port it returns. Plug the OTG cable in before listing. ### `WRITE_FAILED` Dart desktop only. `LibSerialPortTransport.write` did not accept every byte (the port write times out at 1000 ms). **Cause.** The port stalled or was unplugged mid-write. **Fix.** Close, replug, `connect` again. Android writes do not use this code; a USB error rejects the `Future` from `port.write`. ### `NO_FETCH` JavaScript only, thrown when you **create** `smongrotApi` and there is no `globalThis.fetch` and you did not pass `fetch`. **Fix.** Node 18+ has fetch. On an older runtime, pass `fetch` in the options. Dart has no such code (`http` is a real dependency). ## API key These codes are thrown only for `NO_API_KEY`. Every `API_*` code is delivered to `onError`. `lookupModel` still returns `null`, and `identify()` still returns the ECM-ID. ### `NO_API_KEY` `apiKey` is missing or blank. Thrown from `smongrotApi(...)` / `SmongrotApi(...)`, not from `identify`. **Fix.** Pass the key, or do not construct the helper. Without a helper, `connect` without `lookupModel` and `model` stays `null`. Get a free key at https://developers.smongrot.com. ### `API_BAD_INPUT` `onError`. The string passed to `lookupModel` is not 10 hex characters after spaces are removed and letters upper-cased. **Fix.** Pass `identity.ecmId`, which is already 10 upper-case hex, or do not call `lookupModel` when `ecmId` is null. ### `API_UNAUTHORIZED` `onError`. HTTP 401 or 403. **Fix.** The key is wrong, or it was stripped of the `Bearer` scheme. The helper sends `Authorization: Bearer ` itself. Pass the raw key, not a header. ### `API_RATE_LIMITED` `onError`. HTTP 429. The free key allows **1000 requests a day**. **Fix.** Cache the model for that ECM-ID in your app. Live data does not call the API. `identify()` caches too: one session looks up once. ### `API_NETWORK` `onError`. The request threw, or hit the timeout (default **5 s**, `timeoutMs` in JS, `timeout` in Dart). **Fix.** Offline is a supported state. Show the ECM-ID and leave the model as `—`. Raise `timeoutMs` only if your network is slow. Do not retry in a tight loop. ### `API_ERROR` `onError`. Any other HTTP error. `e.message` includes the status and the API's `error.code` / `error.message` when the body has them. **Fix.** Read `e.message`. The ECM-ID read from the box is still valid. ### `API_BAD_RESPONSE` `onError`. HTTP 200 but the JSON has no usable `data` (`model`, `ecu_code` or `maker`). **Fix.** Treat it as an unknown model. Do not parse the body a second way; `modelInfoFromApi` is the parser. ### Unknown ECU HTTP **404** returns `null` and does **not** call `onError`. The box is simply not in the catalog. Show the ECM-ID. ## Timeouts, NAK, echo These are not error codes. **Timeouts.** A command read stops after 120 ms of silence or 2000 ms. A live-table read stops after 120 ms of silence or 500 ms. Nothing is thrown. You get a short or empty reply: fields come back `absent`, or `dtc.read()` comes back `failed`. Fix the cable and the key before you touch `timing`. Override `commandTimeoutMs` / `tableTimeoutMs` (JS) or the matching `Timing` fields (Dart) only for a link you have measured as slow. **NAK.** A fault-code reply that contains the byte `0x7F` counts as no answer. If all three `72 05 74` reads are silent or NAK, `outcome` is `failed`. The SDK does not invent codes from a NAK. Reconnect with the key ON. Do not clear codes; v0.1 has no clear call. **Echo.** The session strips the echo of every frame it sends; you never handle it yourself. | `echo` | `distorted` | What happened | |---|---|---| | `true` | `false` | The cable echoed the request exactly. Normal. | | `true` | `true` | The echo only cleared bits (never set them) and a valid reply follows. Some USB cables do this. The reply is still used. | | `false` | `false` | The read-back did not start with the request. Wrong baud, a port that was not flushed, or two sessions on one cable. | `distorted: true` once in a session is not a failed read. `echo: false` plus an empty `reply` is the same symptom as `ECU_SILENT`: fix the port settings (10400 8N1, no flow control) and use one session. ## Symptoms that look like bugs **Rpm is 0, or a huge number like 17,500, and temperature is −30 °C.** The engine is off (key ON). Check `frame.engine === 'off'` (injector 0 ms and ignition 0°): rpm and temperature are then not real values. Show "engine off". A missing rpm (no table) is `absent`; show `—` for it. **Battery looks fine, other values are `absent`.** Check `frame.profile`. - `generic.t17` has only `rpm`, `tps`, `inj_ms`, `ign`. No temperature, no battery. - Shindengen (`t17.sub4`) reports `eot`, not `ect`. Looking up `ect` on that profile is always `absent`. - `o2r` is on a secondary table polled every 5 ticks, and given up after 3 misses. The first frames do not have it. - Shindengen `batt` is provisional. Raw `0` is `absent`, not 0.0 V. The extra battery source is polled every 10 ticks, except ECM-ID `0105950D01`, which is read from the primary table. - `primaryOk: false` clears the primary fields for that frame. Do not keep the previous numbers. **Shindengen, key just turned ON, `connect` fails or takes several tries.** The 70 ms wake has to be timed on the adapter. An OS break sometimes misses, and the Android ~45 ms pulse is specified as ignored by a Shindengen box fresh off key ON. Let the 4 retries finish. If it still throws `ECU_SILENT`, use an FTDI cable and pass an atomic `wake` / `atomicWake` that holds the line LOW for the `lowMs` you are given (70 ms). `connect` already wakes; an extra pulse before it only adds jitter. **`model` is null.** No `lookupModel` was passed, the key was rejected, the network failed, the daily limit was hit, or the ECU is unknown (404). `id.ecmId` is still the value from the box. Read `onError` to see which of the `API_*` codes it was. 404 is silent. **The browser has no `navigator.serial`.** WebSerial is desktop Chrome or Edge, in a secure context, called from a click. Firefox, Safari and phone browsers do not implement it. Use Node or the Flutter adapters. **Android `listDevices()` is empty.** The cable is not OTG, the plug is charge-only, or the phone is not in USB host mode. Re-list after the permission grant. `create()` returns null when the user denies it: that is `PORT_OPEN` only if you open a null port; check for null first (the example does). Next: [FAQ](https://developers.smongrot.com/docs/faq) ============================================================================== # FILE: site/faq.md ============================================================================== # FAQ [ภาษาไทย](th/faq.md) > Price, the MIT license, what leaves the device, where to ask, and what v0.2 adds. ## Is the SDK free? Yes. `@smongrot/sdk` and `smongrot_sdk` (and the two cable adapters) are free. The license is MIT. A **free API key** turns an ECM-ID into a model name, maker and part code. Live data and fault codes do not need a key and do not spend the quota. The key allows **1000 requests a day**. Over that, the call returns HTTP 429, `onError` gets `API_RATE_LIMITED`, and `model` is null. The ECM-ID from the box is unchanged. Get a key at https://developers.smongrot.com. ## Can I ship this in a commercial product? Yes. MIT lets you use, modify and sell software that includes the SDK. Keep the copyright notice and the license text with your copy. You do not need a separate commercial license for v0.1. Your app's own terms are yours. Do not put the API key in a public web page; look the model up on your server. See [Identify and API key](https://developers.smongrot.com/docs/identify). ## What does the SDK send off the device? Nothing, unless you pass `lookupModel`. `smongrotApi({ apiKey }).lookupModel` sends one request: `GET https://api.smongrot.com/v1/ecu/identify?ecm=<10 hex>` with `Authorization: Bearer `. The only ECU data in that request is the ECM-ID. Live frames, fault codes and the raw cable bytes stay on the machine. If you do not pass `lookupModel`, `identify()` still returns the ECM-ID and the SDK opens no socket. A failed lookup does not block diagnostics. Details: [Identify and API key](https://developers.smongrot.com/docs/identify). ## Where do I get help? Support channel: **placeholder** (not open in v0.1). Until a channel is listed on https://developers.smongrot.com, the error `code` plus [Troubleshooting](https://developers.smongrot.com/docs/troubleshooting) is the path that answers a failed `connect`. ## What is in v0.2? - The SMR board over Bluetooth LE, so a phone with no USB-serial port can run level 1. - iOS, through that board. A cable on iOS is still impossible. - Kotlin and Swift SDKs beside JavaScript and Dart. v0.2 is not in these packages. v0.1 stays read-only: no ECU write, no full ROM read, no fault-code clear. Next: [Overview](https://developers.smongrot.com/docs) ============================================================================== # FILE: spec/kline.json ============================================================================== { "$schema": "./schema/kline.schema.json", "spec": "smongrot.kline", "spec_version": "1.0.0-phase1", "level": 1, "status": "stable", "summary": "Honda PGM-FI diagnostic K-Line: physical layer, wake, session bring-up, frame format, checksum and echo handling. Level 1 = read-only diagnostics (identity, live data, DTC read).", "authority": "Reference implementation (framing, checksum, echo strip, USB session, ECM-ID retry, live pacing). Bench log: Shindengen Lead K2TA, FTDI cable, 2026-10-08.", "out_of_scope": [ "ROM / calibration read", "any ECU write, erase, flash, recovery", "access or programming procedures of any kind", "immobilizer", "DTC clear (service 0x60 changes ECU state)" ], "physical": { "bus": "ISO 9141 K-Line, one wire, half-duplex", "baud": 10400, "data_bits": 8, "parity": "none", "stop_bits": 1, "idle_level": "high (recessive)", "echo": "The transceiver (e.g. L9637D, FTDI cables) reads back every byte the tester sends, before the ECU reply. Strip it: see echo_strip.", "notes": [ "macOS FTDI FT232R can do non-standard bauds; level 1 only uses 10400.", "Some USB cables echo with bits cleared (never set); see echo_strip.distorted." ] }, "wake": { "summary": "ISO 9141 wake: hold the line LOW for low_ms, release HIGH, open the UART at 10400 8N1, wait idle_after_ms, then send StartComm.", "low_ms": 70, "idle_after_ms": 130, "before": [ "flush/purge RX", "set baud 10400" ], "must_be_atomic": true, "why_atomic": "The LOW width must be a tight 70 ms. Building it from separate remote commands (e.g. two BLE writes) adds tens of ms of jitter and the ECU wakes only sometimes. Time it locally on the adapter (board opcode 0x16, FTDI bit-bang).", "transports": { "usb_ftdi": "Bit-bang the TXD pin LOW for low_ms, then back to UART at 10400 (bench: Shindengen Lead K2TA answers this on the first try).", "usb_emulated": "Fallback for chips without bit-bang: switch to baud round(9000/low_ms) clamped to 200..600, send one 0x00 byte (start + 8 zero bits held low), wait ceil(10000/baud)+60 ms, back to 10400. At 70 ms this gives about 45 ms LOW; Shindengen boxes fresh off key-ON ignore it.", "board_ec20_tunnel": "Opcode 0x16 + u16 LE low_ms on the control characteristic (spec/board-ble.json raw_tunnel).", "board_klineble": "The SMR board wakes the bus itself (HIGH 100 ms, LOW 70 ms, idle 150 ms) before its own polls; the phone never times it (spec/board-ble.json klineble)." } }, "frames": { "summary": "Every frame = [header][total length incl. checksum][service][args...][checksum]. Requests from the tester start with 0x72 (diagnostic request) or 0xFE (StartComm); ECU replies start with 0x02.", "request": { "layout": [ "header (0x72)", "L = total bytes including checksum", "service", "args...", "checksum" ], "table_read": { "layout": "72 07 72
", "example": "72 07 72 17 00 0F EF", "note": "count = number of data bytes asked. Only 0x0000..0x00FF style small reads are level 1 (identity and live tables)." } }, "reply": { "layout": [ "0x02", "L = total bytes including checksum", "service echo (e.g. 0x72, 0x71, 0x74)", "args echo...", "data...", "checksum" ], "table_read": "02 L 72
(5 header bytes)", "valid_when": "L >= 4, the frame fits in the buffer, and all L bytes sum to 0 mod 256." } }, "checksum": { "name": "Honda 8-bit two's complement", "compute": "ck = (0x100 - (sum(body) mod 256)) mod 256", "equivalent_forms": [ "((sum & 0xFF) ^ 0xFF) + 1, then & 0xFF", "(-sum) & 0xFF" ], "edge_case": "When sum(body) mod 256 == 0 the checksum is 0x00. The form ((sum & 0xFF) ^ 0xFF) + 1 without the final & 0xFF gives 0x100 there: always mask.", "verify": "A frame (body + checksum) is valid when all its bytes sum to 0 mod 256.", "not_this": "A plain sum (sum & 0xFF) is WRONG: the ECU ignores such frames (a bug once seen in early firmware, fixed).", "worked_example": { "body": "72 07 72 17 00 0F", "sum": "0x72+0x07+0x72+0x17+0x00+0x0F = 0x111", "sum_mod_256": "0x11", "xor_ff": "0xEE", "plus_1": "0xEF", "frame": "72 07 72 17 00 0F EF" } }, "echo_strip": { "summary": "Applied to every raw read-back of one request (reference implementation). T = the exact request bytes, RAW = everything read back for it.", "rules": [ "exact: if RAW starts with T → echo = true, reply = RAW[len(T):] (even when what follows is not a valid frame or is empty).", "distorted: else if len(RAW) > len(T), every one of the first len(T) bytes only CLEARS bits of T ((RAW[i] & ~T[i]) == 0), and a valid reply frame starts at RAW[len(T)] → unless a valid frame starting at RAW[0] is LONGER than len(T), echo = true, distorted = true, reply = RAW[len(T):].", "otherwise: echo = false, reply = RAW unchanged (the reply is never cut on position alone)." ], "valid_reply_at": "valid frame at position p: p+2 <= len(RAW), L = RAW[p+1] >= 4, p+L <= len(RAW), RAW[p..p+L-1] sums to 0 mod 256. Its length is L.", "distorted_note": "Field: some USB cables echo with bits cleared. Counted once per session for telemetry; no other behaviour change.", "level2_note": "The app also accepts one fixed-length level-2 reply form in valid_reply_at; it never occurs in level-1 traffic and is not part of this spec." }, "session": { "summary": "Bring-up order used by the reference USB path (and by the EC20 raw tunnel). Bench trace: Shindengen Lead K2TA, FTDI cable, 2026-10-08.", "steps": [ { "id": "wake", "do": "wake (see wake)", "retry": "wake + start_comm + liveness together up to 4 attempts (kConnectWakeTries) before 'ECU silent'." }, { "id": "start_comm", "request": "FE 04 72 8C", "expect_reply": false, "note": "Reply not required: on the Shindengen bench only the echo came back." }, { "id": "liveness", "do": "Send each in order; the first with a non-empty echo-stripped reply = session up. None answered = no bike / key off → next wake attempt.", "requests": [ { "name": "ecm_query", "request": "72 05 00 F0 99", "bench_reply": "02 04 00 FA" }, { "name": "start_diag", "request": "72 05 71 00 18" }, { "name": "alt_keepalive", "request": "7E 06 01 01 00 7A", "note": "Some Keihin V850 boxes (Giorno/Lead) answer only this. Reproduced for parity with the app; it is a status poll, not a write." } ] }, { "id": "start_diag", "request": "72 05 71 00 18", "reply": "02 0F 71 00 <5-byte ECM-ID> <5 bytes> ", "bench_reply": "02 0F 71 00 01 04 78 0D 01 EE 00 00 00 00 05", "required": "Yes. Without it StartComm succeeds but the live tables stay silent (bench 2026-09-14)." }, { "id": "ecm_id", "request": "72 07 72 00 00 05 10", "reply": "02 0B 72 00 00 <5-byte ECM-ID> ", "bench_reply": "02 0B 72 00 00 01 04 78 0D 01 F6", "retry": { "tries": 3, "gap_ms": 300, "why": "The first ID read right after StartDiag can come back empty." }, "fallback": "If no valid ID frame: use the ECM-ID from this session's StartDiag reply.", "format": "10 upper-case hex chars, e.g. 0104780D01" }, { "id": "live", "do": "Detect the profile and poll (spec/live.json)." } ], "ecm_id_extraction": { "summary": "ECM-ID bytes over an echo-stripped reply.", "rules": [ "Prefer the FIRST position i (scanning forward) where RAW[i..] = 02 0B 72 00 00 and RAW[i..i+10] sums to 0 mod 256: ID = RAW[i+5..i+9].", "Else the FIRST position where RAW[i..] = 02 0F 71 00 and RAW[i..i+14] sums to 0 mod 256: ID = RAW[i+4..i+8].", "Else no ID (never a slice taken by position)." ] } }, "timing": { "command_quiet_ms": 120, "command_timeout_ms": 2000, "table_read_quiet_ms": 120, "table_read_timeout_ms": 500, "dtc_gap_ms": 60, "live_min_gap_ms": 60, "note": "A read ends after quiet_ms of RX silence (the window restarts on every received chunk and starts right after the write) or at timeout_ms. Values are what the app uses, not ECU limits." } } ============================================================================== # FILE: spec/live.json ============================================================================== { "$schema": "./schema/live.schema.json", "spec": "smongrot.live", "spec_version": "1.0.0-phase1", "level": 1, "status": "stable", "summary": "Honda K-Line live data (engine sensors). Poll one or more 0x72 table reads, cut the data bytes out of each reply, and decode every field from a declarative rule. Requires an open diagnostic session (spec/kline.json session).", "authority": "Reference implementation (live decoder, detector and profile set). If this file and the reference implementation ever disagree, the reference wins and this file is a bug.", "derived_from": { "file": "reference implementation: live profile set", "schema_v": 1, "profile_set_version": 2 }, "reply_extraction": { "summary": "How the data bytes of one table read are taken from the echo-stripped reply (reference table read).", "steps": [ "Strip the TX echo (spec/kline.json echo_strip). Call the rest R.", "Scan start index i from len(R)-4 down to 0 (the LAST matching frame wins).", "Skip i unless R[i] == 0x02 and R[i+2] == request[2] (service byte, 0x72) and R[i+3] == request[3] (table byte).", "L = R[i+1] (total frame length incl. the checksum). Skip i unless L >= reply_header_len + 1 and i + L <= len(R).", "Skip i unless the bytes R[i .. i+L-1] sum to 0 mod 256 (spec/kline.json checksum.verify).", "data = R[i+reply_header_len .. i+L-2] (after the header, before the checksum).", "If len(data) >= data_len return data, else return NO DATA. Stop at this first checksum-valid match either way (do not keep scanning).", "No match: NO DATA." ], "header_layout": "Reply = 02 L 72
; reply_header_len 5 for every profile table.", "no_data_means": "The table is absent for this tick: every field read from it is 'absent'." }, "value_rule": { "summary": "Per source: raw = unsigned big-endian integer over `width` bytes at data[offset]. If raw is in null_if → absent. value = raw * scale + add (IEEE-754 double, in that order). If range is given and value < range[0] or value > range[1] → invalid. Then, if clamp is given, value = min(max(value, clamp[0]), clamp[1]). Otherwise ok.", "absent_when": [ "the source's table has no data yet", "offset + width > len(data)", "raw is listed in null_if" ], "invalid_when": [ "value outside range (inclusive bounds)" ], "chain": [ "A field has 1..n sources tried in order. A source with `ecm` is skipped (not read at all) unless the session's ECM-ID, normalised (whitespace removed, upper case), is in that list; an unknown ECM-ID skips it too.", "absent → try the next source.", "invalid → the FIELD is invalid; stop. An out-of-range value is never masked by a later source.", "ok and the field has no `agree` → the field is this value; stop.", "ok and the field has `agree` → keep the first ok value, keep reading later sources: if a later source is invalid → field invalid; if a later source is ok and |later - first| > agree → field invalid; else continue. At the end the field is the FIRST ok value.", "No ok source → absent. Never 0." ], "result": "Each field yields {status: ok|absent|invalid, value (only when ok), prov, source (table id of the winning source, only when ok)}.", "prov_rule": "ok → the winning source's prov. absent/invalid → the first source's prov. Exception: v2_provisional (see detection.match_v2) forces prov = provisional for the listed fields in every status.", "prov_values": { "bench": "proven on a real ECU on the bench", "field": "consistent across real field logs, not meter-checked", "reference": "from the reference live-data tool source only", "provisional": "single sample / inferred; show it, but ask the rider to confirm before any decision" }, "every_field_reported": "Decode returns an entry for every field of the profile, even when its table never answered." }, "units": { "rpm": "engine speed, rev/min", "tps_v": "throttle sensor volts", "tps": "throttle opening, % of the box's full-open angle (0..100). The raw byte is the angle in 0.5 degree steps.", "ect": "engine temperature, degC (coolant or oil, depending on the bike; display label only)", "eot": "engine temperature, degC (Shindengen layout)", "batt": "battery volts as the ECU measures it", "inj_ms": "injector pulse width, ms", "ign": "ignition advance, degrees", "ltft": "long-term fuel trim, %", "o2r": "narrowband O2 sensor raw byte (1..255); see derived_values" }, "derived_values": [ { "key": "o2_v", "from": "o2r", "formula": "o2r * 0.0195", "unit": "V", "prov": "provisional", "source": "Reference implementation (8-bit ADC over 5 V). The reference live-data tool uses o2r / 753.75 * 14.7 (= o2r * 0.019502), equal within 0.0005 V for every raw byte.", "note": "Display only. Narrowband O2 says rich/lean side, not an AFR number." } ], "polling": { "tick_unit_ms": 300, "summary": "A table's poll_every_ticks counts ticks of tick_unit_ms wall time (the board firmware's POLL_MS). The primary table is read every tick; at most ONE secondary table per tick, round-robin. A secondary with give_up_after_misses = N is not asked again this session after N misses in a row while the primary answered.", "usb_target_tick_ms": 150, "min_gap_between_frames_ms": 60, "read_timeout_ms": 500, "read_quiet_ms": 120, "source": "Reference implementation (USB live pacing, table read)." }, "detection": { "summary": "Pick a profile once per connect (reference detector, probe branch).", "probe_table_order": [ 23, 19, 17 ], "probe_table_order_hex": [ "0x17", "0x13", "0x11" ], "probe_request_source": "For each table byte, the request of the first profile (in file order) whose primary table has that table byte.", "tries_per_table": 2, "steps": [ "For each probe table in order: send its request up to tries_per_table times until reply_extraction gives data. No data → next table.", "On data: candidates = non-generic profiles whose primary table has this table byte and whose match rules ALL hold on {primary: data}.", "match_v2 off (default): use `match`. match_v2 on: a profile with `match_v2` uses those rules instead; a profile that matched ONLY by match_v2 (its `match` rules fail) is dropped when a maker hint is given and differs from the profile maker.", "Sort candidates by specificity (number of rules in the active rule list) descending, then range_score descending. Take the first → method 'probed'.", "No candidate → the first generic profile on this table → method 'generic'. No generic → next table.", "No table answered → no profile (connected, live data not supported)." ], "rule_test": "A rule reads raw = unsigned big-endian over width bytes at data[offset] of its table (false when the table is missing or too short). eq: raw must equal eq. ne: raw must not equal ne. A profile with no rules always matches.", "range_score": "Decode the frame with NO ECM-ID; among fields whose status is not absent, the fraction that are ok (0 when none). Used only as a tie-break.", "maker_hint": "From the part code: '38770-' → keihin, '30400-' → shindengen, else none. The observed layout always wins; mismatch = hint and profile maker both set and different (never on a generic profile).", "match_v2": { "flag": "live_temp_v2", "default": false, "summary": "App build flag (internal-test builds only, not server-controlled). When on, profiles that have match_v2 use it in place of match, and fields in v2_provisional get prov = provisional on a frame that matches only by match_v2.", "why": "The reference live-data tool picks Type-4 sub 4 only when data[4..5] == FF FF; build 196's rule (data[4] != FF) sent some Keihin frames to generic.t17 (no temperature)." }, "cache": "Optional, app-specific: remember profile id per ECM-ID; on reconnect validate with one primary read + match, else drop the cache and probe. A cached generic profile is always dropped and re-probed.", "tie_note": "On the shipped profiles no two candidates on one table can both match, so the tie-break order never decides a real frame." }, "profiles": [ { "id": "t17.sub8", "maker": "keihin", "generic": false, "notes": [ "Keihin Type-4 layout (bench: Wave 110i 38770-K03-H01, 2026-10-02). Request 72 07 72 17 00 0F EF is the reference tool's 'Table 20' read for ECM Type 4.", "tps: data[3] is the throttle angle in 0.5 degree steps; shown as % of the box's full-open angle (scale = 50 / full-open degrees, rounded up). Full-open per ECM-ID from real ride plateaus (not meter-checked): 01040F0D01 78, 0105550D01 79, 01033E0D01 74, 0103FA0D01 73, everything else 80.", "t20 = narrowband O2 table 0x20 (reference tool _cmdO2, read every few cycles). o2r = data[0]; 0 = no reading. Not captured on a running bike yet.", "v2_provisional batt: a frame that matches only by match_v2 (data[4] = FF) is on a layout no bench confirmed for that box, so its battery is provisional." ], "primary": "t17", "tables": { "t17": { "request": "72 07 72 17 00 0F EF", "reply_header_len": 5, "data_len": 15, "poll_every_ticks": 1, "optional": false, "give_up_after_misses": null }, "t20": { "request": "72 07 72 20 00 0B EA", "reply_header_len": 5, "data_len": 1, "poll_every_ticks": 5, "optional": true, "give_up_after_misses": 3 } }, "match": [ { "table": "t17", "offset": 4, "width": 1, "ne": 255 } ], "match_v2": [ { "table": "t17", "offset": 4, "width": 2, "ne": 65535 } ], "v2_provisional": [ "batt" ], "fields": [ { "key": "rpm", "unit": "rpm", "sources": [ { "table": "t17", "offset": 0, "width": 2, "scale": 1, "add": 0, "null_if": [], "prov": "bench", "range": [ 0, 20000 ] } ] }, { "key": "tps_v", "unit": "V", "sources": [ { "table": "t17", "offset": 2, "width": 1, "scale": 0.0195, "add": 0, "null_if": [], "prov": "reference", "range": [ 0, 5.1 ] } ] }, { "key": "tps", "unit": "%", "sources": [ { "table": "t17", "offset": 3, "width": 1, "scale": 0.641026, "add": 0, "null_if": [], "prov": "field", "range": [ 0, 120 ], "clamp": [ 0, 100 ], "ecm": [ "01040F0D01" ] }, { "table": "t17", "offset": 3, "width": 1, "scale": 0.632912, "add": 0, "null_if": [], "prov": "field", "range": [ 0, 120 ], "clamp": [ 0, 100 ], "ecm": [ "0105550D01" ] }, { "table": "t17", "offset": 3, "width": 1, "scale": 0.675676, "add": 0, "null_if": [], "prov": "field", "range": [ 0, 120 ], "clamp": [ 0, 100 ], "ecm": [ "01033E0D01" ] }, { "table": "t17", "offset": 3, "width": 1, "scale": 0.684932, "add": 0, "null_if": [], "prov": "field", "range": [ 0, 120 ], "clamp": [ 0, 100 ], "ecm": [ "0103FA0D01" ] }, { "table": "t17", "offset": 3, "width": 1, "scale": 0.625, "add": 0, "null_if": [], "prov": "field", "range": [ 0, 120 ], "clamp": [ 0, 100 ] } ] }, { "key": "ect", "unit": "degC", "sources": [ { "table": "t17", "offset": 5, "width": 1, "scale": 1, "add": -40, "null_if": [ 255 ], "prov": "bench", "range": [ -40, 160 ] } ] }, { "key": "batt", "unit": "V", "sources": [ { "table": "t17", "offset": 10, "width": 1, "scale": 0.1, "add": 0, "null_if": [ 0 ], "prov": "bench", "range": [ 6, 18 ] } ] }, { "key": "inj_ms", "unit": "ms", "sources": [ { "table": "t17", "offset": 11, "width": 2, "scale": 0.004, "add": 0, "null_if": [], "prov": "bench", "range": [ 0, 100 ] } ] }, { "key": "ign", "unit": "deg", "sources": [ { "table": "t17", "offset": 13, "width": 1, "scale": 0.5, "add": -64, "null_if": [], "prov": "bench", "range": [ -64, 64 ] } ] }, { "key": "ltft", "unit": "%", "sources": [ { "table": "t17", "offset": 14, "width": 1, "scale": 0.78, "add": -100, "null_if": [], "prov": "reference", "range": [ -100, 100 ] } ] }, { "key": "o2r", "unit": "raw", "sources": [ { "table": "t20", "offset": 0, "width": 1, "scale": 1, "add": 0, "null_if": [ 0 ], "prov": "reference", "range": [ 1, 255 ] } ] } ] }, { "id": "t17.sub4", "maker": "shindengen", "generic": false, "notes": [ "Shindengen Type-4 layout (bench: Lead 30400-K2TA-T02, 2026-10-02 and 2026-10-08). EOT proven by a bench knob sweep.", "batt chain: t17 data[10] x 0.1 V, read ONLY on ECM-ID 0105950D01 (Lead 125 K2TG; inferred from field logs, the reference tool has no Shindengen case), then D0 data[0] on every sub4 box. Both provisional until a multimeter check. 0 = absent; out of range or the two more than 0.5 V apart = invalid.", "tps full-open 85 degrees from one Shindengen ride (provisional until more rides)." ], "primary": "t17", "tables": { "t17": { "request": "72 07 72 17 00 0F EF", "reply_header_len": 5, "data_len": 15, "poll_every_ticks": 1, "optional": false, "give_up_after_misses": null }, "d0": { "request": "72 07 72 D0 00 10 35", "reply_header_len": 5, "data_len": 16, "poll_every_ticks": 10, "optional": true, "give_up_after_misses": null } }, "match": [ { "table": "t17", "offset": 4, "width": 1, "eq": 255 }, { "table": "t17", "offset": 5, "width": 1, "eq": 255 } ], "fields": [ { "key": "rpm", "unit": "rpm", "sources": [ { "table": "t17", "offset": 0, "width": 2, "scale": 1, "add": 0, "null_if": [], "prov": "bench", "range": [ 0, 20000 ] } ] }, { "key": "tps_v", "unit": "V", "sources": [ { "table": "t17", "offset": 2, "width": 1, "scale": 0.0195, "add": 0, "null_if": [], "prov": "reference", "range": [ 0, 5.1 ] } ] }, { "key": "tps", "unit": "%", "sources": [ { "table": "t17", "offset": 3, "width": 1, "scale": 0.588236, "add": 0, "null_if": [], "prov": "field", "range": [ 0, 120 ], "clamp": [ 0, 100 ] } ] }, { "key": "eot", "unit": "degC", "sources": [ { "table": "t17", "offset": 9, "width": 1, "scale": 1, "add": -40, "null_if": [ 255 ], "prov": "bench", "range": [ -40, 160 ] } ] }, { "key": "batt", "unit": "V", "agree": 0.5, "sources": [ { "table": "t17", "offset": 10, "width": 1, "scale": 0.1, "add": 0, "null_if": [ 0 ], "prov": "provisional", "range": [ 6, 18 ], "ecm": [ "0105950D01" ] }, { "table": "d0", "offset": 0, "width": 1, "scale": 0.1, "add": 0, "null_if": [ 0 ], "prov": "provisional", "range": [ 6, 18 ] } ] }, { "key": "inj_ms", "unit": "ms", "sources": [ { "table": "t17", "offset": 11, "width": 2, "scale": 0.004, "add": 0, "null_if": [], "prov": "bench", "range": [ 0, 100 ] } ] }, { "key": "ign", "unit": "deg", "sources": [ { "table": "t17", "offset": 13, "width": 1, "scale": 0.5, "add": -64, "null_if": [], "prov": "bench", "range": [ -64, 64 ] } ] } ] }, { "id": "t13.type7", "maker": "keihin", "generic": false, "notes": [ "Keihin Type-7 per the reference tool ParseType7 (table 0x13, 14 bytes). Not bench-proven." ], "primary": "t13", "tables": { "t13": { "request": "72 07 72 13 00 0E F4", "reply_header_len": 5, "data_len": 14, "poll_every_ticks": 1, "optional": false, "give_up_after_misses": null }, "t20": { "request": "72 07 72 20 00 0B EA", "reply_header_len": 5, "data_len": 1, "poll_every_ticks": 5, "optional": true, "give_up_after_misses": 3 } }, "match": [], "fields": [ { "key": "rpm", "unit": "rpm", "sources": [ { "table": "t13", "offset": 0, "width": 2, "scale": 1, "add": 0, "null_if": [], "prov": "reference", "range": [ 0, 20000 ] } ] }, { "key": "tps", "unit": "%", "sources": [ { "table": "t13", "offset": 3, "width": 1, "scale": 0.625, "add": 0, "null_if": [], "prov": "reference", "range": [ 0, 120 ], "clamp": [ 0, 100 ] } ] }, { "key": "ect", "unit": "degC", "sources": [ { "table": "t13", "offset": 5, "width": 1, "scale": 1, "add": -40, "null_if": [ 255 ], "prov": "reference", "range": [ -40, 160 ] } ] }, { "key": "batt", "unit": "V", "sources": [ { "table": "t13", "offset": 10, "width": 1, "scale": 0.1, "add": 0, "null_if": [ 0 ], "prov": "reference", "range": [ 6, 18 ] } ] }, { "key": "inj_ms", "unit": "ms", "sources": [ { "table": "t13", "offset": 11, "width": 2, "scale": 0.004, "add": 0, "null_if": [], "prov": "reference", "range": [ 0, 100 ] } ] }, { "key": "ign", "unit": "deg", "sources": [ { "table": "t13", "offset": 13, "width": 1, "scale": 0.5, "add": -64, "null_if": [], "prov": "reference", "range": [ -64, 64 ] } ] }, { "key": "o2r", "unit": "raw", "sources": [ { "table": "t20", "offset": 0, "width": 1, "scale": 1, "add": 0, "null_if": [ 0 ], "prov": "reference", "range": [ 1, 255 ] } ] } ] }, { "id": "t11.type1", "maker": "keihin", "generic": false, "notes": [ "Keihin Type-1 per the reference tool ParseType1 (table 0x11, 20 bytes). LTFT omitted: its reference offset is past the table. Not bench-proven." ], "primary": "t11", "tables": { "t11": { "request": "72 07 72 11 00 14 F0", "reply_header_len": 5, "data_len": 20, "poll_every_ticks": 1, "optional": false, "give_up_after_misses": null }, "t20": { "request": "72 07 72 20 00 0B EA", "reply_header_len": 5, "data_len": 1, "poll_every_ticks": 5, "optional": true, "give_up_after_misses": 3 } }, "match": [], "fields": [ { "key": "rpm", "unit": "rpm", "sources": [ { "table": "t11", "offset": 0, "width": 2, "scale": 1, "add": 0, "null_if": [], "prov": "reference", "range": [ 0, 20000 ] } ] }, { "key": "tps", "unit": "%", "sources": [ { "table": "t11", "offset": 3, "width": 1, "scale": 0.625, "add": 0, "null_if": [], "prov": "reference", "range": [ 0, 120 ], "clamp": [ 0, 100 ] } ] }, { "key": "ect", "unit": "degC", "sources": [ { "table": "t11", "offset": 5, "width": 1, "scale": 1, "add": -40, "null_if": [ 255 ], "prov": "reference", "range": [ -40, 160 ] } ] }, { "key": "batt", "unit": "V", "sources": [ { "table": "t11", "offset": 12, "width": 1, "scale": 0.1, "add": 0, "null_if": [ 0 ], "prov": "reference", "range": [ 6, 18 ] } ] }, { "key": "inj_ms", "unit": "ms", "sources": [ { "table": "t11", "offset": 14, "width": 2, "scale": 0.004, "add": 0, "null_if": [], "prov": "reference", "range": [ 0, 100 ] } ] }, { "key": "ign", "unit": "deg", "sources": [ { "table": "t11", "offset": 16, "width": 1, "scale": 0.5, "add": -64, "null_if": [], "prov": "reference", "range": [ -64, 64 ] } ] }, { "key": "o2r", "unit": "raw", "sources": [ { "table": "t20", "offset": 0, "width": 1, "scale": 1, "add": 0, "null_if": [ 0 ], "prov": "reference", "range": [ 1, 255 ] } ] } ] }, { "id": "generic.t17", "maker": null, "generic": true, "notes": [ "Fallback when table 0x17 answers but no sub-layout matches: only fields proven identical on Keihin AND Shindengen." ], "primary": "t17", "tables": { "t17": { "request": "72 07 72 17 00 0F EF", "reply_header_len": 5, "data_len": 15, "poll_every_ticks": 1, "optional": false, "give_up_after_misses": null } }, "match": [], "fields": [ { "key": "rpm", "unit": "rpm", "sources": [ { "table": "t17", "offset": 0, "width": 2, "scale": 1, "add": 0, "null_if": [], "prov": "bench", "range": [ 0, 20000 ] } ] }, { "key": "tps", "unit": "%", "sources": [ { "table": "t17", "offset": 3, "width": 1, "scale": 0.625, "add": 0, "null_if": [], "prov": "field", "range": [ 0, 120 ], "clamp": [ 0, 100 ] } ] }, { "key": "inj_ms", "unit": "ms", "sources": [ { "table": "t17", "offset": 11, "width": 2, "scale": 0.004, "add": 0, "null_if": [], "prov": "bench", "range": [ 0, 100 ] } ] }, { "key": "ign", "unit": "deg", "sources": [ { "table": "t17", "offset": 13, "width": 1, "scale": 0.5, "add": -64, "null_if": [], "prov": "bench", "range": [ -64, 64 ] } ] } ] } ] } ============================================================================== # FILE: spec/dtc.json ============================================================================== { "$schema": "./schema/dtc.schema.json", "spec": "smongrot.dtc", "spec_version": "1.0.0-phase1", "level": 1, "status": "beta", "summary": "Honda PGM-FI stored fault codes: send three 72 05 74 0x reads, cut the payload out of each reply, decode (code, sub) pairs as Honda blink codes.", "status_reason": "The 72 05 74 0x frames answer on real boxes, and one bench run with two induced faults (Keihin K03-H01, 2026-11-04) gave 07 01 / 08 01. The code meaning of those bytes (Honda blink code, plain binary) is INFERRED, no box with a naturally stored fault has been read, and only the Keihin layout was ever seen. Treat output as beta.", "authority": "Reference implementation (fault-code read frames, decoder and scan result rules).", "requires": "An open diagnostic session (spec/kline.json session, StartDiag sent).", "read": { "requests": [ { "sub": 1, "request": "72 05 74 01 14" }, { "sub": 2, "request": "72 05 74 02 13" }, { "sub": 3, "request": "72 05 74 03 12" } ], "gap_ms": 60, "reply": "02 0C 74 <7-byte payload> ", "bench_replies": { "74 01 (ECT knob at max temp + TPS knob at 0)": "02 0C 74 01 00 07 01 08 01 00 00 6C", "74 02": "02 0C 74 02 00 00 00 00 00 00 00 7C", "74 03": "02 0C 74 03 00 00 00 00 00 00 00 7B" } }, "payload_extraction": { "summary": "Payload of one reply (per sub) over an echo-stripped reply.", "steps": [ "Scan i from len(R)-5 down to 0 (the LAST matching frame wins).", "Skip i unless R[i] == 0x02 and R[i+2] == 0x74, and (when sub is given) R[i+3] == sub.", "L = R[i+1]; skip unless L >= 6 and i + L <= len(R).", "Skip unless R[i .. i+L-1] sums to 0 mod 256.", "payload = R[i+4 .. i+L-2]." ], "none": "No such frame → that reply is unreadable." }, "payload_decode": { "summary": "Decode one payload. payload = [lead byte][code, sub] pairs.", "rules": [ "Unreadable (null) if the payload is empty or its length is even (must be 1 + 2n).", "Unreadable if payload[0] != 0x00 (0x00 is the only value ever seen; its meaning is unknown).", "For each pair (c, s): 00 00 = empty slot, skip; exactly one of them 0 = unreadable; else code c-s.", "Codes are de-duplicated, first-seen order kept." ], "encoding": "Plain binary, not BCD: 0x07 0x01 = blink code 7-1, 0x15 0x01 = 21-1 (INFERRED from the K03-H01 ROM code table).", "label": "\"-\", e.g. 7-1" }, "read_decode": { "summary": "Decode all replies of one scan (replies + subs).", "rules": [ "No replies → unreadable.", "If subs is given it must have one entry per reply, and reply k must carry sub subs[k].", "Any reply unreadable (no frame, or payload unreadable) → the WHOLE read is unreadable. Never guess.", "Else the union of all codes, de-duplicated in order. Empty list = clean." ] }, "maker_rule": { "summary": "Scan result rule: only Keihin boxes (part code 38770-) are decoded. Shindengen / unknown makers answer the same frames but any non-zero payload is reported 'unreadable' until bench-confirmed.", "outcomes": { "faults": "Keihin, read_decode gives at least one code", "clean": "every 74 reply answered and all payloads are zero", "unreadable": "a reply does not parse, or a non-Keihin box returned non-zero payload", "failed": "no reply (or only NAK) to any request" }, "nak": "A reply containing byte 0x7F is treated as a NAK (no answer) by the board's classifier." }, "codes": { "summary": "Generic Honda PGM-FI blink codes the app names. Best-known reference, NOT bench-proven except where bench_confirmed. Meanings translated from the app's Thai names; unknown codes are shown as their label only.", "voltage_split": { "codes": [ 1, 7, 8, 9, 54 ], "sub_1": "signal too low", "sub_2": "signal too high" }, "critical": { "codes": [ 12, 33, 52 ], "meaning": "the engine may not run right; stop and get it checked soon" }, "bench_confirmed": [ "7-1", "8-1" ], "list": [ { "code": 1, "meaning_en": "intake manifold pressure (MAP) sensor" }, { "code": 7, "meaning_en": "engine temperature sensor" }, { "code": 8, "meaning_en": "throttle position sensor" }, { "code": 9, "meaning_en": "intake air temperature sensor" }, { "code": 11, "meaning_en": "vehicle speed sensor" }, { "code": 12, "meaning_en": "injector" }, { "code": 21, "meaning_en": "O2 sensor" }, { "code": 23, "meaning_en": "O2 sensor heater" }, { "code": 29, "meaning_en": "idle air control valve" }, { "code": 33, "meaning_en": "ECU memory" }, { "code": 52, "meaning_en": "crank position sensor" }, { "code": 54, "meaning_en": "bank angle (fall) sensor" } ] }, "not_included": [ "An older OBD-style P-code packing in the reference implementation: a best-guess legacy mapping, never used on a real Honda reply.", "DTC clear (72 05 60 0x): changes ECU state and resets learned values; not level 1." ] } ============================================================================== # FILE: spec/board-ble.json ============================================================================== { "$schema": "./schema/board-ble.schema.json", "spec": "smongrot.board-ble", "spec_version": "1.0.0-phase1", "level": 1, "status": "stable", "summary": "Minimal BLE GATT needed for level 1 over a smongrot board. There are TWO firmwares with different GATT: `klineble` (what shipped SMR boards run: the board talks K-Line itself and sends decoded JSON) and `raw_tunnel` (dev firmware: the phone sends raw K-Line frames and times nothing but the wake). Pick by the service UUID the board exposes.", "authority": "SMR board firmware (KLineBLE, klineble-1.0.11) and the reference app BLE client; dev firmware raw tunnel. Level-1 commands only.", "out_of_scope": [ "image / OTA characteristics (ff13, ff15, EC24, EC27) and every write, flash, recovery, ROM-read or OTA command", "access or programming procedures of any kind" ], "klineble": { "status": "production (SMR boards)", "advertising": { "name": "SMR-<6 upper-case hex from the BT MAC>, e.g. SMR-A526F17C", "scan_by": "service 0000ff10-... OR the name prefix SMR- (iOS/macOS often put the service UUID only in the scan response, and may cache an old name)." }, "service": "0000ff10-0000-1000-8000-00805f9b34fb", "characteristics": { "cmd": { "uuid": "0000ff11-0000-1000-8000-00805f9b34fb", "props": [ "write", "write_without_response" ], "payload": "ASCII text command, no terminator" }, "data": { "uuid": "0000ff12-0000-1000-8000-00805f9b34fb", "props": [ "notify" ], "payload": "UTF-8: one JSON object or one text line per message" }, "ver": { "uuid": "0000ff14-0000-1000-8000-00805f9b34fb", "props": [ "read" ], "payload": "JSON {\"fw\": \"klineble-x.y.z\", \"hw\": ..., \"sn\": \"<6 hex>\", ...}; absent on legacy boards" } }, "mtu": { "board_sets": 512, "note": "A notify carries at most MTU-3 bytes; iOS may negotiate 185 (182 B) while a live JSON can be ~210 B." }, "reassembly": "Join ff12 notifies while a JSON object's braces are unbalanced (drop pieces older than 1 s or longer than 2048 B); a cut-off object never parses and must yield no value. Text lines pass through unchanged.", "wake_and_session": "Done by the board: HIGH 100 ms, LOW 70 ms, UART 10400 8N1, idle 150 ms, then FE 04 72 8C and 72 05 00 F0 99 (session up when that answers); up to 5 wakes; re-opened every 1.5 s while down. The realtime loop does not send StartDiag before polling.", "commands": [ { "cmd": "R", "does": "Start realtime. Board answers the line `STAT realtime on`, then one JSON object per successful poll (every 300 ms).", "board_poll_request": "72 05 71 17 01", "note": "The board polls 72 05 71 17 01, not the 72 07 72 17 00 0F EF read in spec/live.json. Its reply has 4 header bytes; the board decodes it itself (see realtime_json)." }, { "cmd": "S", "does": "Stop realtime. Answer `STAT realtime off`." }, { "cmd": "ECMID", "does": "Read the ECM-ID (72 07 72 00 00 05 10 on the wire).", "answer": "`ECMID <10 hex>` or `ECMID FAIL`", "parse": "split on whitespace; parts[0] == 'ECMID' and parts[1] matches ^[0-9A-Fa-f]{10}$ → upper-case it; anything else = no ID.", "note": "Send one at a time per link: two ECMIDs on one K-Line session collide. App timeout 12 s." }, { "cmd": "DTCPROBE", "status": "beta", "does": "Board opens a session, sends StartDiag, then a sweep of read candidates including 72 05 74 01/02/03 (labels RD_74_01..RD_74_03) and reports one line per candidate, 60 ms apart. Realtime stops; re-send R afterwards if wanted.", "line": "STAT dtcprobe