05. 位置制御
set_cursor_position を介して、Inverse3 のカーソルを目標位置へ移動させます。インタラクションモデルは言語によって異なります — C++ は 1 回限りのランダムな目標を使用し、Python は連続的なキーボード操作による動きを使用します。
学習内容:
- 位置モード制御のための
set_cursor_positionの使い方 - 同じ基盤コマンドに対する 2 つの異なるインタラクションモデル
- 目標位置のワークスペース球へのクランプ — Minverse は Inverse3 より小さい半径を使用します
- 原点がワークスペースの中心に来るよう、ワークスペースのプリセット を設定する
ワークフロー
C++(ランダム目標モデル)
- 標準入力から行バッファリングされたキー入力(
n、+、-、q)を読み取る、バックグラウンドの入力スレッドを開始します。 - WebSocket を開きます。最初の状態フレームで、セッションプロファイル を登録し、
configure.preset: arm_front_centeredを設定します。球内(棄却サンプリング、半径 0.08 m)で最初のランダムな目標を生成します。 - 各ティックで、現在の目標に対して
set_cursor_positionコマンドを送信します。カーソルはこれを滑らかに追従します — サービス側でレート制限と補間が行われます。 - ユーザーが
nと ENTER を入力すると、入力スレッドが新しいランダムな目標を生成します。+/-で速度を調整し、qで終了します。
Python(長押し移動モデル)
- WebSocket を開きます。最初の状態フレームで
status.calibratedを確認し、デバイスがまだキャリブレーションされていない場合はユーザーに通知します。 config.typeを読み取り、ワークスペースの半径を決定します(minverseの場合は 0.04 m、それ以外は 0.10 m)。- セッションプロファイル を登録し、
configure.preset: arm_front_centeredを設定します。 - 各ティックで、キーボードの状態(
W/A/S/D/Q/E)をポーリングし、押されている各軸に沿って目標位置をSPEED分だけ更新して、ワークスペース球内にクランプし、set_cursor_positionを送信します。Rで目標を原点にリセットします。
パラメーター
| 名前 | 既定値 (C++) | 既定値 (Python) | 用途 |
|---|---|---|---|
workspace_radius / RADIUS_INVERSE3 | 0.08 m | 0.10 m (Inverse3) / 0.04 m (Minverse) | 目標球の半径 |
speed_step / SPEED | 0.01 / 押下 | 0.00005 m / ティック | 操作ごとの移動量 |
PRINT_EVERY_MS | — | 100 | テレメトリの出力間隔制限(Python) |
| セッションプロファイル | co.haply.inverse.tutorials:position-control | 同じ | Haply Hub での識別に使用 |
Python のバリアントは、最初の状態フレームから status.calibrated を確認し、デバイスがキャリブレーションされていない場合はユーザーに通知します。C++ のバリアントは、キャリブレーションが完了していることを前提としています。
読み取る状態フィールド
data.inverse3[0].device_id— コマンドの構築に使用data.inverse3[0].state.cursor_position— テレメトリ- (Python、最初のフレームのみ)
data.inverse3[0].config.type— Inverse3 と Minverse のどちらの半径を使用するかを選択 - (Python、最初のフレームのみ)
data.inverse3[0].status.calibrated— false の場合はユーザーに通知
送受信
通信のワークフロー
- C++ は、
std::atomic<float>の目標値を書き込むバックグラウンドの標準入力スレッドを実行します。WebSocket スレッドは毎ティックこれを読み取ります。nと ENTER で入力スレッドが新しいランダムな目標を生成し、qで両方のスレッドが終了します。 - Python はシングルスレッドの非同期処理です。WebSocket ループが毎ティックキーボードの状態をポーリングし、
positionを直接更新します。
Inverse-API のペイロードは同じです。最初のティックではセッションプロファイルと configure.preset を送信し、以降のティックでは set_cursor_position のみを送信します。
- Python
- C++ (nlohmann)
- C++ (Glaze)
単一の非同期ループです。キーボードのポーリング(handle_keys)は、毎ティックインラインで実行され、スレッドは使用しません。config.type と status.calibrated は、最初の状態フレームから一度だけ読み取られます。
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"]
radius = get_workspace_radius(data["inverse3"][0].get("config", {}))
# Handshake: profile + preset (one-shot)
request_msg = {
"session": {"configure": {"profile": {"name": SLUG}}},
"inverse3": [{
"device_id": device_id,
"configure": {"preset": {"preset": "arm_front_centered"}},
}],
}
else:
# Per tick: update position from keyboard (classic polling, not shown), send command
position = handle_keys(position, radius)
request_msg = {
"inverse3": [{
"device_id": device_id,
"commands": {"set_cursor_position": {"position": position}},
}],
}
await websocket.send(json.dumps(request_msg))
2 スレッドモデルです。バックグラウンドスレッドが標準入力を読み取り、std::atomic<float> の目標値を書き込みます。libhv の I/O スレッドは、毎ティック ws.onmessage を実行し、そのアトミック変数を読み取ります。
// Shared state written by the stdin thread, read by the ws thread
static std::atomic<float> target_x{0.0f}, target_y{0.0f}, target_z{0.0f};
ws.onmessage = [&](const std::string &message) {
const json data = json::parse(message);
if (data["inverse3"].empty()) return;
json request = {};
const bool do_handshake = first_message.exchange(false);
if (do_handshake) {
request["session"] = {{"configure", {{"profile",
{{"name", "co.haply.inverse.tutorials:position-control"}}}}}};
generate_random_target();
}
request["inverse3"] = json::array();
for (auto &el : data["inverse3"].items()) {
json dev = {
{"device_id", el.value()["device_id"]},
{"commands", {{"set_cursor_position",
{{"position", {{"x", target_x.load()},
{"y", target_y.load()},
{"z", target_z.load()}}}}}}},
};
if (do_handshake)
dev["configure"] = {{"preset", {{"preset", "arm_front_centered"}}}};
request["inverse3"].push_back(dev);
}
ws.send(request.dump());
};
ws.open("ws://localhost:10001");
std::thread input_thr(input_thread_func); // stdin reader — writes target atomics
while (running) std::this_thread::sleep_for(100ms);
2 スレッドモデルは同じです。コマンドには型付き構造体を使用しています。std::optional<device_configure> がデバイスごとの 1 回限りのプリセットを保持し、以降のティックでは JSON から省略されます。
// Struct models
struct vec3 { float x{}, y{}, z{}; };
struct set_cursor_position_cmd { vec3 position; };
struct preset_cfg { std::string preset; };
struct device_configure { std::optional<preset_cfg> preset; };
struct device_commands {
std::string device_id;
std::optional<device_configure> configure; // one-shot
struct commands_t {
std::optional<set_cursor_position_cmd> set_cursor_position;
} commands;
};
struct commands_message {
std::optional<session_cmd> session; // one-shot
std::vector<device_commands> inverse3;
};
// Send / receive
ws.onmessage = [&](const std::string &msg) {
devices_message data{};
if (glz::read<glz_settings>(data, msg)) return;
commands_message request;
const bool do_handshake = first_message.exchange(false);
if (do_handshake) {
request.session = session_cmd{ /* profile = position-control */ };
}
for (const auto &dev : data.inverse3) {
device_commands dc{ .device_id = dev.device_id };
dc.commands.set_cursor_position = set_cursor_position_cmd{
.position = {target_x.load(), target_y.load(), target_z.load()}};
if (do_handshake)
dc.configure = device_configure{ .preset = preset_cfg{"arm_front_centered"} };
request.inverse3.push_back(std::move(dc));
}
std::string out;
(void)glz::write_json(request, out);
ws.send(out);
};
ws.open("ws://localhost:10001");
std::thread input_thr(input_thread_func);
while (running) std::this_thread::sleep_for(100ms);
チュートリアル 05 も SDK と一緒にローカルへインストールされています。サービスのインストールディレクトリ配下の tutorials/05-haply-inverse-position-control/ を参照してください。
関連: 制御コマンド (set_cursor_position) · マウントとワークスペース(プリセット) · 型 (vec3) · チュートリアル 06(Combined)