Skip to content

Connection and measurement API

Import from nmrlink. Use NMRController for UI operation state; use NMRDevice when handling rejecting promises directly or replacing the transport.

On this page

Parameters and validateParameters

validateParameters(input) returns a copy containing only these eight required fields. It does not change the input or convert numeric strings.

FieldMeaningRange
frequencyHzSet frequency [Hz]Integer 1–2147483647
pulse1Cycles / pulse2CyclesFirst / second pulse RF cycle countsInteger 0–32767
phase1Degrees / phase2DegreesPhase [degrees]0 / 90 / 180 / 270
pulseIntervalMsInter-pulse delay [ms]Integer 0–32767
measurementIntervalMsDevice repetition interval setting [ms]Integer 1–32767
scansAcquisition countInteger 1–32767

These are encoding limits, not guaranteed operating settings for your apparatus or sample. Include second-pulse fields even for Single measurements. An invalid object throws TypeError; out-of-range values throw RangeError.

Measurement record

js
const record = {
  source: "instrument", // "demo" for simulated data
  acquiredAt: "2026-10-21T06:00:00.000Z",
  mode: "single", // "single" or "double"
  parameters: { frequencyHz: 402000, pulse1Cycles: 21, phase1Degrees: 0,
    pulse2Cycles: 42, phase2Degrees: 90, pulseIntervalMs: 5,
    measurementIntervalMs: 200, scans: 64 },
  sampleIntervalMs: 0.02,
  points: 2048,
  raw: Array.from({ length: 2048 }, () => [0, 0]),
};

raw holds uncorrected [Data 1, Data 2] pairs. Acquisition does not apply baseline correction or FFT. Retain source and the original samples separately from derived arrays. Display-only demo records may use parameters:null.

NMRController

js
const controller = new NMRController({ device: new NMRDevice() });
// After controller.connect() succeeds from a connect button, run from a measure button.
const result = await controller.measure(parameters, { mode: "single" });
if (result.ok) console.log(result.value);
else console.error(result.error);

Constructor options may be omitted. connect(), disconnect() and measure(parameters, options) resolve with { ok: true, value } or { ok: false, error }. The default measurement mode is single; double is also supported.

MemberContract
stateconnection, operation, busy, canConnect, canDisconnect, canMeasure, hasResult
state.operationconnect / disconnect / measure / sweep / null
resultLast acquired measurement record, or null
onStateChange(callback)Also reports current state immediately; returns an unsubscribe function
onResult(callback)Reports successful Single/Double records; returns an unsubscribe function
onError(callback)Reports operation and notification-listener errors; returns an unsubscribe function
dispose()Releases monitoring and listeners; throws while busy; does not stop or disconnect

Concurrent operations are refused, without queuing or automatic retries. Call connect directly from a user click. Failures retain the last successful record. Scans use onPoint rather than onResult; result becomes the last evaluated point.

NMRDevice

Constructor optionDefaultMeaning
transportnew WebSerialTransport()Communication transport
responseTimeoutMs5000Maximum wait for an ordinary response / one sample line [ms]
dataTimeoutMs30000Maximum total sample transfer time [ms]
measurementMarginMs20000Margin added to the measurement estimate [ms]

Timeouts must be positive finite numbers. connect() and disconnect() return Promise<void>; measure(parameters, options) returns a promise of a measurement record. Failures reject. state is disconnected / connecting / connected / measuring.

Disconnecting during measurement is refused. Invalid local input sends no commands; communication failure attempts disconnection and requires reconnection. A measurement error combined with a cleanup error produces AggregateError. There is no immediate-stop API.

measurementDurationMs

measurementDurationMs(parameters, { mode: 'single' }) returns an estimate in ms. The default mode is single.

js
// Double includes the inter-pulse delay in every acquisition.
const milliseconds = measurementDurationMs(parameters, { mode: "double" });
testimate=⌈nscans(tinterval+40.96+textra)⌉t_{\mathrm{estimate}}=\left\lceil n_{\mathrm{scans}}\left(t_{\mathrm{interval}}+40.96+t_{\mathrm{extra}}\right)\right\rceil

Use scans for the count and measurementIntervalMs for the interval. All time values are in ms. The extra time is pulseIntervalMs for Double and zero for Single. Serial transfer and command overhead are excluded.

Low-level communication helpers

Normally, let NMRDevice handle these. WebSerialTransport implements connect, disconnect, write(bytes), readLine(timeoutMs) and clearInput. LineDecoder splits received bytes into lines with push, finish and reset.

WebSerialTransport defaults serial to navigator.serial. write(Uint8Array) and readLine(timeoutMs) return promises; readLine resolves to one string line. LineDecoder defaults maxLineBytes to 65536; push accepts Uint8Array and returns completed string lines. finish() throws for an incomplete line; reset() discards state. Non-ASCII and oversized lines are refused.

SAMPLE_COUNT=2048, SAMPLE_INTERVAL_MS=0.02 and PARAMETER_BYTES=18. SERIAL_OPTIONS uses 115200 baud, 8 data bits, 1 stop bit, no parity and no flow control. encodeParameters returns an 18-byte Uint8Array; encodeCommand supports parameters / single / double / read; parseSampleLine returns two integers. Invalid input throws.

Guide: Control measurements · API index