07. ベース&マウント プレイグラウンド
デバイスの 単位変換を対話形式で制御し、 configure.basis, configure.preset, configure.mountこれらは、ワイヤプロトコルレベルでどのように連携して動作するかを示しています。対話型フォーカスが「configure」コマンドに留まるよう、水平なベースを維持します。
学習内容:
- 基底順列 設定 (
"XZY"→ Y軸上方向(アプリケーションフレーム)) - プリセット(
arm_front)選択およびそのプリセットが構成する内容を理解する - 回転クォータニオンを使用した実行時のマウントの再定義(キーボード入力に基づく)
- 相互排他ルール:
mountわあpresetのような デバイスの設定 同じブロック内に同時に存在することはできません - 1回限り
configure動作:キーを押すたびに、configureメッセージが正確に1回送信されます - (C++ Glaze)
std::optionalを用いた相互排他的なフィールドモデリング
ワークフロー
- 最初のメッセージを受け取ると セッションプロファイル,
configure.basis: "XZY",configure.preset: arm_frontを送信します。固定床用としてset_cursor_force送信を開始します。 - 各マティックごとにカーソルのY座標を読み取り、
force_y = max(0, (floor_pos - y) * stiffness)を計算して送信します。 - ユーザーがマウント回転キーを押すと
pending_configure = trueに設定します。 - 次のティックで
rotationこの単位クォータニオン(現在のピッチ/ヨーをZ→Xの順で合成したもの)である変換を含むconfigure.mountブロックを構成します。presetは省略します。これら2つのフィールドは、ワイヤ上では相互に排他的です。 - リセットキー(
R)はオーバーライドを解除します。次回のconfigureでは再びpresetを使用します。
パラメータ
| 名前 | デフォルト値 | 用途 |
|---|---|---|
BASIS | "XZY" | 軸の順列— Y軸上方向のアプリケーションフレーム |
DEVICE_PRESET / DEVICE_CONFIG_PRESET | "arm_front" | 名前付きプリセット— 原点はデバイスベース |
FLOOR_POS_Y | 0.0 m | 固定床面(アプリケーションY) |
STIFFNESS | 1000 単位なし | 床のばね定数 |
MOUNT_STEP_DEG | 10° | キー入力ごとの回転角度 |
PRINT_EVERY_MS | 200 | テレメトリー・スロットル |
制御
| キー | 動作 |
|---|---|
W / S | デバイス+X軸(ピッチ)を基準に、マウントを±10°回転させる |
A / D | デバイス+Z軸(ヨー)を基準に、マウントを±10°回転させる |
R | マウントのリセット — プリセットに戻す |
H | コントロールキーの表示 |
Q | 終了 |
mountわあ presetは互いに排他的ですこのサービスは、両方のフィールドを含む デバイスの設定 ブロックを拒否します。ユーザーがマウントを再定義した場合、チュートリアルではその後のすべての configure において presetを省略します。 Rをクリックすると、次のconfigureで presetこれが再び使用され、 mountは除外されます。
C++の変形版は、バックグラウンドのstdinスレッドで行単位の入力を読み取ります(文字を入力するたびにEnterキーを押します)。Pythonはメインの非同期ループで keyboard パッケージを使用してリアルタイムでキー入力をポーリングするため、ENTERキーを押す必要はありません。キーとコマンドは同じです。
読み取り状態フィールド
data.inverse3[i].stateから読み取る値:
cursor_position.y—vec3. 床の貫通量を計算するために使用します。current_cursor_force— テレメトリ用として報告されます。
送信 / 受信
ペイロードの構造は、すべてのバリエーションで同じです。違いは、各バリエーションが互いに排他的であるという点です。 mount / preset ブランチを構成する方法と、入力スレッドがWebSocketスレッドにシグナルを送信する方法です。
- Python
- C++ (nlohmann)
- C++ (Glaze)
単一の非同期ループ内で keyboard パッケージを使用して、リアルタイムのキー入力をポーリングします。 pending_configureは、キーハンドラによって設定されるグローバルフラグであり、 configure ブロックが送信されるたびに初期化されます。
async with websockets.connect(URI) as websocket:
while True:
msg = await websocket.recv()
data = json.loads(msg)
if first_message:
first_message = False
device_id = data["inverse3"][0]["device_id"]
# Handshake: profile + basis + preset
request_msg = {
"session": {"configure": {"profile": {"name": SLUG}}},
"inverse3": [{
"device_id": device_id,
"configure": build_configure_block(first_handshake=True),
# -> {"basis": {"permutation": "XZY"},
# "preset": {"preset": "arm_front"}}
}],
}
else:
handle_key_inputs() # may set pending_configure = True (classic, not shown)
y = data["inverse3"][0]["state"]["cursor_position"]["y"]
force_y = 0.0 if y > FLOOR_POS_Y else (FLOOR_POS_Y - y) * STIFFNESS
entry = {
"device_id": device_id,
"commands": {"set_cursor_force":
{"vector": {"x": 0.0, "y": force_y, "z": 0.0}}},
}
if pending_configure:
entry["configure"] = build_configure_block(first_handshake=False)
# -> {"mount": {...}} OR {"preset": {...}} (never both)
pending_configure = False
request_msg = {"inverse3": [entry]}
await websocket.send(json.dumps(request_msg))
これは2スレッドモデルです。バックグラウンドのstdinスレッドが行を読み込み、 pending_configure(std::atomic<bool>)を設定すると、libhvのI/Oスレッドが毎ティックこれを確認し、値が設定されている場合に configureを送信します。
std::atomic<bool> pending_configure{false};
ws.onmessage = [&](const std::string &msg) {
const json data = json::parse(msg);
if (!data.contains("inverse3") || data["inverse3"].empty()) return;
const bool do_handshake = first_message;
if (first_message) first_message = false;
const bool do_configure = do_handshake || pending_configure.exchange(false);
json request = {};
if (do_handshake) {
request["session"] = {{"configure", {{"profile",
{{"name", "co.haply.inverse.tutorials:basis-and-mount"}}}}}};
}
request["inverse3"] = json::array();
for (auto &el : data["inverse3"].items()) {
json dev_cmd = {{"device_id", el.value()["device_id"]}};
if (do_configure) {
json cfg = {};
if (do_handshake) cfg["basis"] = {{"permutation", BASIS}};
if (mount_overridden) {
cfg["mount"] = {{"transform", {
{"position", {{"x", 0.0}, {"y", 0.0}, {"z", 0.0}}},
{"rotation", quat_from_xz_deg(mount_angle_x_deg, mount_angle_z_deg)},
{"scale", {{"x", 1.0}, {"y", 1.0}, {"z", 1.0}}},
}}};
} else {
cfg["preset"] = {{"preset", DEVICE_CONFIG_PRESET}};
}
dev_cmd["configure"] = cfg;
}
const float y = el.value()["state"]["cursor_position"]["y"].get<float>();
const float force_y = y > FLOOR_POS_Y ? 0.0f : (FLOOR_POS_Y - y) * STIFFNESS;
dev_cmd["commands"] = {{"set_cursor_force",
{{"vector", {{"x", 0.0}, {"y", force_y}, {"z", 0.0}}}}}};
request["inverse3"].push_back(dev_cmd);
}
ws.send(request.dump());
};
std::thread input_thr(input_thread_func); // stdin reader — flips pending_configure
ws.open("ws://localhost:10001");
while (running.load()) std::this_thread::sleep_for(50ms);
相互排他ルールとは、 std::optional<preset_cfg>わあ std::optional<mount_cfg>と自然に表現されます。値が入力されている側のみが、シリアライズされたJSONに含まれます。プリセット名は enum classとしてモデル化し、 glz::meta 特殊化を使用して、サービスが要求する文字列とマッピングします。
// The preset set modelled as an enum
enum class device_preset {
defaults, arm_front, arm_front_centered,
led_front, led_front_centered, custom,
};
// Glaze meta — serialize the enum as the JSON string the service expects
template <> struct glz::meta<device_preset> {
using enum device_preset;
static constexpr auto value =
enumerate(defaults, arm_front, arm_front_centered,
led_front, led_front_centered, custom);
};
// Transform + the configure block
struct vec3 { float x{}, y{}, z{}; };
struct quat { float w{1.0f}, x{}, y{}, z{}; };
struct transform_t { vec3 position{}; quat rotation{}; vec3 scale{1,1,1}; };
struct preset_cfg { device_preset preset; };
struct basis_cfg { std::string permutation; };
struct mount_cfg { transform_t transform; };
struct device_configure {
std::optional<preset_cfg> preset; // mutually exclusive with mount
std::optional<basis_cfg> basis;
std::optional<mount_cfg> mount; // mutually exclusive with preset
};
// Send / receive
ws.onmessage = [&](const std::string &msg) {
devices_message data{};
if (glz::read<glz_settings>(data, msg)) return;
if (data.inverse3.empty()) return;
const bool do_handshake = first_message.exchange(false);
const bool do_configure = do_handshake || pending_configure.exchange(false);
commands_message out_cmds{};
if (do_handshake) {
out_cmds.session = session_cmd{ /* profile = basis-and-mount */ };
}
for (const auto &dev : data.inverse3) {
device_commands dc{ .device_id = dev.device_id };
if (do_configure) {
device_configure cfg{};
if (do_handshake) cfg.basis = basis_cfg{BASIS};
if (mount_overridden) {
cfg.mount = mount_cfg{ .transform = transform_t{
.rotation = quat_from_xz_deg(mount_angle_x_deg, mount_angle_z_deg)}};
} else {
cfg.preset = preset_cfg{DEVICE_CONFIG_PRESET};
}
dc.configure = std::move(cfg);
}
const float y = dev.state.cursor_position.y;
const float force_y = y > FLOOR_POS_Y ? 0.0f : (FLOOR_POS_Y - y) * STIFFNESS;
dc.commands.set_cursor_force = set_cursor_force_cmd{{0.0f, force_y, 0.0f}};
out_cmds.inverse3.push_back(std::move(dc));
}
std::string out_json;
(void)glz::write_json(out_cmds, out_json);
ws.send(out_json);
};
std::thread input_thr(input_thread_func);
ws.open("ws://localhost:10001");
while (running.load()) std::this_thread::sleep_for(50ms);
チュートリアル 07 は、SDK とともにローカルにもインストールされます。サービスのインストールディレクトリ内の tutorials/07-haply-inverse-basis-and-mount/で閲覧できます。
関連項目: Basisの順列 ・ マウント&ワークスペース ・ デバイスの構成 ・ 制御コマンド (set_cursor_force) ・ タイプ (transform) ・ チュートリアル 04(Hello Floor)