@csselectronics/can-decode 0.0.0-stage → 0.1.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.
- package/LICENSE +36 -0
- package/README.md +29 -2
- package/index.d.ts +101 -0
- package/index.js +2 -0
- package/models/CanTypes.d.ts +133 -0
- package/models/CanTypes.js +2 -0
- package/models/DecodedSignal.d.ts +11 -0
- package/models/DecodedSignal.js +1 -0
- package/models/dbc/BusDbcAssignment.d.ts +45 -0
- package/models/dbc/BusDbcAssignment.js +2 -0
- package/models/dbc/DbcDefinition.d.ts +117 -0
- package/models/dbc/DbcDefinition.js +2 -0
- package/models/dbc/DbcUnion.d.ts +92 -0
- package/models/dbc/DbcUnion.js +2 -0
- package/models/dbc/IDbcDefinition.d.ts +72 -0
- package/models/dbc/IDbcDefinition.js +1 -0
- package/package.json +33 -4
- package/services/pipeline/DecodingEngine.d.ts +107 -0
- package/services/pipeline/DecodingEngine.js +2 -0
- package/services/pipeline/DecodingService.d.ts +52 -0
- package/services/pipeline/DecodingService.js +2 -0
- package/services/pipeline/dbc/DbcAssignmentService.d.ts +84 -0
- package/services/pipeline/dbc/DbcAssignmentService.js +2 -0
- package/services/pipeline/dbc/DbcManagerService.d.ts +95 -0
- package/services/pipeline/dbc/DbcManagerService.js +2 -0
- package/utils/DbcParser.d.ts +26 -0
- package/utils/DbcParser.js +2 -0
- package/utils/JsonParser.d.ts +25 -0
- package/utils/JsonParser.js +2 -0
- package/utils/SignalDecoder.d.ts +38 -0
- package/utils/SignalDecoder.js +2 -0
- package/utils/SignalEncoder.d.ts +46 -0
- package/utils/SignalEncoder.js +2 -0
- package/utils/SignalIdParser.d.ts +41 -0
- package/utils/SignalIdParser.js +2 -0
- package/utils/dbcKey.d.ts +1 -0
- package/utils/dbcKey.js +2 -0
- package/utils/downsampleMinMax.d.ts +8 -0
- package/utils/downsampleMinMax.js +2 -0
- package/utils/signalQuery.d.ts +45 -0
- package/utils/signalQuery.js +2 -0
- package/utils/signalReductions.d.ts +23 -0
- package/utils/signalReductions.js +2 -0
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import type { CanMessage, CanSignal } from '../CanTypes.js';
|
|
2
|
+
import type { SkippedSignal } from '../../utils/DbcParser.js';
|
|
3
|
+
/** Metadata about a loaded CAN data definition. */
|
|
4
|
+
export interface DbcMetadata {
|
|
5
|
+
fileName: string | null;
|
|
6
|
+
loadTime: Date;
|
|
7
|
+
version?: string;
|
|
8
|
+
hasMultiplexing: boolean;
|
|
9
|
+
messageCount: number;
|
|
10
|
+
signalCount: number;
|
|
11
|
+
protocolType?: string;
|
|
12
|
+
/** Integer signals >32 bits excluded from decoding (empty when none). */
|
|
13
|
+
skippedSignals?: SkippedSignal[];
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* IDbcDefinition - Interface for CAN data definitions.
|
|
17
|
+
*
|
|
18
|
+
* Implemented by DbcDefinition (single file) and DbcUnion (multiple files).
|
|
19
|
+
* Enables polymorphic message/signal lookup regardless of source.
|
|
20
|
+
*/
|
|
21
|
+
export interface IDbcDefinition {
|
|
22
|
+
/**
|
|
23
|
+
* Human-readable name of this definition (e.g. filename)
|
|
24
|
+
*/
|
|
25
|
+
readonly name: string | null;
|
|
26
|
+
/**
|
|
27
|
+
* Check if this definition is for J1939 protocol
|
|
28
|
+
*
|
|
29
|
+
* @returns True if protocol type is J1939
|
|
30
|
+
*/
|
|
31
|
+
isJ1939(): boolean;
|
|
32
|
+
/**
|
|
33
|
+
* Get message information.
|
|
34
|
+
*
|
|
35
|
+
* Both `messageId` and `isExtended` are consulted — a frame's IDE must
|
|
36
|
+
* match the DBC message's IDE for the lookup to succeed. A DBC defining
|
|
37
|
+
* `0x111` as 11-bit and another (or the same) DBC defining `0x111` as
|
|
38
|
+
* 29-bit are distinct messages.
|
|
39
|
+
*
|
|
40
|
+
* @param messageId - CAN message ID (clean 29-bit-masked, no IDE flag bit)
|
|
41
|
+
* @param isExtended - True for 29-bit, false for 11-bit
|
|
42
|
+
* @returns Message definition or null
|
|
43
|
+
*/
|
|
44
|
+
getMessageInfo(messageId: number, isExtended: boolean): CanMessage | null;
|
|
45
|
+
/**
|
|
46
|
+
* Get signal information
|
|
47
|
+
*
|
|
48
|
+
* @param message - CAN message definition
|
|
49
|
+
* @param signalName - Signal name
|
|
50
|
+
* @returns Signal definition or null
|
|
51
|
+
*/
|
|
52
|
+
getSignalInfo(message: CanMessage, signalName: string): CanSignal | null;
|
|
53
|
+
/**
|
|
54
|
+
* List all defined message IDs
|
|
55
|
+
*
|
|
56
|
+
* @returns Array of message IDs
|
|
57
|
+
*/
|
|
58
|
+
listMessages(): CanMessage[];
|
|
59
|
+
/**
|
|
60
|
+
* List all signal names for a message
|
|
61
|
+
*
|
|
62
|
+
* @param messageId - CAN message ID
|
|
63
|
+
* @returns Array of signal names
|
|
64
|
+
*/
|
|
65
|
+
listSignals(message: CanMessage): CanSignal[];
|
|
66
|
+
/**
|
|
67
|
+
* Get metadata about this definition
|
|
68
|
+
*
|
|
69
|
+
* @returns Definition metadata (may be aggregated for unions)
|
|
70
|
+
*/
|
|
71
|
+
getMetadata(): DbcMetadata;
|
|
72
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
/*! @csselectronics/can-decode v0.1.0 (c) CSS Electronics ApS, see LICENSE */
|
package/package.json
CHANGED
|
@@ -1,6 +1,35 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@csselectronics/can-decode",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "DBC parsing and CAN signal decoding for CANsub frame streams.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"cansub",
|
|
7
|
+
"can-bus",
|
|
8
|
+
"can-fd",
|
|
9
|
+
"css-electronics",
|
|
10
|
+
"dbc",
|
|
11
|
+
"decoding"
|
|
12
|
+
],
|
|
13
|
+
"license": "SEE LICENSE IN LICENSE",
|
|
14
|
+
"author": "CSS Electronics ApS",
|
|
15
|
+
"homepage": "https://github.com/CSS-Electronics/js-sdk-cansub#readme",
|
|
16
|
+
"type": "module",
|
|
17
|
+
"main": "./index.js",
|
|
18
|
+
"types": "./index.d.ts",
|
|
19
|
+
"exports": {
|
|
20
|
+
".": {
|
|
21
|
+
"types": "./index.d.ts",
|
|
22
|
+
"default": "./index.js"
|
|
23
|
+
},
|
|
24
|
+
"./*": {
|
|
25
|
+
"types": "./*.d.ts",
|
|
26
|
+
"default": "./*.js"
|
|
27
|
+
}
|
|
28
|
+
},
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"@csselectronics/can-pipeline": "^0.1.0",
|
|
31
|
+
"@csselectronics/can-types": "^0.1.0",
|
|
32
|
+
"@csselectronics/websocket-client": "^0.1.0",
|
|
33
|
+
"@preact/signals-core": "^1.12.1"
|
|
34
|
+
}
|
|
35
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DecodingEngine - Pure CAN signal decoding core.
|
|
3
|
+
*
|
|
4
|
+
* Decodes signals into memory-efficient parallel arrays (keys[] + Float64Array).
|
|
5
|
+
* Framework-agnostic: no Preact signals or service dependencies.
|
|
6
|
+
* Optional onSignalDecoded callback for integration hooks.
|
|
7
|
+
*/
|
|
8
|
+
import type { CanFrame } from '@csselectronics/websocket-client/models/CanFrame';
|
|
9
|
+
import { CanMessage, CanSignal } from '../../models/CanTypes.js';
|
|
10
|
+
import type { IDbcDefinition } from '../../models/dbc/IDbcDefinition.js';
|
|
11
|
+
import type { CanBusName } from '@csselectronics/websocket-client/types/CanBusTypes';
|
|
12
|
+
/** Sentinel name used for CAN IDs that have no DBC match */
|
|
13
|
+
export declare const UNMATCHED = "UNMATCHED";
|
|
14
|
+
/**
|
|
15
|
+
* Callback invoked for each newly-seen signal (skipped once per cache
|
|
16
|
+
* entry after first notification).
|
|
17
|
+
*
|
|
18
|
+
* `frameKey` is the interned `CanFrame.key` of the frame that produced
|
|
19
|
+
* the signal — the canonical identity used for bucket grouping. Receivers
|
|
20
|
+
* should derive signal keys as `${frameKey}_${signal.name}` so the
|
|
21
|
+
* encoding stays uniform across normal and error frames (the latter use
|
|
22
|
+
* a different `_ERR_${type}` prefix). The other args are convenience
|
|
23
|
+
* destructurings already implicit in `frameKey`; provided as separate
|
|
24
|
+
* params to avoid the parse on hot paths.
|
|
25
|
+
*/
|
|
26
|
+
export type SignalDecodedCallback = (bus: CanBusName, arbId: number, ide: boolean, message: CanMessage, signal: CanSignal, synthetic: boolean, frameKey: string) => void;
|
|
27
|
+
export declare class DecodingEngine {
|
|
28
|
+
/** When true, decoded values outside the DBC-defined min/max range are replaced with NaN. */
|
|
29
|
+
nullifyOutOfRange: boolean;
|
|
30
|
+
/** Per-bus DBC definitions, set via setDefinition() */
|
|
31
|
+
private definitions;
|
|
32
|
+
/**
|
|
33
|
+
* Cache of synthetic UNMATCHED entries per frame.key.
|
|
34
|
+
* Shared across all UNMATCHED frames with the same key (zero per-frame allocation).
|
|
35
|
+
*/
|
|
36
|
+
private syntheticCache;
|
|
37
|
+
/**
|
|
38
|
+
* Shared signal keys cache for non-multiplexed messages (keyed by frame.key).
|
|
39
|
+
* Self-invalidates on DBC change via CanMessage identity check.
|
|
40
|
+
* The `notified` flag skips onSignalDecoded after first frame (steady-state).
|
|
41
|
+
*/
|
|
42
|
+
private signalKeysCache;
|
|
43
|
+
/** Optional callback for integration hooks (e.g. signal registration). */
|
|
44
|
+
private onSignalDecoded?;
|
|
45
|
+
constructor(onSignalDecoded?: SignalDecodedCallback);
|
|
46
|
+
/** Set the DBC definition for a bus. Pass null to clear. */
|
|
47
|
+
setDefinition(bus: CanBusName, definition: IDbcDefinition | null): void;
|
|
48
|
+
/**
|
|
49
|
+
* Clear caches so signals are re-processed on next frame.
|
|
50
|
+
* Called when clearing all frame data or when DBC definitions change.
|
|
51
|
+
*/
|
|
52
|
+
clearRegistrationCache(): void;
|
|
53
|
+
setNullifyOutOfRange(enabled: boolean): void;
|
|
54
|
+
/**
|
|
55
|
+
* Decode all signals in a CAN frame and populate frame.decodedSignals
|
|
56
|
+
*
|
|
57
|
+
* Process:
|
|
58
|
+
* 1. Look up DBC definition for the frame's bus
|
|
59
|
+
* 2. Get message definition by arbitration ID
|
|
60
|
+
* 3. Decode all signals (handles multiplexing automatically)
|
|
61
|
+
* 4. Build memory-efficient parallel arrays (keys[] + Float64Array)
|
|
62
|
+
* 5. Attach decoded signals via frame.setDecodedSignals()
|
|
63
|
+
*
|
|
64
|
+
* @param frame - CAN frame to decode (will be mutated: frame.decodedSignals populated)
|
|
65
|
+
* @param definitionOverride - Optional definition to use instead of the stored one (avoids per-frame setDefinition calls)
|
|
66
|
+
*/
|
|
67
|
+
decodeFrame(frame: CanFrame, definitionOverride?: IDbcDefinition | null): void;
|
|
68
|
+
/**
|
|
69
|
+
* Single-pass decode for non-multiplexed messages.
|
|
70
|
+
* Iterates signalsArray directly, calling decodeSignal inline.
|
|
71
|
+
* Avoids allocating an intermediate DecodedSignal[] array.
|
|
72
|
+
*/
|
|
73
|
+
private decodeNonMux;
|
|
74
|
+
/**
|
|
75
|
+
* Single-pass decode for non-multiplexed messages with variable-length payload
|
|
76
|
+
* (e.g. J1939 DM1, where the same CAN ID may carry 8..N bytes depending on how
|
|
77
|
+
* many DTCs are active). Mirrors `decodeNonMux` but with two deltas:
|
|
78
|
+
*
|
|
79
|
+
* 1. No `signalKeysCache`: different frames of the same CAN ID may produce
|
|
80
|
+
* different signal sets, so the per-key cache invariant doesn't hold.
|
|
81
|
+
* 2. Out-of-range signals (`requiredBytes > frame.data.length`) are **omitted
|
|
82
|
+
* entirely** — no key push, no value push, no `onSignalDecoded`. The signal
|
|
83
|
+
* is simply absent from this frame, exactly like a non-active mux signal.
|
|
84
|
+
*/
|
|
85
|
+
private decodeNonMuxVariable;
|
|
86
|
+
/**
|
|
87
|
+
* Decode multiplexed messages using CanMessage.decodeSignals() which handles
|
|
88
|
+
* recursive multiplexer traversal. Returns a DecodedSignal[] intermediate.
|
|
89
|
+
*
|
|
90
|
+
* When the message is also flagged `isVariableLength` (e.g. ISO-TP-assembled
|
|
91
|
+
* OBD-DTC responses), active mux signals whose `requiredBytes` exceed the
|
|
92
|
+
* actual frame data length are **omitted entirely** instead of NaN-filled —
|
|
93
|
+
* matching `decodeNonMuxVariable`'s semantics for the slots that "didn't fit".
|
|
94
|
+
*/
|
|
95
|
+
private decodeMux;
|
|
96
|
+
/**
|
|
97
|
+
* Mark a frame as UNMATCHED — attaches a synthetic UNMATCHED signal,
|
|
98
|
+
* fires `onSignalDecoded` once for the synthetic, and caches the synthetic
|
|
99
|
+
* `CanMessage`/`CanSignal` per `frame.key` to avoid allocation.
|
|
100
|
+
*
|
|
101
|
+
* Called from internal `decodeFrame` when there's no DBC match (or a
|
|
102
|
+
* matched message yields no decoded signals), and from external callers
|
|
103
|
+
* (e.g. `DecodingService` when the optional skip predicate suppresses
|
|
104
|
+
* decoding for TP-matched carrier frames).
|
|
105
|
+
*/
|
|
106
|
+
markUnmatched(frame: CanFrame): void;
|
|
107
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! @csselectronics/can-decode v0.1.0 (c) CSS Electronics ApS, see LICENSE */
|
|
2
|
+
var p=Object.defineProperty;var C=(y,e)=>p(y,"name",{value:e,configurable:!0});import{CanMessage as D,CanSignal as N}from"../../models/CanTypes.js";import{decodeSignalValue as k}from"../../utils/SignalDecoder.js";const f="UNMATCHED";class x{static{C(this,"DecodingEngine")}nullifyOutOfRange=!1;definitions=new Map;syntheticCache=new Map;signalKeysCache=new Map;onSignalDecoded;constructor(e){this.onSignalDecoded=e}setDefinition(e,i){this.definitions.get(e)!==i&&(i?this.definitions.set(e,i):this.definitions.delete(e),this.clearRegistrationCache())}clearRegistrationCache(){this.signalKeysCache.clear(),this.syntheticCache.clear()}setNullifyOutOfRange(e){this.nullifyOutOfRange=e}decodeFrame(e,i){if(e.is_error||e.is_rtr){this.markUnmatched(e);return}let s=(i!==void 0?i:this.definitions.get(e.bus))?.getMessageInfo(e.arbitration_id,e.ide);if(!s){this.markUnmatched(e);return}try{s.isMultiplexed?this.decodeMux(e,s):s.isVariableLength?this.decodeNonMuxVariable(e,s):this.decodeNonMux(e,s)}catch(g){console.error(`Failed to decode frame ${e.key}:`,g)}}decodeNonMux(e,i){const l=this.nullifyOutOfRange,s=e.data.length,g=i.signalsArray,n=this.signalKeysCache.get(e.key),o=n!==void 0&&n.message===i,t=o?n.keys:void 0,r=!this.onSignalDecoded||o&&n.notified,a=t??[],d=g.length,b=new Float64Array(d);for(let u=0;u<d;u++){const c=g[u];t||a.push(`${e.key}_${c.name}`);let h=k(e.data,c);s<c.requiredBytes?h=NaN:l&&Number.isFinite(c.min)&&Number.isFinite(c.max)&&c.min<c.max&&(h<c.min||h>c.max)&&(h=NaN),b[u]=h,r||this.onSignalDecoded(e.bus,e.arbitration_id,e.ide,i,c,e.synthetic,e.key)}!o&&d>0&&this.signalKeysCache.set(e.key,{message:i,keys:a,notified:!1}),n&&n.message===i&&!n.notified&&(n.notified=!0),d>0?e.setDecodedSignals(a,b):this.markUnmatched(e)}decodeNonMuxVariable(e,i){const l=this.nullifyOutOfRange,s=e.data.length,g=i.signalsArray,n=[],o=[];for(const t of g){if(s<t.requiredBytes)continue;let r=k(e.data,t);l&&Number.isFinite(t.min)&&Number.isFinite(t.max)&&t.min<t.max&&(r<t.min||r>t.max)&&(r=NaN),n.push(`${e.key}_${t.name}`),o.push(r),this.onSignalDecoded&&this.onSignalDecoded(e.bus,e.arbitration_id,e.ide,i,t,e.synthetic,e.key)}n.length>0?e.setDecodedSignals(n,new Float64Array(o)):this.markUnmatched(e)}decodeMux(e,i){const l=i.decodeSignals(e.data),s=this.nullifyOutOfRange,g=e.data.length,n=i.isVariableLength,o=[],t=[];for(const r of l){const a=r.signal;let d=r.value;if(g<a.requiredBytes){if(n)continue;d=NaN}else s&&Number.isFinite(a.min)&&Number.isFinite(a.max)&&a.min<a.max&&(d<a.min||d>a.max)&&(d=NaN);o.push(`${e.key}_${a.name}`),t.push(d),this.onSignalDecoded&&this.onSignalDecoded(e.bus,e.arbitration_id,e.ide,i,a,e.synthetic,e.key)}o.length>0?e.setDecodedSignals(o,new Float64Array(t)):this.markUnmatched(e)}markUnmatched(e){let i=this.syntheticCache.get(e.key);if(!i){const l=new N({name:"",bitpos:0,bitlen:0,bigendian:!1,signed:!1,factor:1,offset:0,min:0,max:0,unit:"",ignored:!1,lineNo:0}),s=new D({key:e.arbitration_id,name:e.is_error?"":f,length:0,isExtended:e.ide,isMultiplexed:!1,signals:[l]}),n=[`${e.key}_`],o=new Float64Array([NaN]);i={message:s,signal:l,keys:n,values:o},this.syntheticCache.set(e.key,i)}this.onSignalDecoded&&this.onSignalDecoded(e.bus,e.arbitration_id,e.ide,i.message,i.signal,e.synthetic,e.key),e.setDecodedSignalsDirect(i.keys,i.values)}}export{x as DecodingEngine,f as UNMATCHED};
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import type { CanFrame } from '@csselectronics/websocket-client/models/CanFrame';
|
|
2
|
+
import type { IDbcDefinition } from '../../models/dbc/IDbcDefinition.js';
|
|
3
|
+
import type { DbcAssignmentService } from './dbc/DbcAssignmentService.js';
|
|
4
|
+
import type { FilterSelectionService } from '@csselectronics/can-pipeline/services/pipeline/FilterSelectionService';
|
|
5
|
+
import { UNMATCHED } from './DecodingEngine.js';
|
|
6
|
+
export { UNMATCHED };
|
|
7
|
+
/**
|
|
8
|
+
* DecodingService - Centralized signal decoding and registration.
|
|
9
|
+
*
|
|
10
|
+
* Delegates to DecodingEngine for per-frame decoding. Wires the
|
|
11
|
+
* onSignalDecoded callback to FilterSelectionService for registration.
|
|
12
|
+
*/
|
|
13
|
+
export declare class DecodingService {
|
|
14
|
+
private readonly dbcService;
|
|
15
|
+
private readonly engine;
|
|
16
|
+
/**
|
|
17
|
+
* Optional predicate consulted before each `decodeFrame` / `reprocessFrame`.
|
|
18
|
+
* When it returns true, the frame is registered as UNMATCHED instead of
|
|
19
|
+
* being decoded against the assigned DBC. Used by the host to suppress
|
|
20
|
+
* DBC decoding on TP-matched carrier frames; the assembled synthetic
|
|
21
|
+
* (which has `kind: 'synthetic'` rather than `'raw'` in TpMeta) decodes
|
|
22
|
+
* normally.
|
|
23
|
+
*/
|
|
24
|
+
private readonly shouldSkipDbcDecode?;
|
|
25
|
+
/**
|
|
26
|
+
* When true, decoded values outside the DBC-defined min/max range are
|
|
27
|
+
* replaced with NaN. The host persists it (webCAN's `decoding` settings section).
|
|
28
|
+
*/
|
|
29
|
+
readonly nullifyOutOfRange: import("@preact/signals-core").Signal<boolean>;
|
|
30
|
+
constructor(dbcService: DbcAssignmentService, filterSelectionService: FilterSelectionService, shouldSkipDbcDecode?: (frame: CanFrame) => boolean);
|
|
31
|
+
/**
|
|
32
|
+
* Clear registration caches so signals are re-registered on next frame.
|
|
33
|
+
* Called by FrameResetService when clearing all frame data.
|
|
34
|
+
*/
|
|
35
|
+
clearRegistrationCache(): void;
|
|
36
|
+
setNullifyOutOfRange(enabled: boolean): void;
|
|
37
|
+
/**
|
|
38
|
+
* Decode all signals in a CAN frame and populate frame.decodedSignals.
|
|
39
|
+
* If the optional skip predicate returns true (typically: TP-matched
|
|
40
|
+
* carrier), the frame is registered as UNMATCHED instead.
|
|
41
|
+
*
|
|
42
|
+
* @param frame - CAN frame to decode (will be mutated: frame.decodedSignals populated)
|
|
43
|
+
*/
|
|
44
|
+
decodeFrame(frame: CanFrame): void;
|
|
45
|
+
/**
|
|
46
|
+
* Re-decode a frame with an explicit definition override.
|
|
47
|
+
* Used by DbcReprocessService for re-processing stored frames
|
|
48
|
+
* (buses are disconnected so getResolvedDefinition returns null).
|
|
49
|
+
* Same skip predicate gate as `decodeFrame`.
|
|
50
|
+
*/
|
|
51
|
+
reprocessFrame(frame: CanFrame, definition: IDbcDefinition | null): void;
|
|
52
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! @csselectronics/can-decode v0.1.0 (c) CSS Electronics ApS, see LICENSE */
|
|
2
|
+
var m=Object.defineProperty;var t=(n,e)=>m(n,"name",{value:e,configurable:!0});import{signal as f}from"@preact/signals-core";import{DecodingEngine as p,UNMATCHED as u}from"./DecodingEngine.js";class b{static{t(this,"DecodingService")}dbcService;engine;shouldSkipDbcDecode;nullifyOutOfRange=f(!1);constructor(e,i,c){this.dbcService=e,this.shouldSkipDbcDecode=c,this.engine=new p((o,r,s,l,a,d,g)=>{i.registerSignal(o,r,s,l,a,d,g)})}clearRegistrationCache(){this.engine.clearRegistrationCache()}setNullifyOutOfRange(e){this.nullifyOutOfRange.value=e,this.engine.setNullifyOutOfRange(e)}decodeFrame(e){if(this.shouldSkipDbcDecode?.(e)){this.engine.markUnmatched(e);return}const i=this.dbcService.getResolvedDefinition(e.bus);this.engine.nullifyOutOfRange=this.nullifyOutOfRange.peek(),this.engine.decodeFrame(e,i)}reprocessFrame(e,i){if(this.shouldSkipDbcDecode?.(e)){this.engine.markUnmatched(e);return}this.engine.nullifyOutOfRange=this.nullifyOutOfRange.peek(),this.engine.decodeFrame(e,i)}}export{b as DecodingService,u as UNMATCHED};
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import type { CanBusName } from '@csselectronics/websocket-client/types/CanBusTypes';
|
|
2
|
+
import type { DbcManagerService } from './DbcManagerService.js';
|
|
3
|
+
import type { IDbcDefinition } from '../../../models/dbc/IDbcDefinition.js';
|
|
4
|
+
import { BusDbcAssignment } from '../../../models/dbc/BusDbcAssignment.js';
|
|
5
|
+
import type { ConnectionService } from '@csselectronics/websocket-client/services/pipeline/ConnectionService';
|
|
6
|
+
/**
|
|
7
|
+
* DbcAssignmentService - Single owner of DBC-to-bus mapping.
|
|
8
|
+
*
|
|
9
|
+
* Manages per-bus DBC filename assignments and resolves them to runtime
|
|
10
|
+
* definitions via DbcManagerService. Reactively resolves on connect and clears
|
|
11
|
+
* on disconnect. Holds state only; the host persists the assignments (webCAN's
|
|
12
|
+
* `decoding` settings section).
|
|
13
|
+
*/
|
|
14
|
+
export declare class DbcAssignmentService {
|
|
15
|
+
/** Per-bus DBC assignments */
|
|
16
|
+
private assignments;
|
|
17
|
+
/**
|
|
18
|
+
* Per-bus memoized `buildDefinition` result. `buildDefinition` reads exactly
|
|
19
|
+
* two signals (the assignment's `dbcFilenames` and the manager's
|
|
20
|
+
* `localDefinitions`), so the computed invalidates automatically on any DBC
|
|
21
|
+
* or assignment change. This keeps the disconnected decode path (CSV import,
|
|
22
|
+
* TP reprocess) from rebuilding the definition per frame.
|
|
23
|
+
*/
|
|
24
|
+
private builtDefinitions;
|
|
25
|
+
/** DBC definition manager for resolution (null when DBC feature disabled) */
|
|
26
|
+
private readonly definitionManager;
|
|
27
|
+
constructor(definitionManager: DbcManagerService | null);
|
|
28
|
+
/** Tracks previously connected buses for reactive disconnect detection */
|
|
29
|
+
private previouslyConnected;
|
|
30
|
+
/** Create an empty assignment per available channel and watch bus connections. */
|
|
31
|
+
initBuses(channels: number[], connectionService: ConnectionService): void;
|
|
32
|
+
/**
|
|
33
|
+
* Get the BusDbcAssignment for a bus (used by UI components).
|
|
34
|
+
*/
|
|
35
|
+
getAssignment(busName: CanBusName): BusDbcAssignment | null;
|
|
36
|
+
/**
|
|
37
|
+
* Convenience: get the resolved definition for a bus.
|
|
38
|
+
* Used by DecodingService / ChartService per-frame.
|
|
39
|
+
*
|
|
40
|
+
* Live streaming hits the cached fast path: `resolvedDefinition` is set
|
|
41
|
+
* once by `resolveForBus()` on bus connect and queried per frame at near-
|
|
42
|
+
* zero cost.
|
|
43
|
+
*
|
|
44
|
+
* Offline pipelines (CSV import, TP reprocess) run while buses are
|
|
45
|
+
* disconnected, so the cached value is null. Falls through to the
|
|
46
|
+
* per-bus memoized `buildDefinition` computed so inline `decodeFrame`
|
|
47
|
+
* produces correct decoded signals regardless of connection state. This
|
|
48
|
+
* eliminates the need for a separate post-pass `dbcReprocess` after
|
|
49
|
+
* offline ingest, without rebuilding the definition per frame. The
|
|
50
|
+
* fallback only fires when disconnected, so the live hot path is
|
|
51
|
+
* unaffected.
|
|
52
|
+
*/
|
|
53
|
+
getResolvedDefinition(busName: CanBusName): IDbcDefinition | null;
|
|
54
|
+
/**
|
|
55
|
+
* Resolve DBC filenames to a unified definition for a bus.
|
|
56
|
+
* Returns the definition without setting it on the assignment.
|
|
57
|
+
* Used by DbcReprocessService for re-processing stored frames.
|
|
58
|
+
*/
|
|
59
|
+
buildDefinition(busName: CanBusName): IDbcDefinition | null;
|
|
60
|
+
/**
|
|
61
|
+
* Resolve DBC filenames to a unified definition for a bus and set it on the assignment.
|
|
62
|
+
* Called reactively when a bus connects.
|
|
63
|
+
*/
|
|
64
|
+
resolveForBus(busName: CanBusName): void;
|
|
65
|
+
/**
|
|
66
|
+
* Clear resolved definition for a bus (keeps filenames).
|
|
67
|
+
* Called reactively when a bus disconnects.
|
|
68
|
+
*/
|
|
69
|
+
clearForBus(busName: CanBusName): void;
|
|
70
|
+
/**
|
|
71
|
+
* Remove a DBC filename from all bus assignments.
|
|
72
|
+
* Called when a DBC file is deleted from the loaded pool.
|
|
73
|
+
*/
|
|
74
|
+
removeFromAllBuses(filename: string): void;
|
|
75
|
+
/** Drop every assigned filename that is not in `loaded` (the pool's file names). */
|
|
76
|
+
removeMissing(loaded: ReadonlySet<string>): void;
|
|
77
|
+
/**
|
|
78
|
+
* Reactively watch ConnectionService for bus connect/disconnect.
|
|
79
|
+
* On connect: resolve DBC filenames (synchronous - runs in same microtask,
|
|
80
|
+
* before any WebSocket frames arrive via the event loop).
|
|
81
|
+
* On disconnect: clear resolved definitions (keeps filenames for reconnect).
|
|
82
|
+
*/
|
|
83
|
+
private watchBusConnections;
|
|
84
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! @csselectronics/can-decode v0.1.0 (c) CSS Electronics ApS, see LICENSE */
|
|
2
|
+
var u=Object.defineProperty;var c=(o,e)=>u(o,"name",{value:e,configurable:!0});import{computed as f,effect as m}from"@preact/signals-core";import{BusDbcAssignment as g}from"../../../models/dbc/BusDbcAssignment.js";import{DbcUnion as d}from"../../../models/dbc/DbcUnion.js";class b{static{c(this,"DbcAssignmentService")}assignments=new Map;builtDefinitions=new Map;definitionManager;constructor(e){this.definitionManager=e}previouslyConnected=new Set;initBuses(e,n){this.assignments=new Map;for(const i of e){const s=`CAN${i}`;this.assignments.set(s,new g(s,[])),this.builtDefinitions.set(s,f(()=>this.buildDefinition(s)))}this.watchBusConnections(n)}getAssignment(e){return this.assignments.get(e)??null}getResolvedDefinition(e){const n=this.assignments.get(e)?.getResolvedDefinition()??null;if(n)return n;const i=this.builtDefinitions.get(e);return i?i.value:this.buildDefinition(e)}buildDefinition(e){const n=this.assignments.get(e);if(!n||!this.definitionManager)return null;const i=n.dbcFilenames.value;if(i.length===0)return null;const s=this.definitionManager.getAllValidDefinitions(),t=[];for(const a of i){const r=s.find(l=>l.name===a);r?.definition?t.push(r.definition):console.warn(`[DbcAssignmentService] DBC file '${a}' not loaded - skipping`)}return t.length===0?null:t.length===1?t[0]:new d(t)}resolveForBus(e){const n=this.assignments.get(e);if(!n){console.warn(`[DbcAssignmentService] Bus assignment not found: ${e}`);return}n.setResolvedDefinition(this.buildDefinition(e))}clearForBus(e){this.assignments.get(e)?.setResolvedDefinition(null)}removeFromAllBuses(e){for(const n of this.assignments.values())n.dbcFilenames.value.includes(e)&&n.removeFilename(e)}removeMissing(e){for(const n of this.assignments.values()){const i=n.dbcFilenames.value;i.some(s=>!e.has(s))&&(n.dbcFilenames.value=i.filter(s=>e.has(s)))}}watchBusConnections(e){m(()=>{const n=e.connectedBuses.value;for(const i of n)this.previouslyConnected.has(i)||this.resolveForBus(i);for(const i of this.previouslyConnected)n.has(i)||this.clearForBus(i);this.previouslyConnected=new Set(n)})}}export{b as DbcAssignmentService};
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import type { IDbcDefinition } from '../../../models/dbc/IDbcDefinition.js';
|
|
2
|
+
/**
|
|
3
|
+
* A DBC file in the pool. Only files that parse enter the pool, so every
|
|
4
|
+
* entry carries a valid definition.
|
|
5
|
+
*/
|
|
6
|
+
export interface LoadedDefinition {
|
|
7
|
+
/** Unique identifier for this entry (generated; kept when the file is replaced). */
|
|
8
|
+
id: string;
|
|
9
|
+
/** Display name (the file name). */
|
|
10
|
+
name: string;
|
|
11
|
+
/** Parsed definition. */
|
|
12
|
+
definition: IDbcDefinition;
|
|
13
|
+
/** Original file content (what the settings file and cache store). */
|
|
14
|
+
content: string;
|
|
15
|
+
/** Content length in characters. */
|
|
16
|
+
size: number;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* DbcManagerService - the DBC pool: loads and validates definition files and
|
|
20
|
+
* provides them for per-bus assignment. Holds state only; the host persists
|
|
21
|
+
* the pool (webCAN's `dbc_files` settings section).
|
|
22
|
+
*/
|
|
23
|
+
export declare class DbcManagerService {
|
|
24
|
+
/**
|
|
25
|
+
* Local definitions (loaded in current session)
|
|
26
|
+
*/
|
|
27
|
+
readonly localDefinitions: import("@preact/signals-core").Signal<LoadedDefinition[]>;
|
|
28
|
+
/**
|
|
29
|
+
* Counter for generating unique IDs
|
|
30
|
+
*/
|
|
31
|
+
private idCounter;
|
|
32
|
+
/**
|
|
33
|
+
* Parse a file into a valid definition entry. Format is detected from the
|
|
34
|
+
* filename extension.
|
|
35
|
+
*
|
|
36
|
+
* @throws {Error} If parsing fails or the format is unsupported; the message
|
|
37
|
+
* names the file.
|
|
38
|
+
*/
|
|
39
|
+
private parseDefinition;
|
|
40
|
+
/**
|
|
41
|
+
* Load a CAN definition file locally (into browser memory)
|
|
42
|
+
*
|
|
43
|
+
* @param filename - Name of file (for display and format detection)
|
|
44
|
+
* @param content - File content
|
|
45
|
+
* @returns Loaded definition
|
|
46
|
+
* @throws {Error} If parsing fails or format is unsupported
|
|
47
|
+
*/
|
|
48
|
+
loadLocal(filename: string, content: string): LoadedDefinition;
|
|
49
|
+
/**
|
|
50
|
+
* Replace the whole pool from a list of files, as one signal write.
|
|
51
|
+
* Same-named entries keep the first occurrence. Files that fail to parse are
|
|
52
|
+
* reported rather than thrown, so one bad file does not block the rest.
|
|
53
|
+
*
|
|
54
|
+
* @returns The files that were skipped.
|
|
55
|
+
*/
|
|
56
|
+
replaceAll(files: ReadonlyArray<{
|
|
57
|
+
name: string;
|
|
58
|
+
content: string;
|
|
59
|
+
}>): {
|
|
60
|
+
failed: {
|
|
61
|
+
name: string;
|
|
62
|
+
error: string;
|
|
63
|
+
}[];
|
|
64
|
+
};
|
|
65
|
+
/**
|
|
66
|
+
* Replace an already-loaded definition that shares this filename, in place.
|
|
67
|
+
*
|
|
68
|
+
* Parses the new content BEFORE mutating any state: if the new content is
|
|
69
|
+
* invalid the existing definition is left fully intact and an error is
|
|
70
|
+
* thrown (so a malformed re-upload never destroys the user's working DBC).
|
|
71
|
+
* The same `id` is retained so the list row stays stable. Channel
|
|
72
|
+
* assignments key on `name`, not `id`, so they automatically reflect the
|
|
73
|
+
* new content with no re-assignment. Falls back to {@link loadLocal} when no
|
|
74
|
+
* definition with this filename exists.
|
|
75
|
+
*
|
|
76
|
+
* @param filename - Name of the file to replace (matched against existing names)
|
|
77
|
+
* @param content - New file content
|
|
78
|
+
* @returns The replaced (or newly loaded) definition
|
|
79
|
+
* @throws {Error} If parsing the new content fails (existing definition kept)
|
|
80
|
+
*/
|
|
81
|
+
replaceLocal(filename: string, content: string): LoadedDefinition;
|
|
82
|
+
/**
|
|
83
|
+
* Remove a local definition
|
|
84
|
+
*
|
|
85
|
+
* @param id - Definition ID
|
|
86
|
+
*/
|
|
87
|
+
removeLocal(id: string): void;
|
|
88
|
+
/** Every definition in the pool (all valid: a file that fails to parse never enters it). */
|
|
89
|
+
getAllValidDefinitions(): LoadedDefinition[];
|
|
90
|
+
/**
|
|
91
|
+
* File names of every definition in the pool.
|
|
92
|
+
* Used to drop assignments to files that are not in the pool.
|
|
93
|
+
*/
|
|
94
|
+
getLoadedFilenames(): Set<string>;
|
|
95
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! @csselectronics/can-decode v0.1.0 (c) CSS Electronics ApS, see LICENSE */
|
|
2
|
+
var l=Object.defineProperty;var s=(a,i)=>l(a,"name",{value:i,configurable:!0});import{signal as c}from"@preact/signals-core";import{DbcDefinition as f}from"../../../models/dbc/DbcDefinition.js";class m{static{s(this,"DbcManagerService")}localDefinitions=c([]);idCounter=0;parseDefinition(i,n,t=`local_${this.idCounter++}_${Date.now()}`){try{const o=f.fromFile(n,i);return{id:t,name:i,definition:o,size:n.length,content:n}}catch(o){const e=o instanceof Error?o.message:"Unknown error";throw new Error(`Failed to load ${i}: ${e}`)}}loadLocal(i,n){const t=this.parseDefinition(i,n);return this.localDefinitions.value=[...this.localDefinitions.value,t],t}replaceAll(i){const n=[],t=[],o=new Set;for(const e of i){if(o.has(e.name)){t.push({name:e.name,error:`Duplicate filename ${e.name}; first occurrence kept`});continue}o.add(e.name);try{n.push(this.parseDefinition(e.name,e.content))}catch(r){t.push({name:e.name,error:r instanceof Error?r.message:String(r)})}}return this.localDefinitions.value=n,{failed:t}}replaceLocal(i,n){const t=this.localDefinitions.value.find(e=>e.name===i);if(!t)return this.loadLocal(i,n);const o=this.parseDefinition(i,n,t.id);return this.localDefinitions.value=this.localDefinitions.value.map(e=>e.id===t.id?o:e),o}removeLocal(i){this.localDefinitions.value=this.localDefinitions.value.filter(n=>n.id!==i)}getAllValidDefinitions(){return this.localDefinitions.value}getLoadedFilenames(){return new Set(this.localDefinitions.value.map(i=>i.name))}}export{m as DbcManagerService};
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { CanMessage } from '../models/CanTypes.js';
|
|
2
|
+
/** Signal excluded from decoding (integer >32 bits; JS bitwise ops are 32-bit). */
|
|
3
|
+
export interface SkippedSignal {
|
|
4
|
+
messageName: string;
|
|
5
|
+
signalName: string;
|
|
6
|
+
bitlen: number;
|
|
7
|
+
}
|
|
8
|
+
interface DbcParseResult {
|
|
9
|
+
messages: Map<number, CanMessage>;
|
|
10
|
+
metadata: {
|
|
11
|
+
fileName: string | null;
|
|
12
|
+
attributes: Map<string, string | number>;
|
|
13
|
+
/** Integer signals >32 bits that were excluded from decoding. */
|
|
14
|
+
skippedSignals: SkippedSignal[];
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Parse DBC file text into structured data
|
|
19
|
+
*
|
|
20
|
+
* @param dbcText - Raw DBC file content
|
|
21
|
+
* @param fileName - Optional file name for reference
|
|
22
|
+
* @returns Parsed messages, value tables, and metadata
|
|
23
|
+
* @throws {Error} If parsing fails with descriptive error message
|
|
24
|
+
*/
|
|
25
|
+
export declare function parseDBC(dbcText: string, fileName?: string | null): DbcParseResult;
|
|
26
|
+
export {};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! @csselectronics/can-decode v0.1.0 (c) CSS Electronics ApS, see LICENSE */
|
|
2
|
+
var F=Object.defineProperty;var c=(i,n)=>F(i,"name",{value:n,configurable:!0});import{CanMessage as W,CanSignal as G}from"../models/CanTypes.js";import{parseCanId as C,validateCanId as P}from"@csselectronics/can-types/utils/CanIdParser";import{pgnMaskFor as w,formatPgn as U}from"@csselectronics/can-types/utils/j1939";import{validateSignalOverlaps as J}from"./SignalDecoder.js";import{encodeIdeKey as T}from"./dbcKey.js";var X=(s=>(s.Message="message",s.Signal="signal",s.ValueTable="valueTable",s.MessageComment="messageComment",s.SignalComment="signalComment",s.Multiplexing="multiplexing",s.AttributeDefinition="attributeDefinition",s.AttributeDefault="attributeDefault",s.Attribute="attribute",s.SignalValueType="signalValueType",s.Other="other",s))(X||{});const E=300;function L(i){if(i!==void 0)return i.length>E?i.slice(0,E)+"...":i}c(L,"capComment");class H{static{c(this,"MetaDataInfo")}valueTables;signalComments;messageComments;signalMultiplexors;attributes;messageAttributes;signalValueTypes;constructor(){this.valueTables=new Map,this.signalComments=new Map,this.messageComments=new Map,this.signalMultiplexors=new Map,this.attributes=new Map,this.messageAttributes=new Map,this.signalValueTypes=new Map}getMultiplexedSignals(n,r,e){const t=new Map;for(const l of this.signalMultiplexors.values())if(n===l.messageId&&(e&&!l.multiplexorName||r===l.multiplexorName))for(const o of l.values){let u=t.get(o);u||(u=[],t.set(o,u)),u.push(l.signalName)}return t}}function K(i,n,r){const e=i.match(/^BO_\s+(\d+)\s+(\w+):\s+(\d+)\s+(\w+)/);if(!e)throw new Error(`Invalid message format at line ${n}: ${i}`);const[,t,l,o,u]=e,m=parseInt(t,10),a=C(m);let p=a.canId;try{P(a)}catch(M){throw new Error(`${M.message} at line ${n}`)}r.attributes.get("ProtocolType")==="J1939"&&a.isExtended&&(p=p&w(p));const g=T(p,a.isExtended),f=T(a.canId,a.isExtended),d=parseInt(o,10);if(d<0||d>1024)throw new Error(`Invalid DLC ${d} for message ${l}: must be 0-1024`);return{messageId:g,canId:p,rawCleanId:f,dbcId:a.canId,name:l,length:d,isExtended:a.isExtended,lineNo:n,comment:L(r.messageComments.get(g)),sender:u,signals:new Map,hasMultiplexing:!1}}c(K,"parseMessageLine");function z(i,n){const r=i.match(/^SG_MUL_VAL_\s+(\d+)\s+(\w+)\s+(\w+)\s+([\d\-,\s]+);/);if(!r)return null;const[,e,t,l,o]=r,u=C(parseInt(e,10));let m=u.canId;n.attributes.get("ProtocolType")==="J1939"&&u.isExtended&&(m=m&w(m));const a=T(m,u.isExtended),p=`${a}_${t}`,s=1e4,g=[],f=o.split(",");for(const d of f){const M=d.trim().match(/^(\d+)-(\d+)$/);if(M){const h=parseInt(M[1],10),b=parseInt(M[2],10);for(let x=h;x<=b;x++)if(g.push(x),g.length>s)return null}}return g.length===0?null:{fullSignalName:p,messageId:a,values:g,multiplexorName:l,signalName:t}}c(z,"parseMultiplexorLine");function Y(i,n,r,e){const t=i.match(/^SG_\s+(\w+)\s*(?:(M|m\d+(?:M)?)\s+)?:\s*(\d+)\|(\d+)@([01])([+-])\s+\(([-+]?\d*\.?\d+(?:[eE][-+]?\d+)?),([-+]?\d*\.?\d+(?:[eE][-+]?\d+)?)\)\s+\[([-+]?\d*\.?\d+(?:[eE][-+]?\d+)?)\|([-+]?\d*\.?\d+(?:[eE][-+]?\d+)?)\]\s+"(.*?)"/);if(!t)throw new Error(`Invalid signal format at line ${n}: ${i}`);const[,l,o,u,m,a,p,s,g,f,d,M]=t,h=parseInt(m,10),b=parseFloat(s),x=parseFloat(g),D=`${r}_${l}`,N=e.signalValueTypes.get(D),A=N==="float",$=N==="double",y=j(o),S=`${r}_${l}`,k=e.valueTables.get(S),V=L(e.signalComments.get(S));!e.signalMultiplexors.get(S)&&y?.isMultiplexed&&e.signalMultiplexors.set(S,{fullSignalName:S,messageId:r,multiplexorName:void 0,signalName:l,values:[y.multiplexorValue]});const B=y?.isRoot??!1,v=y?.isMultiplexer??!1,O=y?.isMultiplexed??!1,R=M||"",I=new G({name:l,bitpos:parseInt(u,10),bitlen:h,bigendian:a==="0",signed:p==="-",factor:b,offset:x,min:parseFloat(f),max:parseFloat(d),unit:R,comment:V,ignored:!1,valueTable:k,lineNo:n,isFloat:A,isDouble:$,isMultiplexer:v,isRootMultiplexer:B,isMuxedChild:O,multiplexedSignals:v?new Map:void 0});if(I.bitpos<0||I.bitpos>=8192)throw new Error(`Invalid start bit ${I.bitpos} for signal ${l} at line ${n}`);if(I.bitlen<=0||I.bitlen>64)throw new Error(`Invalid length ${I.bitlen} for signal ${l} at line ${n}`);return I}c(Y,"parseSignalLine");function j(i){let n;if(i){if(i==="M")n={isMultiplexer:!0,isMultiplexed:!1,isRoot:!0};else{const r=i.match(/m(\d+)(M)?/);r&&(n={isMultiplexer:r[2]==="M",isMultiplexed:!0,isRoot:!1,multiplexorValue:parseInt(r[1],10)})}return n}}c(j,"parseMultiplexerIndicator");function _(i,n){const r=C(i);let e=r.canId;return n.attributes.get("ProtocolType")==="J1939"&&r.isExtended&&(e=e&w(e)),T(e,r.isExtended)}c(_,"maskedMessageKey");function q(i,n){const r=i.match(/^VAL_\s+(\d+)\s+(\w+)\s+(.+?)\s*;/);if(!r)return null;const[,e,t,l]=r,u=`${_(parseInt(e,10),n)}_${t}`,m=new Map,a=/(-?\d+)\s+"([^"]*)"/g;let p;for(;(p=a.exec(l))!==null;){const[,s,g]=p;m.set(parseInt(s,10),g)}return m.size===0?null:{key:u,valueMap:m}}c(q,"parseValueTableLine");function Q(i,n){const r=i.match(/^SIG_VALTYPE_\s+(\d+)\s+(\w+)\s*:\s*(\d+)\s*;/);if(!r)return null;const[,e,t,l]=r,u=`${_(parseInt(e,10),n)}_${t}`;return l==="1"?{key:u,valueType:"float"}:l==="2"?{key:u,valueType:"double"}:null}c(Q,"parseSignalValueTypeLine");function Z(i,n){if(i.startsWith("CM_ SG_")){const r=i.match(/^CM_\s+SG_\s+(\d+)\s+(\w+)\s+"([^"]+)"/);if(r){const[,e,t,l]=r;return{key:`${_(parseInt(e,10),n)}_${t}`,comment:l}}}return null}c(Z,"parseSignalCommentLine");function ee(i,n){if(i.startsWith("CM_ BO_")){const r=i.match(/^CM_\s+BO_\s+(\d+)\s+"([^"]+)"/);if(r){const[,e,t]=r;return{key:_(parseInt(e,10),n),comment:t}}}return null}c(ee,"parseMessageCommentLine");function te(i){const n=i.match(/^BA_\s+"([^"]+)"\s+BO_\s+(\d+)\s+"([^"]+)"\s*;/);if(n){const[,l,o,u]=n;return{key:l,value:u,messageId:parseInt(o,10)}}const r=i.match(/^BA_\s+"([^"]+)"\s+BO_\s+(\d+)\s+([-+]?\d+(?:\.\d+)?)\s*;/);if(r){const[,l,o,u]=r;return{key:l,value:parseFloat(u),messageId:parseInt(o,10)}}const e=i.match(/^BA_\s+"([^"]+)"\s+"([^"]+)"\s*;/);if(e){const[,l,o]=e;return{key:l,value:o}}const t=i.match(/^BA_\s+"([^"]+)"\s+([-+]?\d+(?:\.\d+)?)\s*;/);if(t){const[,l,o]=t;return{key:l,value:parseFloat(o)}}return null}c(te,"parseAttributeLine");function ne(i){const n=new H,{valueTables:r,signalComments:e,messageComments:t,signalMultiplexors:l,attributes:o}=n;for(const{lineType:u,content:m}of i)if(u==="attribute"){const a=te(m);if(a)if(a.messageId!==void 0){const p=C(a.messageId),s=T(p.canId,p.isExtended);let g=n.messageAttributes.get(s);g||(g=new Map,n.messageAttributes.set(s,g)),g.set(a.key,a.value)}else o.set(a.key,a.value)}for(const{lineType:u,content:m}of i)if(u=="multiplexing"){const a=z(m,n);a!=null&&l.set(a.fullSignalName,a)}else if(u==="valueTable"){const a=q(m,n);a&&r.set(a.key,a.valueMap)}else if(u==="messageComment"){const a=ee(m,n);a&&t.set(a.key,a.comment)}else if(u==="signalComment"){const a=Z(m,n);a&&e.set(a.key,a.comment)}else if(u==="signalValueType"){const a=Q(m,n);a&&n.signalValueTypes.set(a.key,a.valueType)}return n}c(ne,"parseMetaData");function se(i){if(typeof i!="string")return;const n=i.split(/\r?\n/),r=[];let e="other";for(const[t,l]of n.entries()){const o=l.trim();!o||o.startsWith("//")||(o.startsWith("BO_TX_BU_")?e="other":o.startsWith("BO_")?e="message":o.startsWith("VAL_")?e="valueTable":o.startsWith("CM_ SG_")?e="signalComment":o.startsWith("CM_")?e="messageComment":o.startsWith("SG_MUL_VAL_")?e="multiplexing":o.startsWith("SIG_VALTYPE_")?e="signalValueType":o.startsWith("SG_")?e="signal":o.startsWith("BA_DEF_ ")?e="attributeDefinition":o.startsWith("BA_DEF_DEF_ ")?e="attributeDefault":o.startsWith("BA_ ")?e="attribute":e="other",r.push({lineType:e,lineNumber:t+1,content:o}))}return r}c(se,"parseLines");function ae(i,n,r){const e=new Map;for(const t of i.values()){let l;for(const s of t.signals.values()){if(s.isMultiplexer&&s.multiplexedSignals){const g=n.getMultiplexedSignals(t.messageId,s.name,s.isRootMultiplexer||!1);for(const[f,d]of g.entries())for(const M of d){const h=t.signals.get(M);if(h){let b=s.multiplexedSignals.get(f);b||(b=[],s.multiplexedSignals.set(f,b)),b.push(h)}}}s.isRootMultiplexer&&(l=s,t.hasMultiplexing=!0)}const o=Array.from(t.signals.values());J(o,t.name,t.messageId);for(const s of o)s.bitlen>32&&!s.isFloat&&!s.isDouble&&r.push({messageName:t.name,signalName:s.name,bitlen:s.bitlen});const u=n.messageAttributes.get(t.rawCleanId),m=u?.get("VariableLength"),a=m===1||m==="1";let p=new W({key:t.canId,name:t.name,length:t.length,isExtended:t.isExtended,dbcId:t.dbcId,isMultiplexed:t.hasMultiplexing,isVariableLength:a,multiplexorSignal:l,signals:o,lineNo:t.lineNo,attributes:u,comment:t.comment});e.set(t.messageId,p)}return e}c(ae,"processMessages");function pe(i,n=null){if(typeof i!="string")throw new Error("Invalid DBC content: must be a string");const r=se(i);if(!r)throw new Error("Invalid DBC format");const e=new Map;let t=null;try{const l=ne(r);for(const{lineType:m,content:a,lineNumber:p}of r){if(m==="message"){const s=K(a,p,l);if(s.name==="VECTOR__INDEPENDENT_SIG_MSG"){t=null;continue}const g=e.get(s.messageId);if(g){let d=`Duplicate message ID ${`0x${s.canId.toString(16).toUpperCase()}`}: "${s.name}" at line ${p} conflicts with "${g.name}" at line ${g.lineNo}`;throw g.rawCleanId!==s.rawCleanId&&(d+=` (distinct raw IDs collide after J1939 PGN masking, PGN ${U(s.canId>>>8)})`),new Error(d)}e.set(s.messageId,s),t=s}if(m==="signal"&&t!=null){const s=Y(a,p,t.messageId,l);t.signals.set(s.name,s)}}const o=[],u=ae(e,l,o);if(u.size===0)throw new Error("No valid CAN messages found in DBC file");return{messages:u,metadata:{fileName:n,attributes:l.attributes,skippedSignals:o}}}catch(l){throw new Error(`DBC parsing failed : ${l.message}`)}}c(pe,"parseDBC");export{pe as parseDBC};
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { CanMessage } from '../models/CanTypes.js';
|
|
2
|
+
import type { SkippedSignal } from './DbcParser.js';
|
|
3
|
+
/**
|
|
4
|
+
* JsonParser - Parses simplified JSON CAN definition format.
|
|
5
|
+
* Supports nested multiplexing structures and Vector-style CAN ID flags.
|
|
6
|
+
*/
|
|
7
|
+
interface JsonParseResult {
|
|
8
|
+
messages: Map<number, CanMessage>;
|
|
9
|
+
metadata: {
|
|
10
|
+
fileName: string | null;
|
|
11
|
+
hasMultiplexing: boolean;
|
|
12
|
+
/** Integer signals >32 bits that were excluded from decoding. */
|
|
13
|
+
skippedSignals: SkippedSignal[];
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Parse JSON file text into structured data
|
|
18
|
+
*
|
|
19
|
+
* @param jsonText - Raw JSON file content
|
|
20
|
+
* @param fileName - Optional file name for reference
|
|
21
|
+
* @returns Parsed messages, value tables, and metadata
|
|
22
|
+
* @throws {Error} If parsing fails
|
|
23
|
+
*/
|
|
24
|
+
export declare function parseJSON(jsonText: string, fileName?: string | null): JsonParseResult;
|
|
25
|
+
export {};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! @csselectronics/can-decode v0.1.0 (c) CSS Electronics ApS, see LICENSE */
|
|
2
|
+
var y=Object.defineProperty;var x=(o,f)=>y(o,"name",{value:f,configurable:!0});import{CanMessage as w,CanSignal as C}from"../models/CanTypes.js";import{parseCanId as N,validateCanId as I}from"@csselectronics/can-types/utils/CanIdParser";import{encodeIdeKey as J}from"./dbcKey.js";import{validateSignalOverlaps as k}from"./SignalDecoder.js";function R(o,f=null){if(!o||typeof o!="string")throw new Error("Invalid JSON content: must be a non-empty string");const g=new Map;let e=!1;const m=[];try{const i=JSON.parse(o);if(!i.messages||!Array.isArray(i.messages))throw new Error('Invalid JSON format: missing "messages" array');for(const s of i.messages){const p=s.key,a=N(p);I(a);let t=[],u,c=!1;if(s.signals&&Array.isArray(s.signals)){t=h(s.signals);for(const r of t)if(r.multiplexedSignals&&r.multiplexedSignals.size>0){u||(u=r,c=!0),e=!0;break}s.signals.some(r=>r.multiplexed?.length>0)||k(t,s.name||`Message_${a.canId}`,a.canId)}const n=s.name||`Message_${a.canId}`;for(const l of t)l.bitlen>32&&!l.isFloat&&!l.isDouble&&m.push({messageName:n,signalName:l.name,bitlen:l.bitlen});const d=new w({key:a.canId,name:n,length:s.length||8,isExtended:a.isExtended,isMultiplexed:c,isVariableLength:s.isVariableLength===!0,multiplexorSignal:u,signals:t});g.set(J(a.canId,a.isExtended),d)}return{messages:g,metadata:{fileName:f,hasMultiplexing:e,skippedSignals:m}}}catch(i){throw new Error(`JSON parsing failed: ${i.message}`)}}x(R,"parseJSON");function h(o,f=!1){const g=[];for(const e of o){const m=e.unit||"";let i,s=!1,p=!1;if(e.multiplexed&&Array.isArray(e.multiplexed)&&e.multiplexed.length>0){i=new Map,s=!0,p=e.isRoot||!1;for(const n of e.multiplexed){const d=n.from,l=n.to!==void 0?n.to:d,r=n.signals&&Array.isArray(n.signals)?h(n.signals,!0):[];for(let S=d;S<=l;S++){let b=i.get(S);b||(b=[],i.set(S,b));for(const M of r)b.push(M)}g.push(...r)}}if(e.ignored)continue;const a=e.bigendian||!1,t=e.bitpos,u=a?8*Math.floor(t/8)+(7-t%8):t,c=new C({name:e.name,bitpos:u,bitlen:e.bitlen,bigendian:a,signed:e.signed||!1,factor:e.factor||1,offset:e.offset||0,min:e.min||0,max:e.max||0,unit:m,ignored:!1,lineNo:e.lineNo||0,isFloat:!1,isDouble:!1,isMultiplexer:s,isRootMultiplexer:p,isMuxedChild:f,valueTable:e.valueTable?new Map(Object.entries(e.valueTable).map(([n,d])=>[Number(n),d])):void 0,multiplexedSignals:i});g.push(c)}return g}x(h,"parseJSONSignals");export{R as parseJSON};
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { CanSignal } from '../models/CanTypes.js';
|
|
2
|
+
import type { DecodedSignal } from '../models/DecodedSignal.js';
|
|
3
|
+
export type { DecodedSignal } from '../models/DecodedSignal.js';
|
|
4
|
+
/** Extract little-endian (Intel) signal value. */
|
|
5
|
+
export declare function extractLittleEndian(data: Uint8Array, bitpos: number, bitlen: number): number;
|
|
6
|
+
/**
|
|
7
|
+
* Extraction for big-endian (Motorola) signals.
|
|
8
|
+
* Byte-aligned fast path for common case; general path for arbitrary bit positions.
|
|
9
|
+
*/
|
|
10
|
+
export declare function extractBigEndian(data: Uint8Array, bitpos: number, bitlen: number): number;
|
|
11
|
+
/**
|
|
12
|
+
* Validate that no two signals within a message occupy the same bits.
|
|
13
|
+
* Skips validation for multiplexed messages (muxed signals legitimately share bit positions).
|
|
14
|
+
*
|
|
15
|
+
* @param signals - Array of signals to check (must have DBC-convention bitpos)
|
|
16
|
+
* @param messageName - Message name for error reporting
|
|
17
|
+
* @param messageId - Message ID for error reporting
|
|
18
|
+
* @throws {Error} If overlapping signals are detected
|
|
19
|
+
*/
|
|
20
|
+
export declare function validateSignalOverlaps(signals: {
|
|
21
|
+
name: string;
|
|
22
|
+
bitpos: number;
|
|
23
|
+
bitlen: number;
|
|
24
|
+
bigendian: boolean;
|
|
25
|
+
isMultiplexer?: boolean;
|
|
26
|
+
}[], messageName: string, messageId: number): void;
|
|
27
|
+
/**
|
|
28
|
+
* Extract raw integer value using CanSignal definition
|
|
29
|
+
*/
|
|
30
|
+
export declare function extractRawValue(data: Uint8Array, signal: CanSignal): number;
|
|
31
|
+
/** Apply two's complement for signed values. */
|
|
32
|
+
export declare function applyTwosComplement(raw: number, bitlen: number): number;
|
|
33
|
+
/** Apply factor and offset to scale physical value. */
|
|
34
|
+
export declare function applyFactorOffset(raw: number, signal: CanSignal): number;
|
|
35
|
+
/** Full decoding pipeline for a single signal. Returns numeric value only. */
|
|
36
|
+
export declare function decodeSignalValue(data: Uint8Array, signal: CanSignal): number;
|
|
37
|
+
/** Full decoding pipeline for a single signal. Returns DecodedSignal with signal reference. */
|
|
38
|
+
export declare function decodeSignal(data: Uint8Array, signal: CanSignal): DecodedSignal;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! @csselectronics/can-decode v0.1.0 (c) CSS Electronics ApS, see LICENSE */
|
|
2
|
+
var m=Object.defineProperty;var a=(e,t)=>m(e,"name",{value:t,configurable:!0});function y(e,t){return t?8*Math.floor(e/8)+(7-e%8):e}a(y,"dbcBitPosToInternal");function p(e,t,r){const o=Math.floor(t/8),n=new Uint8Array(4);for(let i=0;i<4;i++)o+i<e.length&&(n[i]=e[o+i]);return new DataView(n.buffer).getFloat32(0,!r)}a(p,"extractFloat32");function d(e,t,r){const o=Math.floor(t/8),n=new Uint8Array(8);for(let i=0;i<8;i++)o+i<e.length&&(n[i]=e[o+i]);return new DataView(n.buffer).getFloat64(0,!r)}a(d,"extractFloat64");function g(e,t,r){const o=Math.floor(t/8),n=t%8,u=t+r,i=Math.floor((u-1)/8);let f=0,s=0;for(let l=o;l<=i&&l<e.length;l++){let c=e[l];l===o&&n>0&&(c>>=n);const b=u-l*8;b<8&&(c&=(1<<b)-1),f|=c<<s,s+=8-(l===o?n:0)}return r===32?f>>>0:f&(1<<r)-1}a(g,"extractLittleEndian");function x(e,t,r){const o=Math.floor(t/8);if(t%8===7&&r%8===0){let f=0;const s=r/8;for(let l=0;l<s&&o+l<e.length;l++)f=f<<8|e[o+l];return r===32?f>>>0:f}let u=y(t,!0),i=0;for(let f=0;f<r;f++,u++){const s=Math.floor(u/8);if(s>=e.length)break;const l=7-u%8;i=i<<1|e[s]>>l&1}return i>>>0}a(x,"extractBigEndian");function h(e,t,r){const o=[];if(r){let n=e;for(let u=0;u<t;u++)o.push(n),n%8===0?n=(Math.floor(n/8)+1)*8+7:n--}else for(let n=0;n<t;n++)o.push(e+n);return o}a(h,"getOccupiedBits");function M(e,t,r){if(e.some(n=>n.isMultiplexer))return;const o=e.map(n=>({name:n.name,bits:new Set(h(n.bitpos,n.bitlen,n.bigendian))}));for(let n=0;n<o.length;n++)for(let u=n+1;u<o.length;u++)for(const i of o[n].bits)if(o[u].bits.has(i))throw new Error(`Overlapping signals in message "${t}" (0x${r.toString(16)}): "${o[n].name}" and "${o[u].name}" share bit ${i}`)}a(M,"validateSignalOverlaps");function B(e,t){const{bitpos:r,bitlen:o,bigendian:n}=t;return t.isFloat?p(e,r,n):t.isDouble?d(e,r,n):n?x(e,r,o):g(e,r,o)}a(B,"extractRawValue");function S(e,t){if(t===32)return e&2147483648?e-4294967296:e;const r=1<<t-1;return e&r?e-(1<<t):e}a(S,"applyTwosComplement");function v(e,t){return e*t.factor+t.offset}a(v,"applyFactorOffset");function w(e,t){let r=B(e,t);return t.signed&&!t.isFloat&&!t.isDouble&&(r=S(r,t.bitlen)),t.isIdentityScale?r:r*t.factor+t.offset}a(w,"decodeSignalValue");function A(e,t){return{signal:t,value:w(e,t)}}a(A,"decodeSignal");export{v as applyFactorOffset,S as applyTwosComplement,A as decodeSignal,w as decodeSignalValue,x as extractBigEndian,g as extractLittleEndian,B as extractRawValue,M as validateSignalOverlaps};
|