カスタムのWeb UI
ワークスペースのアプリの画面は、HTMLとJavaScriptで書きます。エンジンが/appで配信し、画面はWebSocketで計算グラフの入出力ポートとやり取りします。このページでは、ノードとプラグインを書くで追加したGainとCounterを、画面から操作します。
置き場所
テンプレートを--vnfで指定して起動したエンジンは、templates/default/flows/default.vnf/app/のファイルをhttp://localhost:8000/app/の下で配信します。テンプレートのindex.htmlが、はじめにで開いたSignal Labです。
同じフォルダのnonoha-client.iife.jsは、エンジンとやり取りするクライアント(nonoha-client-js)を、<script>タグで読み込める1つのファイルにまとめたものです。
計算グラフの入出力ポート
画面がやり取りするのは、グラフ自身の入出力ポート(graph.jsonのinputsとoutputs)です。Counterをつないだ出力ポートcountに加えて、Gainの係数を画面から変更できるように、入力ポートgainを追加し、Gainのプロパティポート@gainにつなぎます。エンジンを止めてから、templates/default/flows/default.vnf/graphs/app.vng/graph.jsonに次を追加します。
"inputs": { "gain": { "types": ["f64"] } },
"edges": [{ "source": ".gain", "target": "Gain_1.@gain" }]ここに書いたのは追加する部分だけで、既存のinputsとedgesはそのまま残します。
ページを書く
templates/default/flows/default.vnf/app/gain.htmlを作成します。
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Gain</title>
<p>Count: <output id="count">-</output></p>
<p>Peak: <output id="peak">-</output></p>
<label>Gain <input id="gain" type="range" min="0" max="1" step="0.01" value="0.5"></label>
<script src="nonoha-client.iife.js"></script>
<script>
const client = new NonohaClient.GraphClient(location.host, "app")
// Each output of the graph arrives here, by its name
client.addOutputCallback(({ portName, values }) => {
const array = values[0].array // a typed array, reused for the next output
if (portName === "count") document.getElementById("count").textContent = array[0]
if (portName === "waveform") document.getElementById("peak").textContent = Math.max(...array).toFixed(2)
})
client.connect()
// Send a value to an input of the graph
const send = (portName, dataType, array) =>
client.dispatchInput({ portName, values: [{ dataType, shape: [1], array }] })
// The socket opens a moment after connect(): try until it takes the value
function start() {
try {
send("enabled", NonohaClient.PortDataType.Bool, new Uint8Array([1]))
} catch {
setTimeout(start, 200)
}
}
start()
document.getElementById("gain").addEventListener("input", (event) => {
send("gain", NonohaClient.PortDataType.Float64, new Float64Array([Number(event.target.value)]))
})
</script>
</html>new NonohaClient.GraphClient(location.host, "app")は、このページを配信したエンジンのappグラフに接続します。addOutputCallbackに渡した関数は、グラフの出力が届くたびに呼ばれます。values[0].arrayは型付き配列(Float32Arrayなど)で、次の出力で再利用されることがあります。値を保持するときはコピーします。dispatchInputは、グラフの入力ポートに値を送ります。dataTypeは入力ポートのデータ型、arrayは値です。shapeは先頭がバッチ次元で、1つの値なら[1]、f32[3]の入力ポートなら[1, 3]です。connect()のあと、WebSocketが開くまで少し時間がかかり、その間のdispatchInputは例外になります。テンプレートと同じく、送信に成功するまで送り直します。- Clockは、入力ポート
enabledにtrueが届くまで動きません。
エンジンを起動し直してhttp://localhost:8000/app/gain.htmlを開くと、Countが増えていき、Peakに波形の最大値が表示されます。スライダーを0.2にすると、Peakも0.20になります。
ほかのマシンから開く
エンジンは既定では、自分のマシンからの接続だけを受け付けます。同じネットワークのタブレットなどから開くときは、--host 0.0.0.0を付けて起動します。エンジンのAPIには認証がないので、信頼できるネットワークの中だけで使います(安全に使うために)。
次に読む
- 計算グラフの出力を描画する例として、テンプレートの
index.htmlがあります(Canvasで波形とスペクトルを描画します)。 - WebSocket APIとREST APIの詳細は、nonoha-engineのAPIリファレンスにあります。