@elkamarado/remote-oscilloscope-tbs2204b-driver 0.0.0-stage → 0.2.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 ADDED
@@ -0,0 +1,17 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
package/README.md CHANGED
@@ -1,3 +1,59 @@
1
- # Temporary Holding Version
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.
1
+ # TBS2204B driver
2
+
3
+ A TypeScript SCPI/TCP driver for Tektronix TBS2204B oscilloscopes. The
4
+ instrument's Ethernet SCPI socket uses port `4000`.
5
+
6
+ ```ts
7
+ import { Tbs2204bDriver } from "@elkamarado/remote-oscilloscope-tbs2204b-driver";
8
+
9
+ const scope = new Tbs2204bDriver({ host: "10.0.5.44" });
10
+ try {
11
+ await scope.connect();
12
+ console.log(await scope.identify());
13
+ const capture = await scope.capture(["CH1", "CH2"]);
14
+ } finally {
15
+ await scope.disconnect();
16
+ }
17
+ ```
18
+
19
+ `capture()` freezes acquisition for the duration of a multi-channel read and
20
+ restores the acquisition state and waveform-transfer settings afterward.
21
+ Waveform samples are scaled to volts; sample times are derived from the
22
+ instrument preamble. Captured waveforms also include a snapshot of the
23
+ instrument's channel enable/scale/position settings and horizontal
24
+ seconds-per-division. `getDisplaySettings()` reads the same settings without
25
+ capturing. `decodeI2c()` operates on the captured waveforms and does not
26
+ require further instrument commands.
27
+
28
+ `executeScpi(command)` sends a single-line text SCPI command and returns its
29
+ response for queries. Binary waveform queries are intentionally excluded;
30
+ use `capture()` for waveform data.
31
+
32
+ The initial implementation uses the scope's current waveform transfer window.
33
+ It does not change vertical or horizontal display settings.
34
+
35
+ ## Development
36
+
37
+ - `npm test`
38
+ - `npm run build`
39
+
40
+ ## Publishing
41
+
42
+ The publishing script builds and tests the package, then stages it on npm.
43
+ The first release uses the current version; for later releases, pass a version
44
+ bump such as `patch`, `minor`, or `major`:
45
+
46
+ ```powershell
47
+ .\scripts\publish-npm.ps1
48
+ .\scripts\publish-npm.ps1 -VersionType patch
49
+ ```
50
+
51
+ The script asks for the npm stage-only token with masked input and removes its
52
+ temporary npm configuration when it exits. Use `-DryRun` to check the workflow
53
+ without entering a token or staging a package. The staging CLI requires Node.js
54
+ 22.9 or newer.
55
+
56
+ Staging does not publish the package publicly. After reviewing the staged
57
+ version, approve it with `npx --yes npm@11 stage approve <stage-id>`; npm will
58
+ require your 2FA code. You can list pending versions with
59
+ `npx --yes npm@11 stage list`.
@@ -0,0 +1,78 @@
1
+ type Channel = "CH1" | "CH2" | "CH3" | "CH4";
2
+ interface DriverOptions {
3
+ host: string;
4
+ port?: number;
5
+ timeoutMs?: number;
6
+ maxWaveformBytes?: number;
7
+ onConnectionError?: (error: Error) => void;
8
+ }
9
+ interface DeviceIdentity {
10
+ manufacturer: string;
11
+ model: string;
12
+ serialNumber: string;
13
+ firmware: string;
14
+ raw: string;
15
+ }
16
+ interface ChannelDisplaySettings {
17
+ enabled: boolean;
18
+ voltsPerDivision: number;
19
+ positionDivisions: number;
20
+ }
21
+ interface ScopeDisplaySettings {
22
+ secondsPerDivision: number;
23
+ channels: Record<Channel, ChannelDisplaySettings>;
24
+ }
25
+ interface Waveform {
26
+ channel: Channel;
27
+ capturedAt: string;
28
+ displaySettings?: ScopeDisplaySettings;
29
+ xIncrement: number;
30
+ xZero: number;
31
+ pointOffset: number;
32
+ yIncrement: number;
33
+ yZero: number;
34
+ yOffset: number;
35
+ samples: number[];
36
+ }
37
+ interface I2cDecodeOptions {
38
+ sclChannel: Channel;
39
+ sdaChannel: Channel;
40
+ thresholdVolts?: number;
41
+ }
42
+ type I2cEvent = {
43
+ kind: "start" | "repeated-start" | "stop";
44
+ time: number;
45
+ } | {
46
+ kind: "address";
47
+ time: number;
48
+ byte: number;
49
+ address: number;
50
+ direction: "write" | "read";
51
+ acknowledged: boolean;
52
+ } | {
53
+ kind: "data";
54
+ time: number;
55
+ byte: number;
56
+ acknowledged: boolean;
57
+ };
58
+
59
+ declare class Tbs2204bDriver {
60
+ private readonly connection;
61
+ private operation;
62
+ constructor(options: DriverOptions);
63
+ get connected(): boolean;
64
+ connect(): Promise<void>;
65
+ disconnect(): Promise<void>;
66
+ executeScpi(command: string): Promise<string>;
67
+ identify(): Promise<DeviceIdentity>;
68
+ getDisplaySettings(): Promise<ScopeDisplaySettings>;
69
+ capture(channels: readonly Channel[]): Promise<Waveform[]>;
70
+ private readPreamble;
71
+ private queryNumber;
72
+ private readDisplaySettings;
73
+ private enqueue;
74
+ }
75
+
76
+ declare function decodeI2c(waveforms: readonly Waveform[], options: I2cDecodeOptions): I2cEvent[];
77
+
78
+ export { type Channel, type ChannelDisplaySettings, type DeviceIdentity, type DriverOptions, type I2cDecodeOptions, type I2cEvent, type ScopeDisplaySettings, Tbs2204bDriver, type Waveform, decodeI2c };
package/dist/index.js ADDED
@@ -0,0 +1,523 @@
1
+ // src/scpi-connection.ts
2
+ import net from "net";
3
+ var SocketByteReader = class {
4
+ chunks = [];
5
+ available = 0;
6
+ reads = [];
7
+ failure = null;
8
+ push(chunk) {
9
+ if (chunk.length === 0) return;
10
+ this.chunks.push(chunk);
11
+ this.available += chunk.length;
12
+ this.drain();
13
+ }
14
+ fail(error) {
15
+ this.failure = error;
16
+ for (const read of this.reads.splice(0)) read.reject(error);
17
+ }
18
+ read(length) {
19
+ if (!Number.isInteger(length) || length < 0) {
20
+ return Promise.reject(new Error("Read length must be a non-negative integer"));
21
+ }
22
+ if (length === 0) return Promise.resolve(Buffer.alloc(0));
23
+ if (this.failure) return Promise.reject(this.failure);
24
+ return new Promise((resolve, reject) => {
25
+ this.reads.push({ length, resolve, reject });
26
+ this.drain();
27
+ });
28
+ }
29
+ drain() {
30
+ while (this.reads.length > 0 && this.available >= this.reads[0].length) {
31
+ const request = this.reads.shift();
32
+ if (request) request.resolve(this.take(request.length));
33
+ }
34
+ }
35
+ take(length) {
36
+ const result = Buffer.allocUnsafe(length);
37
+ let written = 0;
38
+ while (written < length) {
39
+ const first = this.chunks[0];
40
+ const count = Math.min(first.length, length - written);
41
+ first.copy(result, written, 0, count);
42
+ written += count;
43
+ this.available -= count;
44
+ if (count === first.length) {
45
+ this.chunks.shift();
46
+ } else {
47
+ this.chunks[0] = first.subarray(count);
48
+ }
49
+ }
50
+ return result;
51
+ }
52
+ };
53
+ var ScpiConnection = class {
54
+ constructor(host, port, timeoutMs, maxWaveformBytes, onConnectionError) {
55
+ this.host = host;
56
+ this.port = port;
57
+ this.timeoutMs = timeoutMs;
58
+ this.maxWaveformBytes = maxWaveformBytes;
59
+ this.onConnectionError = onConnectionError;
60
+ }
61
+ host;
62
+ port;
63
+ timeoutMs;
64
+ maxWaveformBytes;
65
+ onConnectionError;
66
+ socket = null;
67
+ reader = null;
68
+ operation = Promise.resolve();
69
+ get connected() {
70
+ return this.socket?.readyState === "open";
71
+ }
72
+ async connect() {
73
+ if (this.connected) return;
74
+ const socket = new net.Socket();
75
+ socket.setTimeout(this.timeoutMs);
76
+ socket.setNoDelay(true);
77
+ await new Promise((resolve, reject) => {
78
+ const onError = (error) => {
79
+ socket.destroy();
80
+ reject(error);
81
+ };
82
+ socket.once("error", onError);
83
+ socket.once("timeout", () => onError(new Error("SCPI connection timed out")));
84
+ socket.connect(this.port, this.host, () => {
85
+ socket.removeListener("error", onError);
86
+ socket.removeAllListeners("timeout");
87
+ resolve();
88
+ });
89
+ });
90
+ const reader = new SocketByteReader();
91
+ let socketError = null;
92
+ const failConnection = (error) => {
93
+ reader.fail(error);
94
+ if (this.socket !== socket || socketError) return;
95
+ socketError = error;
96
+ this.onConnectionError?.(error);
97
+ };
98
+ socket.on("data", (chunk) => reader.push(chunk));
99
+ socket.on("error", failConnection);
100
+ socket.on("close", () => failConnection(new Error("SCPI connection closed")));
101
+ socket.on("timeout", () => {
102
+ failConnection(new Error("SCPI operation timed out"));
103
+ socket.destroy();
104
+ });
105
+ this.socket = socket;
106
+ this.reader = reader;
107
+ }
108
+ async disconnect() {
109
+ const socket = this.socket;
110
+ this.socket = null;
111
+ this.reader = null;
112
+ if (!socket) return;
113
+ await new Promise((resolve) => {
114
+ if (socket.destroyed) {
115
+ resolve();
116
+ return;
117
+ }
118
+ socket.once("close", resolve);
119
+ socket.end();
120
+ socket.destroy();
121
+ });
122
+ }
123
+ queryLine(command) {
124
+ return this.enqueue(async () => {
125
+ await this.writeCommand(command);
126
+ const reader = this.requireReader();
127
+ const bytes = [];
128
+ let total = 0;
129
+ while (total < 65536) {
130
+ const byte = await reader.read(1);
131
+ if (byte[0] === 10) {
132
+ return Buffer.concat(bytes, total).toString("ascii").replace(/\r$/, "").trim();
133
+ }
134
+ bytes.push(byte);
135
+ total += byte.length;
136
+ }
137
+ throw new Error(`SCPI response exceeded 65536 bytes: ${command}`);
138
+ });
139
+ }
140
+ write(command) {
141
+ return this.enqueue(() => this.writeCommand(command));
142
+ }
143
+ queryBinaryBlock(command) {
144
+ return this.enqueue(async () => {
145
+ await this.writeCommand(command);
146
+ const reader = this.requireReader();
147
+ const marker = await reader.read(1);
148
+ if (marker[0] !== 35) {
149
+ throw new Error(`Expected IEEE binary block for ${command}, received 0x${marker[0].toString(16)}`);
150
+ }
151
+ const digitByte = await reader.read(1);
152
+ const digitCount = digitByte[0] - 48;
153
+ if (digitCount < 1 || digitCount > 9) {
154
+ throw new Error(`Invalid IEEE binary block length header for ${command}`);
155
+ }
156
+ const lengthText = (await reader.read(digitCount)).toString("ascii");
157
+ if (!/^\d+$/.test(lengthText)) {
158
+ throw new Error(`Invalid IEEE binary block size: ${lengthText}`);
159
+ }
160
+ const length = Number(lengthText);
161
+ if (!Number.isSafeInteger(length) || length > this.maxWaveformBytes) {
162
+ throw new Error(`Waveform block size ${length} exceeds the configured limit`);
163
+ }
164
+ const payload = await reader.read(length);
165
+ const terminator = await reader.read(1);
166
+ if (terminator[0] !== 10 && terminator[0] !== 13) {
167
+ throw new Error(`Expected waveform block terminator, received 0x${terminator[0].toString(16)}`);
168
+ }
169
+ if (terminator[0] === 13) {
170
+ const lineFeed = await reader.read(1);
171
+ if (lineFeed[0] !== 10) {
172
+ throw new Error("Invalid CRLF terminator after waveform block");
173
+ }
174
+ }
175
+ return payload;
176
+ });
177
+ }
178
+ writeCommand(command) {
179
+ const socket = this.socket;
180
+ if (!socket || !this.reader || !this.connected) {
181
+ return Promise.reject(new Error("Not connected to the oscilloscope"));
182
+ }
183
+ if (!command.trim() || /[\r\n]/.test(command)) {
184
+ return Promise.reject(new Error("SCPI command must be a non-empty single line"));
185
+ }
186
+ return new Promise((resolve, reject) => {
187
+ socket.write(`${command}
188
+ `, (error) => {
189
+ if (error) reject(error);
190
+ else resolve();
191
+ });
192
+ });
193
+ }
194
+ requireReader() {
195
+ if (!this.reader) throw new Error("Not connected to the oscilloscope");
196
+ return this.reader;
197
+ }
198
+ enqueue(operation) {
199
+ const result = this.operation.then(operation);
200
+ this.operation = result.then(
201
+ () => void 0,
202
+ () => void 0
203
+ );
204
+ return result;
205
+ }
206
+ };
207
+
208
+ // src/driver.ts
209
+ var DEFAULT_PORT = 4e3;
210
+ var DEFAULT_TIMEOUT_MS = 15e3;
211
+ var DEFAULT_MAX_WAVEFORM_BYTES = 16 * 1024 * 1024;
212
+ var CHANNELS = ["CH1", "CH2", "CH3", "CH4"];
213
+ var Tbs2204bDriver = class {
214
+ connection;
215
+ operation = Promise.resolve();
216
+ constructor(options) {
217
+ if (!options.host.trim()) throw new Error("An oscilloscope host is required");
218
+ const port = options.port ?? DEFAULT_PORT;
219
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
220
+ const maxWaveformBytes = options.maxWaveformBytes ?? DEFAULT_MAX_WAVEFORM_BYTES;
221
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
222
+ throw new Error("The SCPI TCP port must be an integer from 1 to 65535");
223
+ }
224
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
225
+ throw new Error("The SCPI timeout must be a positive finite number");
226
+ }
227
+ if (!Number.isSafeInteger(maxWaveformBytes) || maxWaveformBytes <= 0) {
228
+ throw new Error("The maximum waveform size must be a positive safe integer");
229
+ }
230
+ this.connection = new ScpiConnection(
231
+ options.host.trim(),
232
+ port,
233
+ timeoutMs,
234
+ maxWaveformBytes,
235
+ options.onConnectionError
236
+ );
237
+ }
238
+ get connected() {
239
+ return this.connection.connected;
240
+ }
241
+ connect() {
242
+ return this.enqueue(() => this.connection.connect());
243
+ }
244
+ disconnect() {
245
+ return this.enqueue(() => this.connection.disconnect());
246
+ }
247
+ executeScpi(command) {
248
+ return this.enqueue(async () => {
249
+ if (!command.trim() || /[\r\n]/.test(command)) {
250
+ throw new Error("SCPI command must be a non-empty single line");
251
+ }
252
+ const normalized = command.trim();
253
+ if (/CURVe\s*\?$/i.test(normalized)) {
254
+ throw new Error("Binary waveform queries are handled by waveform capture, not the text terminal");
255
+ }
256
+ if (normalized.endsWith("?")) return this.connection.queryLine(normalized);
257
+ await this.connection.write(normalized);
258
+ return "Sent; no response was requested.";
259
+ });
260
+ }
261
+ identify() {
262
+ return this.enqueue(async () => {
263
+ const raw = await this.connection.queryLine("*IDN?");
264
+ const [manufacturer = "", model = "", serialNumber = "", ...firmwareParts] = raw.split(",");
265
+ if (!model) throw new Error(`Unexpected instrument identity response: ${raw}`);
266
+ return {
267
+ manufacturer,
268
+ model,
269
+ serialNumber,
270
+ firmware: firmwareParts.join(","),
271
+ raw
272
+ };
273
+ });
274
+ }
275
+ getDisplaySettings() {
276
+ return this.enqueue(() => this.readDisplaySettings());
277
+ }
278
+ capture(channels) {
279
+ return this.enqueue(async () => {
280
+ if (channels.length === 0) throw new Error("Select at least one channel");
281
+ const uniqueChannels = [...new Set(channels)];
282
+ for (const channel of uniqueChannels) {
283
+ if (!CHANNELS.includes(channel)) throw new Error(`Unsupported channel: ${channel}`);
284
+ }
285
+ const previous = {
286
+ acquisitionState: await this.queryNumber("ACQ:STATE?"),
287
+ source: await this.connection.queryLine("DAT:SOU?"),
288
+ encoding: await this.connection.queryLine("DAT:ENC?"),
289
+ width: await this.queryNumber("DAT:WID?")
290
+ };
291
+ const capturedAt = (/* @__PURE__ */ new Date()).toISOString();
292
+ let primaryError;
293
+ let waveforms = [];
294
+ try {
295
+ if (previous.acquisitionState !== 0) {
296
+ await this.connection.write("ACQ:STATE 0");
297
+ }
298
+ const settings = await this.readDisplaySettings();
299
+ for (const channel of uniqueChannels) {
300
+ if (!settings.channels[channel].enabled) {
301
+ throw new Error(
302
+ `${channel} is disabled on the oscilloscope; enable it before capturing`
303
+ );
304
+ }
305
+ }
306
+ await this.connection.write("DAT:ENC SRIBINARY");
307
+ await this.connection.write("DAT:WID 1");
308
+ waveforms = [];
309
+ for (const channel of uniqueChannels) {
310
+ await this.connection.write(`DAT:SOU ${channel}`);
311
+ const preamble = await this.readPreamble();
312
+ const data = await this.connection.queryBinaryBlock("CURVE?");
313
+ if (data.length !== preamble.pointCount) {
314
+ throw new Error(
315
+ `${channel}: expected ${preamble.pointCount} waveform bytes, received ${data.length}`
316
+ );
317
+ }
318
+ waveforms.push({
319
+ channel,
320
+ capturedAt,
321
+ displaySettings: settings,
322
+ xIncrement: preamble.xIncrement,
323
+ xZero: preamble.xZero,
324
+ pointOffset: preamble.pointOffset,
325
+ yIncrement: preamble.yIncrement,
326
+ yZero: preamble.yZero,
327
+ yOffset: preamble.yOffset,
328
+ samples: Array.from(
329
+ { length: data.length },
330
+ (_, index) => (data.readInt8(index) - preamble.yOffset) * preamble.yIncrement + preamble.yZero
331
+ )
332
+ });
333
+ }
334
+ } catch (error) {
335
+ primaryError = error;
336
+ }
337
+ const restoreErrors = [];
338
+ for (const [command, value] of [
339
+ ["DAT:SOU", previous.source],
340
+ ["DAT:ENC", previous.encoding],
341
+ ["DAT:WID", String(previous.width)]
342
+ ]) {
343
+ try {
344
+ await this.connection.write(`${command} ${value}`);
345
+ } catch (error) {
346
+ restoreErrors.push(toError(error));
347
+ }
348
+ }
349
+ if (previous.acquisitionState !== 0) {
350
+ try {
351
+ await this.connection.write("ACQ:STATE 1");
352
+ } catch (error) {
353
+ restoreErrors.push(toError(error));
354
+ }
355
+ }
356
+ if (primaryError && restoreErrors.length > 0) {
357
+ throw new AggregateError(
358
+ [toError(primaryError), ...restoreErrors],
359
+ "Waveform acquisition failed and oscilloscope settings could not all be restored"
360
+ );
361
+ }
362
+ if (primaryError) throw primaryError;
363
+ if (restoreErrors.length > 0) {
364
+ throw new AggregateError(restoreErrors, "Could not restore oscilloscope settings");
365
+ }
366
+ return waveforms;
367
+ });
368
+ }
369
+ async readPreamble() {
370
+ return {
371
+ pointCount: await this.queryNumber("WFMOUTPRE:NR_PT?"),
372
+ xIncrement: await this.queryNumber("WFMOUTPRE:XINCR?"),
373
+ xZero: await this.queryNumber("WFMOUTPRE:XZERO?"),
374
+ pointOffset: await this.queryNumber("WFMOUTPRE:PT_OFF?"),
375
+ yIncrement: await this.queryNumber("WFMOUTPRE:YMULT?"),
376
+ yZero: await this.queryNumber("WFMOUTPRE:YZERO?"),
377
+ yOffset: await this.queryNumber("WFMOUTPRE:YOFF?")
378
+ };
379
+ }
380
+ async queryNumber(command) {
381
+ const response = await this.connection.queryLine(command);
382
+ const match = /(?:^|\s)([+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?)\s*$/i.exec(response);
383
+ const value = match ? Number(match[1]) : Number.NaN;
384
+ if (!Number.isFinite(value)) {
385
+ throw new Error(`Expected a numeric response to ${command}, received "${response}"`);
386
+ }
387
+ return value;
388
+ }
389
+ async readDisplaySettings() {
390
+ const channels = {};
391
+ for (const channel of CHANNELS) {
392
+ const voltsPerDivision = await this.queryNumber(`${channel}:SCALE?`);
393
+ if (voltsPerDivision <= 0) {
394
+ throw new Error(`Invalid vertical scale for ${channel}: ${voltsPerDivision}`);
395
+ }
396
+ channels[channel] = {
397
+ enabled: await this.queryNumber(`SELECT:${channel}?`) !== 0,
398
+ voltsPerDivision,
399
+ positionDivisions: await this.queryNumber(`${channel}:POSITION?`)
400
+ };
401
+ }
402
+ const secondsPerDivision = await this.queryNumber("HOR:MAI:SCALE?");
403
+ if (secondsPerDivision <= 0) {
404
+ throw new Error(`Invalid horizontal scale: ${secondsPerDivision}`);
405
+ }
406
+ return {
407
+ secondsPerDivision,
408
+ channels
409
+ };
410
+ }
411
+ enqueue(operation) {
412
+ const result = this.operation.then(operation);
413
+ this.operation = result.then(
414
+ () => void 0,
415
+ () => void 0
416
+ );
417
+ return result;
418
+ }
419
+ };
420
+ function toError(error) {
421
+ return error instanceof Error ? error : new Error(String(error));
422
+ }
423
+
424
+ // src/analysis/i2c.ts
425
+ var MAX_SAMPLE_INTERVAL_RATIO = 1e-6;
426
+ function decodeI2c(waveforms, options) {
427
+ if (options.sclChannel === options.sdaChannel) {
428
+ throw new Error("SCL and SDA must use different channels");
429
+ }
430
+ const scl = findWaveform(waveforms, options.sclChannel);
431
+ const sda = findWaveform(waveforms, options.sdaChannel);
432
+ if (scl.samples.length !== sda.samples.length) {
433
+ throw new Error("I2C channels must have the same number of samples");
434
+ }
435
+ if (!Number.isFinite(scl.xIncrement) || scl.xIncrement <= 0 || !Number.isFinite(sda.xIncrement) || sda.xIncrement <= 0) {
436
+ throw new Error("I2C channels must have a positive finite sample interval");
437
+ }
438
+ const scale = Math.max(Math.abs(scl.xIncrement), Math.abs(sda.xIncrement));
439
+ if (Math.abs(scl.xIncrement - sda.xIncrement) > scale * MAX_SAMPLE_INTERVAL_RATIO) {
440
+ throw new Error("I2C channels must have the same sample interval");
441
+ }
442
+ const sclStartTime = scl.xZero - scl.pointOffset * scl.xIncrement;
443
+ const sdaStartTime = sda.xZero - sda.pointOffset * sda.xIncrement;
444
+ if (Math.abs(sclStartTime - sdaStartTime) > scale * MAX_SAMPLE_INTERVAL_RATIO) {
445
+ throw new Error("I2C channels must start at the same sample time");
446
+ }
447
+ const threshold = options.thresholdVolts ?? 1.5;
448
+ if (!Number.isFinite(threshold)) throw new Error("I2C threshold must be finite");
449
+ const events = [];
450
+ let active = false;
451
+ let firstByte = true;
452
+ let shiftRegister = 0;
453
+ let bitCount = 0;
454
+ let byteTime = 0;
455
+ let previousScl = levelAt(scl.samples[0] ?? 0, threshold);
456
+ let previousSda = levelAt(sda.samples[0] ?? 0, threshold);
457
+ for (let index = 1; index < scl.samples.length; index += 1) {
458
+ const sclValue = scl.samples[index];
459
+ const sdaValue = sda.samples[index];
460
+ if (!Number.isFinite(sclValue) || !Number.isFinite(sdaValue)) {
461
+ throw new Error(`I2C sample ${index} contains a non-finite voltage`);
462
+ }
463
+ const sclHigh = levelAt(sclValue, threshold);
464
+ const sdaHigh = levelAt(sdaValue, threshold);
465
+ const time = scl.xZero + (index - scl.pointOffset) * scl.xIncrement;
466
+ if (previousScl && previousSda !== sdaHigh) {
467
+ if (sdaHigh) {
468
+ if (active) events.push({ kind: "stop", time });
469
+ active = false;
470
+ } else {
471
+ events.push({ kind: active ? "repeated-start" : "start", time });
472
+ active = true;
473
+ firstByte = true;
474
+ bitCount = 0;
475
+ shiftRegister = 0;
476
+ byteTime = time;
477
+ }
478
+ }
479
+ if (active && !previousScl && sclHigh) {
480
+ if (bitCount === 0) byteTime = time;
481
+ if (bitCount < 8) {
482
+ shiftRegister = shiftRegister << 1 | Number(sdaHigh);
483
+ bitCount += 1;
484
+ } else {
485
+ if (firstByte) {
486
+ events.push({
487
+ kind: "address",
488
+ time: byteTime,
489
+ byte: shiftRegister,
490
+ address: shiftRegister >> 1,
491
+ direction: (shiftRegister & 1) === 0 ? "write" : "read",
492
+ acknowledged: !sdaHigh
493
+ });
494
+ firstByte = false;
495
+ } else {
496
+ events.push({
497
+ kind: "data",
498
+ time: byteTime,
499
+ byte: shiftRegister,
500
+ acknowledged: !sdaHigh
501
+ });
502
+ }
503
+ bitCount = 0;
504
+ shiftRegister = 0;
505
+ }
506
+ }
507
+ previousScl = sclHigh;
508
+ previousSda = sdaHigh;
509
+ }
510
+ return events;
511
+ }
512
+ function findWaveform(waveforms, channel) {
513
+ const waveform = waveforms.find((candidate) => candidate.channel === channel);
514
+ if (!waveform) throw new Error(`No waveform data for ${channel}`);
515
+ return waveform;
516
+ }
517
+ function levelAt(volts, threshold) {
518
+ return volts >= threshold;
519
+ }
520
+ export {
521
+ Tbs2204bDriver,
522
+ decodeI2c
523
+ };
package/package.json CHANGED
@@ -1,6 +1,33 @@
1
- {
2
- "name": "@elkamarado/remote-oscilloscope-tbs2204b-driver",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "@elkamarado/remote-oscilloscope-tbs2204b-driver",
3
+ "version": "0.2.0",
4
+ "description": "Typed SCPI waveform acquisition and I2C decoding for the Tektronix TBS2204B",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "README.md",
18
+ "LICENSE"
19
+ ],
20
+ "scripts": {
21
+ "build": "tsup src/index.ts --format esm --dts",
22
+ "test": "tsx --test src/analysis/i2c.test.ts src/driver.test.ts"
23
+ },
24
+ "engines": {
25
+ "node": ">=20"
26
+ },
27
+ "devDependencies": {
28
+ "@types/node": "^22.0.0",
29
+ "tsup": "^8.5.0",
30
+ "tsx": "^4.19.0",
31
+ "typescript": "^5.7.0"
32
+ }
33
+ }