nmrlink 0.0.0-stage → 0.1.1
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 +24 -0
- package/README.md +132 -2
- package/package.json +39 -4
- package/src/analysis.js +14 -0
- package/src/baseline.js +31 -0
- package/src/browser.js +93 -0
- package/src/controller.js +119 -0
- package/src/device.js +132 -0
- package/src/fft.js +100 -0
- package/src/frequency-record.js +40 -0
- package/src/frequency-sweep.js +30 -0
- package/src/graphs.js +235 -0
- package/src/index.js +30 -0
- package/src/line-decoder.js +56 -0
- package/src/protocol.js +107 -0
- package/src/pulse-fit.js +86 -0
- package/src/pulse-record.js +50 -0
- package/src/pulse-sweep.js +40 -0
- package/src/record.js +40 -0
- package/src/relaxation-fit.js +69 -0
- package/src/sample-validation.js +13 -0
- package/src/signed-signal.js +83 -0
- package/src/sweep.js +32 -0
- package/src/t1-record.js +42 -0
- package/src/t1-sweep.js +66 -0
- package/src/t2-record.js +41 -0
- package/src/t2-sweep.js +80 -0
- package/src/timing.js +9 -0
- package/src/web-serial-transport.js +144 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Masamitsu Bando
|
|
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. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
22
|
+
|
|
23
|
+
Scope: The original/ directory is excluded from this license; its license
|
|
24
|
+
has not been determined. Third-party materials retain their own licenses.
|
package/README.md
CHANGED
|
@@ -1,3 +1,133 @@
|
|
|
1
|
-
#
|
|
1
|
+
# nmrlink
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
教育用NMR装置の制御・波形解析・グラフを自分のWeb UIへ組み込むJavaScriptライブラリです。Web Serial APIによる接続、Single/Double測定、FID・FFT、周波数走査、パルス校正、T1・T2測定に対応します。
|
|
4
|
+
|
|
5
|
+
[ドキュメント](https://masabando.github.io/nmrlink/) · [API](https://masabando.github.io/nmrlink/docs/API.html) · [標準Web UI](https://masabando.github.io/nmrlink/examples/standard/) · [GitHub](https://github.com/masabando/nmrlink)
|
|
6
|
+
|
|
7
|
+
## 導入
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install nmrlink
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
GitHubリポジトリからソースを直接使うこともできます。ローカルで配布用アーカイブを作る場合は、リポジトリのルートで次を実行します。
|
|
14
|
+
|
|
15
|
+
```sh
|
|
16
|
+
npm pack --workspace nmrlink --ignore-scripts
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
作成された `nmrlink-0.1.1.tgz` を別プロジェクトへインストールできます。
|
|
20
|
+
|
|
21
|
+
```sh
|
|
22
|
+
npm install /path/to/nmrlink-0.1.1.tgz
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## 対応環境と配布内容
|
|
26
|
+
|
|
27
|
+
- 実機の直接接続にはWeb Serial対応デスクトップブラウザとHTTPSまたは同じPCのlocalhostが必要です。接続する装置はNMRLinkの通信仕様に対応している必要があります。
|
|
28
|
+
- ES modules形式のJavaScriptを提供します。CommonJS形式とTypeScript型定義は含みません。
|
|
29
|
+
- ライブラリ自体の実行時依存パッケージはありません。Node.jsから解析やSVG生成を使う場合にDOMは不要です。
|
|
30
|
+
- パッケージには読みやすい `src/`、このREADME、MITライセンスを含みます。ソースは圧縮・難読化していません。
|
|
31
|
+
|
|
32
|
+
ブラウザアプリのViteなどのバンドラー環境ではパッケージ名でimportします。素のHTMLではimport mapか、ソースへの相対URLが必要です。[ビルドなしで使う方法](https://masabando.github.io/nmrlink/guide/install.html)も参照してください。
|
|
33
|
+
|
|
34
|
+
## 自分のWeb UIから測定する
|
|
35
|
+
|
|
36
|
+
次の例はバンドラー環境のブラウザ用コードです。HTMLに接続・測定・切断・保存ボタン、状態欄、2つのグラフ表示先を用意します。
|
|
37
|
+
|
|
38
|
+
```html
|
|
39
|
+
<button id="connect">接続</button>
|
|
40
|
+
<button id="measure" disabled>測定</button>
|
|
41
|
+
<button id="disconnect" disabled>切断</button>
|
|
42
|
+
<button id="save" disabled>生データJSONを保存</button>
|
|
43
|
+
<p id="status" role="status">未接続</p>
|
|
44
|
+
<div id="fid"></div>
|
|
45
|
+
<div id="fft"></div>
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
```js
|
|
49
|
+
import { NMRController, analyzeMeasurement } from "nmrlink";
|
|
50
|
+
import { NMRGraphs } from "nmrlink/graphs";
|
|
51
|
+
import { saveMeasurement } from "nmrlink/browser";
|
|
52
|
+
|
|
53
|
+
const get = id => document.getElementById(id);
|
|
54
|
+
const controller = new NMRController();
|
|
55
|
+
const graphs = new NMRGraphs({ fid: get("fid"), fft: get("fft") });
|
|
56
|
+
|
|
57
|
+
// 装置・試料に合わせて確認する値です。校正済みの値へ変更してください。
|
|
58
|
+
const parameters = {
|
|
59
|
+
frequencyHz: 402000,
|
|
60
|
+
pulse1Cycles: 21, phase1Degrees: 0,
|
|
61
|
+
pulse2Cycles: 42, phase2Degrees: 90,
|
|
62
|
+
pulseIntervalMs: 5, measurementIntervalMs: 200, scans: 128,
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
controller.onStateChange(state => {
|
|
66
|
+
get("connect").disabled = !state.canConnect;
|
|
67
|
+
get("measure").disabled = !state.canMeasure;
|
|
68
|
+
get("disconnect").disabled = !state.canDisconnect;
|
|
69
|
+
});
|
|
70
|
+
controller.onError(error => { get("status").textContent = error.message; });
|
|
71
|
+
controller.onResult(record => {
|
|
72
|
+
get("save").disabled = false;
|
|
73
|
+
try {
|
|
74
|
+
graphs.show(record, analyzeMeasurement(record));
|
|
75
|
+
get("status").textContent = "測定が完了しました。";
|
|
76
|
+
} catch (error) {
|
|
77
|
+
graphs.clear();
|
|
78
|
+
get("status").textContent = `解析できませんでした:${error.message}`;
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
// ポート選択はクリックから直接呼び出します。
|
|
83
|
+
get("connect").onclick = () => controller.connect();
|
|
84
|
+
get("measure").onclick = () => controller.measure(parameters, { mode: "single" });
|
|
85
|
+
get("disconnect").onclick = () => controller.disconnect();
|
|
86
|
+
get("save").onclick = () => {
|
|
87
|
+
if (controller.result) saveMeasurement(controller.result);
|
|
88
|
+
};
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
接続・測定のエラーは `onError` に通知され、操作は `{ ok, value, error }` を返します。低水準の `NMRDevice` はエラー時にrejectします。測定の自動再送や進行中の測定の即時停止は行いません。画面を破棄するときは、処理完了後に切断し、`graphs.dispose()` と `controller.dispose()` で監視を終了します。
|
|
92
|
+
|
|
93
|
+
## 実機なしで解析する
|
|
94
|
+
|
|
95
|
+
Node.jsまたはブラウザで実行できます。2チャンネルを複素信号として解析します。
|
|
96
|
+
|
|
97
|
+
```js
|
|
98
|
+
import { analyzeMeasurement } from "nmrlink";
|
|
99
|
+
import { createRecordPlots } from "nmrlink/graphs";
|
|
100
|
+
|
|
101
|
+
const record = {
|
|
102
|
+
source: "demo", acquiredAt: new Date().toISOString(),
|
|
103
|
+
mode: "single", parameters: null, points: 2048, sampleIntervalMs: 0.02,
|
|
104
|
+
raw: Array.from({ length: 2048 }, (_, index) => {
|
|
105
|
+
const t = index * 0.00002;
|
|
106
|
+
const amplitude = 1000 * Math.exp(-t / 0.003);
|
|
107
|
+
return [
|
|
108
|
+
amplitude * Math.cos(2 * Math.PI * 1200 * t),
|
|
109
|
+
amplitude * Math.sin(2 * Math.PI * 1200 * t),
|
|
110
|
+
];
|
|
111
|
+
}),
|
|
112
|
+
};
|
|
113
|
+
const analysis = analyzeMeasurement(record, { startMs: 1, endMs: 5 });
|
|
114
|
+
console.log(analysis.peak.hz); // 受信周波数からの差 [Hz]。FFTビン値。
|
|
115
|
+
const svg = createRecordPlots(record); // { fid, fft, ... }
|
|
116
|
+
console.log(svg.fid); // SVG文字列。Node.jsでも生成できます。
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
## import先
|
|
120
|
+
|
|
121
|
+
| 入口 | 主な機能 |
|
|
122
|
+
| --- | --- |
|
|
123
|
+
| `nmrlink` | NMRDevice、NMRController、条件検証、補正・FFT、走査、T1/T2解析、保存JSONの解析 |
|
|
124
|
+
| `nmrlink/graphs` | NMRGraphs、createRecordPlots、周波数・パルス・T1/T2のSVG生成 |
|
|
125
|
+
| `nmrlink/browser` | JSON・PNGの保存、測定JSONの読み込み、JSTファイル名の日時書式 |
|
|
126
|
+
|
|
127
|
+
[グラフの表示例とコピー用コード](https://masabando.github.io/nmrlink/guide/frequencygraph.html)や[APIリファレンス](https://masabando.github.io/nmrlink/docs/API.html)から用途別に確認できます。
|
|
128
|
+
|
|
129
|
+
## ライセンス
|
|
130
|
+
|
|
131
|
+
MIT。作者:Masamitsu Bando。配布物内のLICENSEを参照してください。
|
|
132
|
+
|
|
133
|
+
GitHubの `original/` にある提供元のPythonプログラムはこのnpmパッケージに含めず、NMRLinkのMITライセンスの対象外です。
|
package/package.json
CHANGED
|
@@ -1,6 +1,41 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nmrlink",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "JavaScript library for educational NMR hardware control via Web Serial, signal analysis, and SVG graphs.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"nmr",
|
|
8
|
+
"web-serial",
|
|
9
|
+
"javascript",
|
|
10
|
+
"hardware",
|
|
11
|
+
"fft"
|
|
12
|
+
],
|
|
13
|
+
"scripts": {
|
|
14
|
+
"test": "node --test tests/*.test.js"
|
|
15
|
+
},
|
|
16
|
+
"exports": {
|
|
17
|
+
".": "./src/index.js",
|
|
18
|
+
"./graphs": "./src/graphs.js",
|
|
19
|
+
"./browser": "./src/browser.js"
|
|
20
|
+
},
|
|
21
|
+
"license": "MIT",
|
|
22
|
+
"author": {
|
|
23
|
+
"name": "Masamitsu Bando",
|
|
24
|
+
"url": "https://alice.helixcode.net/~bando/"
|
|
25
|
+
},
|
|
26
|
+
"homepage": "https://masabando.github.io/nmrlink/",
|
|
27
|
+
"repository": {
|
|
28
|
+
"type": "git",
|
|
29
|
+
"url": "git+https://github.com/masabando/nmrlink.git",
|
|
30
|
+
"directory": "packages/nmrlink"
|
|
31
|
+
},
|
|
32
|
+
"bugs": {
|
|
33
|
+
"url": "https://github.com/masabando/nmrlink/issues"
|
|
34
|
+
},
|
|
35
|
+
"files": [
|
|
36
|
+
"src/",
|
|
37
|
+
"README.md",
|
|
38
|
+
"LICENSE"
|
|
39
|
+
],
|
|
40
|
+
"main": "./src/index.js"
|
|
41
|
+
}
|
package/src/analysis.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { correctBaseline } from "./baseline.js";
|
|
2
|
+
import { computeSpectrum } from "./fft.js";
|
|
3
|
+
|
|
4
|
+
/** Common analysis pipeline. The acquired record is never modified. */
|
|
5
|
+
export function analyzeMeasurement(record, {
|
|
6
|
+
startMs = 1, endMs = 5, tailPoints = 100, truncate = true, window = "hann",
|
|
7
|
+
} = {}) {
|
|
8
|
+
const baseline = correctBaseline(record.raw, { tailPoints, truncate });
|
|
9
|
+
const spectrum = computeSpectrum(baseline.data, {
|
|
10
|
+
sampleIntervalMs: record.sampleIntervalMs, startMs, endMs, window,
|
|
11
|
+
});
|
|
12
|
+
const peak = spectrum.bins.reduce((maximum, bin) => bin.amplitude > maximum.amplitude ? bin : maximum);
|
|
13
|
+
return { data: baseline.data, baseline, spectrum, peak };
|
|
14
|
+
}
|
package/src/baseline.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { validateSamples } from "./sample-validation.js";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Subtract each channel's tail mean, preserving the input array.
|
|
5
|
+
* Defaults match the PoC: last 100 samples and Python int-style truncation.
|
|
6
|
+
* tailPoints is a sample count, not a duration in milliseconds.
|
|
7
|
+
*/
|
|
8
|
+
export function correctBaseline(raw, { tailPoints = 100, truncate = true } = {}) {
|
|
9
|
+
validateSamples(raw);
|
|
10
|
+
if (!Number.isSafeInteger(tailPoints) || tailPoints < 1 || tailPoints > raw.length) {
|
|
11
|
+
throw new RangeError("tailPoints must be an integer from 1 to the sample count.");
|
|
12
|
+
}
|
|
13
|
+
if (typeof truncate !== "boolean") throw new TypeError("truncate must be boolean.");
|
|
14
|
+
|
|
15
|
+
const base = [0, 0];
|
|
16
|
+
for (let channel = 0; channel < 2; channel++) {
|
|
17
|
+
let sum = 0;
|
|
18
|
+
for (let index = raw.length - tailPoints; index < raw.length; index++) {
|
|
19
|
+
sum += raw[index][channel];
|
|
20
|
+
}
|
|
21
|
+
base[channel] = sum / tailPoints;
|
|
22
|
+
if (!Number.isFinite(base[channel])) throw new RangeError("Baseline calculation overflowed.");
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const data = raw.map(pair => pair.map((value, channel) => {
|
|
26
|
+
const corrected = value - base[channel];
|
|
27
|
+
if (!Number.isFinite(corrected)) throw new RangeError("Baseline correction overflowed.");
|
|
28
|
+
return truncate ? Math.trunc(corrected) : corrected;
|
|
29
|
+
}));
|
|
30
|
+
return { base, data, tailPoints, truncate };
|
|
31
|
+
}
|
package/src/browser.js
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { parseMeasurement, MAX_MEASUREMENT_JSON_BYTES } from "./record.js";
|
|
2
|
+
|
|
3
|
+
/** Format an acquisition instant in Japan time, independent of the browser's timezone. */
|
|
4
|
+
export function formatFileTimestamp(acquiredAt) {
|
|
5
|
+
const date = new Date(acquiredAt);
|
|
6
|
+
if (typeof acquiredAt !== "string" || !Number.isFinite(date.getTime())) {
|
|
7
|
+
throw new TypeError("ファイル名に使う取得日時が正しくありません。");
|
|
8
|
+
}
|
|
9
|
+
const formatter = new Intl.DateTimeFormat("en-GB", {
|
|
10
|
+
timeZone: "Asia/Tokyo", year: "numeric", month: "2-digit", day: "2-digit",
|
|
11
|
+
hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23",
|
|
12
|
+
});
|
|
13
|
+
const parts = Object.fromEntries(formatter.formatToParts(date).map(part => [part.type, part.value]));
|
|
14
|
+
const milliseconds = String(date.getUTCMilliseconds()).padStart(3, "0");
|
|
15
|
+
return `${parts.year}-${parts.month}-${parts.day}_${parts.hour}-${parts.minute}-${parts.second}-${milliseconds}_JST`;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Download an unmodified record as readable JSON. Browser-only utility. */
|
|
19
|
+
export function saveMeasurement(record) {
|
|
20
|
+
if (!record) throw new TypeError("A measurement record is required.");
|
|
21
|
+
const blob = new Blob([JSON.stringify(record, null, 2) + "\n"], { type: "application/json" });
|
|
22
|
+
const url = URL.createObjectURL(blob);
|
|
23
|
+
const link = document.createElement("a");
|
|
24
|
+
link.href = url;
|
|
25
|
+
link.download = `nmrlink-${formatFileTimestamp(record.acquiredAt)}.json`;
|
|
26
|
+
link.click();
|
|
27
|
+
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Save an NMRGraphs SVG as an opaque PNG, at twice its SVG resolution by default. */
|
|
31
|
+
export async function saveGraphPng(svg, { filename = "nmrlink-graph.png", scale = 2 } = {}) {
|
|
32
|
+
if (svg?.localName !== "svg" || svg.namespaceURI !== "http://www.w3.org/2000/svg") {
|
|
33
|
+
throw new TypeError("An SVG graph element is required.");
|
|
34
|
+
}
|
|
35
|
+
if (!Number.isFinite(scale) || scale <= 0 || scale > 4) {
|
|
36
|
+
throw new RangeError("PNG scale must be greater than zero and at most 4.");
|
|
37
|
+
}
|
|
38
|
+
const bounds = svg.viewBox.baseVal;
|
|
39
|
+
const width = Math.round(bounds.width * scale);
|
|
40
|
+
const height = Math.round(bounds.height * scale);
|
|
41
|
+
if (width < 1 || height < 1 || width > 8192 || height > 8192 || width * height > 16777216) {
|
|
42
|
+
throw new RangeError("PNG dimensions must be positive and within 8192 pixels and 16 megapixels.");
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Snapshot the current plot before awaiting image decoding or any later UI updates.
|
|
46
|
+
const copy = svg.cloneNode(true);
|
|
47
|
+
copy.setAttribute("width", String(width));
|
|
48
|
+
copy.setAttribute("height", String(height));
|
|
49
|
+
copy.style.fontFamily = getComputedStyle(svg).fontFamily;
|
|
50
|
+
const source = new Blob([new XMLSerializer().serializeToString(copy)], { type: "image/svg+xml;charset=utf-8" });
|
|
51
|
+
const sourceUrl = URL.createObjectURL(source);
|
|
52
|
+
let png;
|
|
53
|
+
try {
|
|
54
|
+
const image = new Image();
|
|
55
|
+
await new Promise((resolve, reject) => {
|
|
56
|
+
image.onload = resolve;
|
|
57
|
+
image.onerror = () => reject(new Error("グラフ画像を読み込めませんでした。"));
|
|
58
|
+
image.src = sourceUrl;
|
|
59
|
+
});
|
|
60
|
+
const canvas = document.createElement("canvas");
|
|
61
|
+
canvas.width = width;
|
|
62
|
+
canvas.height = height;
|
|
63
|
+
const context = canvas.getContext("2d");
|
|
64
|
+
if (!context) throw new Error("PNG保存に必要なCanvasを利用できません。");
|
|
65
|
+
context.fillStyle = "#ffffff";
|
|
66
|
+
context.fillRect(0, 0, width, height);
|
|
67
|
+
context.drawImage(image, 0, 0, width, height);
|
|
68
|
+
png = await new Promise((resolve, reject) => canvas.toBlob(
|
|
69
|
+
blob => blob ? resolve(blob) : reject(new Error("PNG画像を生成できませんでした。")), "image/png",
|
|
70
|
+
));
|
|
71
|
+
} finally {
|
|
72
|
+
URL.revokeObjectURL(sourceUrl);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const url = URL.createObjectURL(png);
|
|
76
|
+
try {
|
|
77
|
+
const link = document.createElement("a");
|
|
78
|
+
link.href = url;
|
|
79
|
+
link.download = filename;
|
|
80
|
+
link.click();
|
|
81
|
+
} finally {
|
|
82
|
+
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** Read a local file only; parsing never opens a serial port or sends a command. */
|
|
87
|
+
export async function readMeasurement(file) {
|
|
88
|
+
if (!file || typeof file.text !== "function" || !Number.isFinite(file.size)) {
|
|
89
|
+
throw new TypeError("測定JSONファイルを指定してください。");
|
|
90
|
+
}
|
|
91
|
+
if (file.size > MAX_MEASUREMENT_JSON_BYTES) throw new RangeError("測定JSONは2 MiB以下のファイルを指定してください。");
|
|
92
|
+
return parseMeasurement(await file.text());
|
|
93
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { NMRDevice } from "./device.js";
|
|
2
|
+
import { runFrequencySweep } from "./frequency-sweep.js";
|
|
3
|
+
import { runT2Sweep } from "./t2-sweep.js";
|
|
4
|
+
import { runT1Sweep } from "./t1-sweep.js";
|
|
5
|
+
import { runPulseSweep } from "./pulse-sweep.js";
|
|
6
|
+
|
|
7
|
+
/** UI-independent operation lifecycle. Commands report errors rather than reject. */
|
|
8
|
+
export class NMRController {
|
|
9
|
+
constructor({ device = new NMRDevice() } = {}) {
|
|
10
|
+
this.device = device;
|
|
11
|
+
this.result = null;
|
|
12
|
+
this.operation = null;
|
|
13
|
+
this.disposed = false;
|
|
14
|
+
this.listeners = { state: new Set(), result: new Set(), error: new Set() };
|
|
15
|
+
// Transports currently have no shared event contract for an idle USB loss.
|
|
16
|
+
this.timer = setInterval(() => this.emitState(), 500);
|
|
17
|
+
this.timer.unref?.();
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
get state() {
|
|
21
|
+
const connected = this.device.state === "connected";
|
|
22
|
+
const busy = this.operation !== null;
|
|
23
|
+
return {
|
|
24
|
+
connection: this.device.state, operation: this.operation, busy,
|
|
25
|
+
canConnect: !this.disposed && !busy && this.device.state === "disconnected",
|
|
26
|
+
canDisconnect: !this.disposed && !busy && connected,
|
|
27
|
+
canMeasure: !this.disposed && !busy && connected,
|
|
28
|
+
hasResult: this.result !== null,
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
subscribe(type, callback) {
|
|
33
|
+
if (this.disposed) throw new Error("Controller is disposed.");
|
|
34
|
+
this.listeners[type].add(callback);
|
|
35
|
+
return () => this.listeners[type].delete(callback);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
onStateChange(callback) {
|
|
39
|
+
const unsubscribe = this.subscribe("state", callback);
|
|
40
|
+
callback(this.state);
|
|
41
|
+
return unsubscribe;
|
|
42
|
+
}
|
|
43
|
+
onResult(callback) { return this.subscribe("result", callback); }
|
|
44
|
+
onError(callback) { return this.subscribe("error", callback); }
|
|
45
|
+
|
|
46
|
+
emit(type, value) {
|
|
47
|
+
for (const listener of this.listeners[type]) {
|
|
48
|
+
try { listener(value); }
|
|
49
|
+
catch (error) {
|
|
50
|
+
// A UI/analysis error must not invalidate a successful hardware operation.
|
|
51
|
+
if (type !== "error") this.emit("error", error);
|
|
52
|
+
else console.error(error);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
emitState() {
|
|
58
|
+
const state = this.state;
|
|
59
|
+
const signature = JSON.stringify(state);
|
|
60
|
+
if (signature !== this.previousState) {
|
|
61
|
+
this.previousState = signature;
|
|
62
|
+
this.emit("state", state);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async run(operation, action) {
|
|
67
|
+
if (this.disposed || this.operation) {
|
|
68
|
+
const error = new Error("Controller is disposed or another operation is running.");
|
|
69
|
+
this.emit("error", error);
|
|
70
|
+
return { ok: false, error };
|
|
71
|
+
}
|
|
72
|
+
this.operation = operation;
|
|
73
|
+
this.emitState();
|
|
74
|
+
try {
|
|
75
|
+
// No asynchronous work precedes action: connect retains the user's gesture.
|
|
76
|
+
const value = await action();
|
|
77
|
+
if (operation === "measure") {
|
|
78
|
+
this.result = value;
|
|
79
|
+
this.emit("result", value);
|
|
80
|
+
}
|
|
81
|
+
return { ok: true, value };
|
|
82
|
+
} catch (error) {
|
|
83
|
+
this.emit("error", error);
|
|
84
|
+
return { ok: false, error };
|
|
85
|
+
} finally {
|
|
86
|
+
this.operation = null;
|
|
87
|
+
this.emitState();
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
connect() { return this.run("connect", () => this.device.connect()); }
|
|
92
|
+
disconnect() { return this.run("disconnect", () => this.device.disconnect()); }
|
|
93
|
+
measure(parameters, options) { return this.run("measure", () => this.device.measure(parameters, options)); }
|
|
94
|
+
|
|
95
|
+
sweep(parameters, options = {}) { return this.scan(runFrequencySweep, parameters, options); }
|
|
96
|
+
pulseSweep(parameters, options = {}) { return this.scan(runPulseSweep, parameters, options); }
|
|
97
|
+
|
|
98
|
+
t2Sweep(parameters, options = {}) { return this.scan(runT2Sweep, parameters, options); }
|
|
99
|
+
|
|
100
|
+
t1Sweep(parameters, options = {}) { return this.scan(runT1Sweep, parameters, options); }
|
|
101
|
+
|
|
102
|
+
scan(runner, parameters, options) {
|
|
103
|
+
return this.run("sweep", () => runner(this.device, parameters, {
|
|
104
|
+
...options,
|
|
105
|
+
onPoint: async (point, completed, total) => {
|
|
106
|
+
this.result = point.record;
|
|
107
|
+
if (options.onPoint) await options.onPoint(point, completed, total);
|
|
108
|
+
},
|
|
109
|
+
}));
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Stop UI monitoring only; never stop or disconnect the hardware implicitly. */
|
|
113
|
+
dispose() {
|
|
114
|
+
if (this.operation) throw new Error("Wait for the current operation before disposing.");
|
|
115
|
+
clearInterval(this.timer);
|
|
116
|
+
this.disposed = true;
|
|
117
|
+
for (const listeners of Object.values(this.listeners)) listeners.clear();
|
|
118
|
+
}
|
|
119
|
+
}
|
package/src/device.js
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { encodeCommand, encodeParameters, validateParameters, parseSampleLine,
|
|
2
|
+
SAMPLE_COUNT, SAMPLE_INTERVAL_MS } from "./protocol.js";
|
|
3
|
+
import { measurementDurationMs } from "./timing.js";
|
|
4
|
+
import { WebSerialTransport } from "./web-serial-transport.js";
|
|
5
|
+
|
|
6
|
+
const delay = milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds));
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Device protocol shared by browser and Node.js transports.
|
|
10
|
+
* A transport implements connect, disconnect, write, readLine and clearInput.
|
|
11
|
+
* Measurement returns raw samples; baseline correction belongs to analysis.
|
|
12
|
+
*/
|
|
13
|
+
export class NMRDevice {
|
|
14
|
+
constructor({ transport = new WebSerialTransport(), responseTimeoutMs = 5000,
|
|
15
|
+
dataTimeoutMs = 30000, measurementMarginMs = 20000 } = {}) {
|
|
16
|
+
for (const value of [responseTimeoutMs, dataTimeoutMs, measurementMarginMs]) {
|
|
17
|
+
if (!Number.isFinite(value) || value <= 0) throw new RangeError("Timeouts must be positive finite numbers.");
|
|
18
|
+
}
|
|
19
|
+
this.transport = transport;
|
|
20
|
+
this.responseTimeoutMs = responseTimeoutMs;
|
|
21
|
+
this.dataTimeoutMs = dataTimeoutMs;
|
|
22
|
+
this.measurementMarginMs = measurementMarginMs;
|
|
23
|
+
this.state = "disconnected";
|
|
24
|
+
this.busy = false;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
get state() {
|
|
28
|
+
if (this.currentState === "connected" &&
|
|
29
|
+
["disconnected", "disconnecting"].includes(this.transport.state)) {
|
|
30
|
+
return "disconnected";
|
|
31
|
+
}
|
|
32
|
+
return this.currentState;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
set state(value) { this.currentState = value; }
|
|
36
|
+
|
|
37
|
+
async connect() {
|
|
38
|
+
if (this.busy || this.state !== "disconnected") throw new Error("Device is already active.");
|
|
39
|
+
this.busy = true;
|
|
40
|
+
this.state = "connecting";
|
|
41
|
+
try {
|
|
42
|
+
await this.transport.connect();
|
|
43
|
+
this.state = "connected";
|
|
44
|
+
} catch (error) {
|
|
45
|
+
this.state = "disconnected";
|
|
46
|
+
throw error;
|
|
47
|
+
} finally {
|
|
48
|
+
this.busy = false;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Disconnecting is not a firmware stop command. */
|
|
53
|
+
async disconnect() {
|
|
54
|
+
if (this.busy) throw new Error("Wait for the current operation; disconnect does not stop a measurement.");
|
|
55
|
+
this.busy = true;
|
|
56
|
+
try { await this.transport.disconnect(); }
|
|
57
|
+
finally { this.state = "disconnected"; this.busy = false; }
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Apply settings, acquire once (with scans averaging), and return 2048 raw pairs.
|
|
62
|
+
* @param {import('./protocol.js').MeasurementParameters} input
|
|
63
|
+
* @param {{mode?: 'single'|'double'}} options
|
|
64
|
+
*/
|
|
65
|
+
async measure(input, { mode = "single" } = {}) {
|
|
66
|
+
// Invalid local input must not send commands or invalidate a good connection.
|
|
67
|
+
const parameters = validateParameters(input);
|
|
68
|
+
if (!["single", "double"].includes(mode)) throw new RangeError("Mode must be single or double.");
|
|
69
|
+
if (this.busy) throw new Error("Another device operation is in progress.");
|
|
70
|
+
if (this.state !== "connected") throw new Error("Device is not connected.");
|
|
71
|
+
this.busy = true;
|
|
72
|
+
this.state = "measuring";
|
|
73
|
+
try {
|
|
74
|
+
await this.applyParameters(parameters);
|
|
75
|
+
this.transport.clearInput();
|
|
76
|
+
await this.transport.write(encodeCommand(mode));
|
|
77
|
+
await this.response(this.responseTimeoutMs);
|
|
78
|
+
|
|
79
|
+
const estimateMs = measurementDurationMs(parameters, { mode });
|
|
80
|
+
await this.response(estimateMs + this.measurementMarginMs);
|
|
81
|
+
await delay(50);
|
|
82
|
+
await this.transport.write(encodeCommand("read"));
|
|
83
|
+
|
|
84
|
+
const raw = [];
|
|
85
|
+
const deadline = performance.now() + this.dataTimeoutMs;
|
|
86
|
+
for (let index = 0; index < SAMPLE_COUNT; index++) {
|
|
87
|
+
const remainingMs = deadline - performance.now();
|
|
88
|
+
if (remainingMs <= 0) throw new Error(`Sample transfer timed out at ${index}/${SAMPLE_COUNT}.`);
|
|
89
|
+
const line = await this.transport.readLine(Math.min(remainingMs, this.responseTimeoutMs));
|
|
90
|
+
raw.push(parseSampleLine(line));
|
|
91
|
+
}
|
|
92
|
+
this.state = "connected";
|
|
93
|
+
return {
|
|
94
|
+
source: "instrument",
|
|
95
|
+
acquiredAt: new Date().toISOString(),
|
|
96
|
+
mode,
|
|
97
|
+
parameters,
|
|
98
|
+
sampleIntervalMs: SAMPLE_INTERVAL_MS,
|
|
99
|
+
points: SAMPLE_COUNT,
|
|
100
|
+
raw,
|
|
101
|
+
};
|
|
102
|
+
} catch (error) {
|
|
103
|
+
// After a protocol error, stale responses could otherwise be mistaken for
|
|
104
|
+
// the next operation. Require reconnection rather than retrying commands.
|
|
105
|
+
this.state = "disconnected";
|
|
106
|
+
try { await this.transport.disconnect(); }
|
|
107
|
+
catch (cleanupError) { throw new AggregateError([error, cleanupError], "Measurement and cleanup failed."); }
|
|
108
|
+
throw error;
|
|
109
|
+
} finally {
|
|
110
|
+
this.busy = false;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async applyParameters(parameters) {
|
|
115
|
+
this.transport.clearInput();
|
|
116
|
+
await this.transport.write(encodeCommand("parameters"));
|
|
117
|
+
await delay(50);
|
|
118
|
+
const acknowledgement = await this.response(this.responseTimeoutMs);
|
|
119
|
+
if (!acknowledgement.includes("CMD_P_OK")) throw new Error("Controller did not accept parameter setup.");
|
|
120
|
+
await this.transport.write(encodeParameters(parameters));
|
|
121
|
+
await delay(50);
|
|
122
|
+
await this.response(this.responseTimeoutMs);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async response(timeoutMs) {
|
|
126
|
+
const line = (await this.transport.readLine(timeoutMs)).trim();
|
|
127
|
+
if (!line || /error|fail|reject/i.test(line)) {
|
|
128
|
+
throw new Error(`Invalid controller acknowledgement: ${line}`);
|
|
129
|
+
}
|
|
130
|
+
return line;
|
|
131
|
+
}
|
|
132
|
+
}
|