can-opener-js 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +419 -2
  2. package/dist/ble/index.cjs +1778 -0
  3. package/dist/ble/index.cjs.map +1 -0
  4. package/dist/ble/index.d.cts +234 -0
  5. package/dist/ble/index.d.ts +234 -0
  6. package/dist/ble/index.js +877 -0
  7. package/dist/ble/index.js.map +1 -0
  8. package/dist/chunk-5VWMNZJV.js +1004 -0
  9. package/dist/chunk-5VWMNZJV.js.map +1 -0
  10. package/dist/chunk-GK35KBVI.js +54 -0
  11. package/dist/chunk-GK35KBVI.js.map +1 -0
  12. package/dist/chunk-H53CBMCZ.js +348 -0
  13. package/dist/chunk-H53CBMCZ.js.map +1 -0
  14. package/dist/index.cjs +3262 -0
  15. package/dist/index.cjs.map +1 -0
  16. package/dist/index.d.cts +716 -0
  17. package/dist/index.d.ts +716 -0
  18. package/dist/index.js +3154 -0
  19. package/dist/index.js.map +1 -0
  20. package/dist/pairing-XB_GL-if.d.cts +359 -0
  21. package/dist/pairing-XB_GL-if.d.ts +359 -0
  22. package/dist/react-native-ble/index.cjs +150 -0
  23. package/dist/react-native-ble/index.cjs.map +1 -0
  24. package/dist/react-native-ble/index.d.cts +48 -0
  25. package/dist/react-native-ble/index.d.ts +48 -0
  26. package/dist/react-native-ble/index.js +104 -0
  27. package/dist/react-native-ble/index.js.map +1 -0
  28. package/dist/security/index.cjs +1204 -0
  29. package/dist/security/index.cjs.map +1 -0
  30. package/dist/security/index.d.cts +88 -0
  31. package/dist/security/index.d.ts +88 -0
  32. package/dist/security/index.js +172 -0
  33. package/dist/security/index.js.map +1 -0
  34. package/dist/transport/index.cjs +1177 -0
  35. package/dist/transport/index.cjs.map +1 -0
  36. package/dist/transport/index.d.cts +147 -0
  37. package/dist/transport/index.d.ts +147 -0
  38. package/dist/transport/index.js +1131 -0
  39. package/dist/transport/index.js.map +1 -0
  40. package/dist/types-Bv18cLeE.d.cts +278 -0
  41. package/dist/types-Bv18cLeE.d.ts +278 -0
  42. package/package.json +69 -4
package/README.md CHANGED
@@ -1,3 +1,420 @@
1
- # Temporary Holding Version
1
+ # can-opener-js
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ React-style vehicle state management for cars. `can-opener-js` gives TypeScript apps a
4
+ virtual vehicle object that monitors the state of a car through named signals and
5
+ uses named actions to control that state. It abstracts DBC files, CAN IDs, byte order,
6
+ scaling, masks, and bit-level signal packing behind named vehicle state.
7
+
8
+ Under the hood, it is a signal-first library for modeling virtual vehicles on
9
+ top of a interpreter layer. Can Opener interfaces with the OBD device.
10
+ Each connected vehicle owns its own vehicle profile, transport, controllers, APIs, and state, so multi-vehicle
11
+ apps do not need globals or shared registries. That makes vehicle scripts
12
+ portable: the same code can run across different cars by swapping the profile,
13
+ DBC files, and transport.
14
+
15
+ It turns signal names like `ENGINE_RPM`, `TURN_SIGNAL_LEFT`, and
16
+ `VEHICLE_SPEED` into DBC-aware state reads, subscriptions, queries, and actions while
17
+ leaving real CAN, BLE, firmware, and ISO-TP details to the transport layer.
18
+
19
+ ## Install
20
+
21
+ ```sh
22
+ npm install can-opener-js
23
+ ```
24
+
25
+ ## Quick Start
26
+
27
+ ```ts
28
+ import { VirtualVehicleManager } from "can-opener-js";
29
+ import { MockTransport } from "can-opener-js/transport";
30
+
31
+ const vv = new VirtualVehicleManager();
32
+ const car = await vv.connect({
33
+ id: "tesla-1",
34
+ transport: new MockTransport(),
35
+ profiles: [vehicleProfile],
36
+ });
37
+
38
+ // Subscribe to one signal. Firmware owns the streaming cadence.
39
+ const rpmSubscribed = await car.subscribe("ENGINE_RPM"); // true
40
+
41
+ // Or subscribe to related signals at once.
42
+ const bodySubscribed = await car.subscribe(["TURN_SIGNAL_LEFT", "HIGH_BEAMS"]); // true
43
+ const activeSubscriptions = car.subscriptionCount();
44
+
45
+ const speed = await car.query("VEHICLE_SPEED");
46
+ const rpm = car.state.engine_rpm;
47
+ const alsoRpm = car.state.get<number>("ENGINE_RPM");
48
+
49
+ await car.action("HORN");
50
+
51
+ await car.unsubscribe("ENGINE_RPM");
52
+ await car.unsubscribe(["TURN_SIGNAL_LEFT", "HIGH_BEAMS"]);
53
+ ```
54
+
55
+ ## Core Ideas
56
+
57
+ - Treat the vehicle like app state: subscribe to signals, read the latest values
58
+ from `car.state`, and run queries or actions through a consistent API.
59
+ - Applications use signal names. The DBC controller maps those names to CAN IDs,
60
+ bit layout, protocol metadata, and diagnostic bindings.
61
+ - `frame` signals are decoded from incoming CAN frames and can be subscribed to.
62
+ - Diagnostic signals are requested on demand through `query()` or polled through
63
+ `subscribeQuery()`.
64
+ - A transport only sends and receives frames. It does not need to parse DBC
65
+ files, know app-level signal names, or implement vehicle state.
66
+ - Multiple vehicles can be connected at the same time. Each vehicle has isolated
67
+ state and DBC bindings.
68
+
69
+ ## Profiles And DBC
70
+
71
+ DBC files define received CAN messages and signal bit layouts. YAML profiles
72
+ define the executable capabilities: endpoints, request/response queries,
73
+ actions, monitor subscriptions, applicability, and DBC mapping references. The
74
+ library does not ship a built-in catalog of PIDs, actions, request bytes, or
75
+ DBC mappings; loaded YAML+DBC files are the source of truth.
76
+
77
+ ```yaml
78
+ version: 1
79
+
80
+ dbc:
81
+ files:
82
+ - path: signals.dbc
83
+
84
+ endpoints:
85
+ obd:
86
+ request_id: 0x7DF
87
+ response_ids:
88
+ - range: [0x7E8, 0x7EF]
89
+ timeout_ms: 500
90
+
91
+ queries:
92
+ SPEED:
93
+ endpoint: obd
94
+ send: [0x02, 0x01, 0x0D, 0, 0, 0, 0, 0]
95
+ expect: [0x41, 0x0D]
96
+ dbc_mapping:
97
+ message: OBD_Response_7E8
98
+ signal: SPEED
99
+ ```
100
+
101
+ ```dbc
102
+ BO_ 2024 OBD_Response_7E8: 8 ECU
103
+ SG_ RESPONSE_SERVICE : 0|8@1+ (1,0) [0|255] "" Vector__XXX
104
+ SG_ PID M : 8|8@1+ (1,0) [0|255] "" Vector__XXX
105
+ SG_ SPEED m13 : 16|8@1+ (1,0) [0|255] "km/h" Vector__XXX
106
+ ```
107
+
108
+ Raw DBC-only loading is still supported for simple frame subscriptions and
109
+ legacy tests. In profile-backed vehicles, executable names come from YAML
110
+ `queries`, `actions`, and `signals` declarations.
111
+
112
+ See the [Vehicle Profile and Library Specification](docs/vehicle-profile-spec.md)
113
+ for YAML profiles, DBC files, capabilities, and the library contract, and
114
+ [Vehicle Keywords](docs/vehicle-keywords.md) for the common capability names
115
+ profiles should use. See the
116
+ [BLE Transport Protocol](docs/can-opener-se-ble-protocol.md) and
117
+ [Security Protocol](docs/can-opener-se-security-protocol.md) when implementing
118
+ an app for current Can Opener SE firmware.
119
+
120
+ DBC `VAL_` entries expose enum-like signal values as labels by default. Numeric
121
+ signals without matching `VAL_` entries return their DBC-scaled physical values:
122
+
123
+ ```dbc
124
+ BO_ 100 DRIVE_STATUS: 8 BCM
125
+ SG_ DRIVE_MODE : 0|2@1+ (1,0) [0|3] "" Vector__XXX
126
+
127
+ VAL_ 100 DRIVE_MODE 0 "park" 1 "reverse" 2 "drive" 3 "low";
128
+ ```
129
+
130
+ `DRIVE_MODE` remains the physical DBC signal, and subscribing to it updates
131
+ state to labels like `"park"` or `"drive"`. Profile `normalize` blocks can
132
+ remap car-specific DBC labels when a portable script needs a canonical
133
+ vocabulary.
134
+
135
+ The test fixtures include `tests/fixtures/vehicles/universal/pid/profile.yaml`
136
+ and `tests/fixtures/vehicles/universal/pid/signals.dbc` as a starter profile
137
+ pair for common OBD-II PID queries.
138
+
139
+ ## Connecting Vehicles
140
+
141
+ Use `VirtualVehicleManager` to connect and track vehicles:
142
+
143
+ ```ts
144
+ const manager = new VirtualVehicleManager();
145
+
146
+ const car = await manager.connect({
147
+ id: "car-a",
148
+ transport: new MockTransport(),
149
+ profiles: [profile],
150
+ });
151
+
152
+ manager.get("car-a");
153
+ manager.list();
154
+ await manager.disconnect("car-a");
155
+ await manager.disconnectAll();
156
+ ```
157
+
158
+ Calling `connect()` loads profile-declared DBC files, creates isolated
159
+ controllers and state, connects the transport, and wires incoming transport
160
+ frames into subscription decoding.
161
+
162
+ ## Subscriptions
163
+
164
+ Frame subscriptions are requested by signal name, and the underlying transport
165
+ subscription is tracked per CAN frame. Firmware owns the streaming cadence, so
166
+ `subscribe()` returns `true` once the firmware monitor list has accepted the
167
+ request. Frame subscriptions stay open until `unsubscribe()` is called.
168
+ If `TURN_SIGNAL_LEFT` and `HIGH_BEAMS` are encoded in the same CAN ID, the
169
+ vehicle keeps one frame subscription and modifies it as signal names are added
170
+ or removed. Diagnostic query polling is intentionally a separate API.
171
+
172
+ ```ts
173
+ const subscribed = await car.subscribe("ENGINE_RPM"); // true
174
+ const activeCount = car.subscriptionCount(); // 1
175
+
176
+ await car.unsubscribe("ENGINE_RPM");
177
+ ```
178
+
179
+ You can also declare related subscriptions together:
180
+
181
+ ```ts
182
+ const subscribed = await car.subscribe(["TURN_SIGNAL_LEFT", "HIGH_BEAMS"]); // true
183
+ const activeCount = car.subscriptionCount(); // 2
184
+
185
+ await car.unsubscribe(["TURN_SIGNAL_LEFT", "HIGH_BEAMS"]);
186
+ ```
187
+
188
+ Profile-backed subscriptions use names declared under YAML `signals`. Without
189
+ profile normalization, incoming values are the DBC-decoded values: enum labels
190
+ from `VAL_` when present, otherwise scaled physical numbers. A profile can add
191
+ `normalize.enum` to remap enum labels before values are written to `car.state`.
192
+
193
+ When multiple signals share a CAN frame, the transport receives one merged
194
+ subscription request for that frame. Removing the last active signal for a CAN
195
+ frame unsubscribes the transport from that frame.
196
+
197
+ Incoming frames update `car.state` only for actively subscribed signals:
198
+
199
+ ```ts
200
+ transport.emitFrame(car.dbc.encodeSignal("ENGINE_RPM", 900));
201
+
202
+ car.state.get<number>("ENGINE_RPM"); // 900
203
+ car.state.engine_rpm; // 900
204
+ ```
205
+
206
+ Query polling subscriptions use `subscribeQuery()`, which returns a handle that
207
+ can be passed to `unsubscribeQuery()` later:
208
+
209
+ ```ts
210
+ const speedSubscription = await car.subscribeQuery("VEHICLE_SPEED", {
211
+ frequencyHz: 2,
212
+ });
213
+
214
+ car.unsubscribeQuery(speedSubscription);
215
+ ```
216
+
217
+ ## Queries
218
+
219
+ Use `query()` for names declared under profile `queries`:
220
+
221
+ ```ts
222
+ const speed = await car.query<number>("SPEED");
223
+ ```
224
+
225
+ The YAML profile describes the endpoint, request bytes, accepted response IDs,
226
+ expected response prefix, and either a `dbc_mapping` or built-in `decoder`. The
227
+ transport receives a raw request frame through `sendRequest()` with
228
+ `expectCanResponse: true`. The response is validated against `expect` and
229
+ decoded by the referenced DBC signal or built-in decoder.
230
+
231
+ Calling `query()` for a name not declared in the profile throws an unknown
232
+ signal error.
233
+
234
+ ## Actions
235
+
236
+ Use `action()` for names declared under profile `actions`:
237
+
238
+ ```ts
239
+ await car.action("flash_lights");
240
+ ```
241
+
242
+ Actions can be request-only, verified request/response, or multi-step flows.
243
+ Legacy raw DBC-only vehicles can still use `action()` with action options to send
244
+ encoded frame signals.
245
+
246
+ ## Vehicle State
247
+
248
+ Each vehicle exposes a `VehicleState` instance backed by `valtio/vanilla`:
249
+
250
+ ```ts
251
+ const rpm = car.state.get<number>("ENGINE_RPM");
252
+ const sameRpm = car.state.engine_rpm;
253
+
254
+ const dispose = car.state.subscribe(() => {
255
+ console.log(car.state.snapshot());
256
+ });
257
+
258
+ dispose();
259
+ ```
260
+
261
+ State keys are stored by the subscribed name. In profile-backed vehicles, that
262
+ is the YAML `signals` or `queries` key. Property access also accepts common
263
+ camelCase or snake_case variants by converting them to upper snake case.
264
+
265
+ ## Transport
266
+
267
+ The core transport is intentionally dumb:
268
+
269
+ - it connects and disconnects;
270
+ - it sends raw CAN requests through one request path;
271
+ - it configures the firmware monitor list for subscriptions;
272
+ - it receives monitor snapshots containing the latest raw CAN frames;
273
+ - it does not parse DBC, ISO-TP, UDS, or app-level signal names.
274
+
275
+ `MockTransport` ships with the library for tests and local simulations.
276
+ `SlcanTransport` speaks Lawicel SLCAN over a byte port, including ISO-TP
277
+ reassembly for `sendRequest()`. A browser opens that port with Web Serial:
278
+
279
+ ```ts
280
+ import { SlcanTransport, openWebSerialSlcanPort, requestWebSerialPort } from "can-opener-js/transport";
281
+
282
+ const port = await requestWebSerialPort();
283
+ const transport = new SlcanTransport(await openWebSerialSlcanPort(port), { bitrate: 500_000 });
284
+ ```
285
+
286
+ Pass `canFd: true` when the adapter runs CANable 2 firmware. The transport then
287
+ sends CAN FD requests with that firmware's `d`/`b` commands, accepts
288
+ `dataBitrate` 2 or 5 Mbit/s in `configureBus` (`Y2`/`Y5`, which turns on bit
289
+ rate switching), and parses received CAN FD frames. Without it, CAN FD requests
290
+ are rejected, because CANable 1 firmware ignores those commands silently.
291
+
292
+ `examples/slcan-web` is a small page that connects a CANable and runs the Nissan
293
+ Versa profile through this transport. `npm run dev:slcan` starts it.
294
+
295
+ ### Can Opener SE over BLE
296
+
297
+ `CanOpenerBleTransport` (`can-opener-js/ble`) speaks the
298
+ [BLE Transport Protocol](docs/can-opener-se-ble-protocol.md): requests,
299
+ CAN FD payloads, batches, monitoring, and bus timing. It does not depend on a
300
+ BLE stack. The app connects the adapter, discovers services, and passes the
301
+ transport a `CanOpenerGattLink`. `can-opener-js/react-native-ble` provides one
302
+ for react-native-ble-plx:
303
+
304
+ ```ts
305
+ import { Platform } from "react-native";
306
+ import { BleManager } from "react-native-ble-plx";
307
+ import { CanOpenerBleTransport } from "can-opener-js/ble";
308
+ import { bleplxGattLink, bleplxSecurityWritePolicy } from "can-opener-js/react-native-ble";
309
+ import { credentialAuthorizer } from "can-opener-js/security";
310
+
311
+ const ble = new BleManager();
312
+ const device = await ble.connectToDevice(deviceId, { requestMTU: 247 });
313
+ await device.discoverAllServicesAndCharacteristics();
314
+
315
+ const transport = new CanOpenerBleTransport(bleplxGattLink(ble, device.id), {
316
+ authorize: credentialAuthorizer(credentialStore),
317
+ securityWritePolicy: bleplxSecurityWritePolicy(Platform.OS === "android" ? "android" : "ios"),
318
+ subscribeSettleMs: Platform.OS === "android" ? 80 : 0,
319
+ });
320
+ ```
321
+
322
+ The adapter rejects vehicle notifications until the phone proves a key on the
323
+ security characteristic, so `authorize` runs inside `connect()` before they are
324
+ enabled. `credentialStore` is the app's `CredentialStore`: it lists the keys
325
+ saved for adapters and saves what authentication reports, such as a redeemed
326
+ guest invite. `can-opener-js/security` also covers claiming an adapter
327
+ (`withSecuritySession(link, (session) => session.claim(seed))`), backup codes,
328
+ invite links, and guest management through `transport.accessSession`.
329
+
330
+ The firmware matches replies by sequence byte only. When another client shares
331
+ the link, such as an iOS Siri extension using `0x80`-`0xFF`, give each one a
332
+ disjoint `sequenceRange`; the default is `0x00`-`0x7F`.
333
+
334
+ Other transports implement `VehicleTransport` the same way. `CanOpenerBleTransport`
335
+ maps its methods onto the firmware characteristics:
336
+
337
+ - `sendRequest()` maps to the Request characteristic. Actions use
338
+ `expectCanResponse: false`; PID and diagnostic reads use
339
+ `expectCanResponse: true`.
340
+ - `updateMonitor()` maps to the Monitor Control characteristic with `add`,
341
+ `remove`, and `clear` operations.
342
+ - `onMonitorSnapshot()` maps to Monitor Data notifications. Each snapshot
343
+ contains the current monitored frame set, with CAN ID, DLC, and up to 8 data
344
+ bytes per frame.
345
+
346
+ ```ts
347
+ import type {
348
+ CanPayload,
349
+ MonitorControlRequest,
350
+ MonitorControlResponse,
351
+ MonitorSnapshot,
352
+ VehicleRequest,
353
+ VehicleTransport,
354
+ } from "can-opener-js/transport";
355
+
356
+ class MyTransport implements VehicleTransport {
357
+ async connect(): Promise<void> {}
358
+ async disconnect(): Promise<void> {}
359
+ async sendRequest(req: VehicleRequest): Promise<CanPayload | undefined> {
360
+ if (!req.expectCanResponse) {
361
+ return undefined;
362
+ }
363
+ if (req.diagnostic?.transport === "isotp") {
364
+ // Gather and return the reassembled logical diagnostic payload here.
365
+ }
366
+ return new Uint8Array();
367
+ }
368
+ async updateMonitor(req: MonitorControlRequest): Promise<MonitorControlResponse> {
369
+ return { status: "ok", currentMonitorCount: 0 };
370
+ }
371
+ onMonitorSnapshot(cb: (snapshot: MonitorSnapshot) => void): () => void {
372
+ return () => {};
373
+ }
374
+ }
375
+ ```
376
+
377
+ `onMonitorSnapshot()` should register a callback for monitor data notifications
378
+ and return a dispose function. The vehicle calls that dispose function when
379
+ disconnected.
380
+
381
+ ## Multiple vehicles
382
+
383
+ `VirtualVehicleManager` never uses globals. Each connected vehicle has isolated
384
+ state, DBC registry, controller instances, and transport.
385
+
386
+ ```ts
387
+ const vehicleA = await manager.connect({
388
+ id: "car-a",
389
+ transport: transportA,
390
+ dbcFiles,
391
+ });
392
+
393
+ const vehicleB = await manager.connect({
394
+ id: "car-b",
395
+ transport: transportB,
396
+ dbcFiles,
397
+ });
398
+
399
+ vehicleA.state.engine_rpm;
400
+ vehicleB.state.engine_rpm;
401
+ ```
402
+
403
+ ## Development
404
+
405
+ ```sh
406
+ npm test
407
+ npm run typecheck
408
+ npm run build
409
+ ```
410
+
411
+ The test suite uses `MockTransport` to simulate PID responses, action sends,
412
+ subscription registration, and incoming CAN frames.
413
+
414
+ ## Out of scope for v1
415
+
416
+ - BLE link adapters other than react-native-ble-plx. Web Bluetooth or Node BLE
417
+ only need a `CanOpenerGattLink`; `CanOpenerBleTransport` stays the same.
418
+ - ISO-TP assembly/disassembly, which should remain firmware-side.
419
+ - React bindings. The core uses `valtio/vanilla`, so a React entry point can be
420
+ added without changing the vehicle model.