06. 통합 예제 (Inverse3 + 무선 VerseGrip)
두 기기를 사용하는 튜토리얼입니다. 그립을 원하는 방향으로 향하게 한 상태에서 버튼을 누르고 있으면 해당 방향으로 Inverse3 커서가 이동합니다. 커서는 구형 작업 공간 내부로 제한됩니다.
학습 내용:
- 같은 상태 프레임에서 두 가지 기기 유형 읽기 (
inverse3및wireless_verse_grip) - 쿼터니언에서 그립이 가리키는 방향 추출하기 (로컬
+Y축) set_cursor_position을 사용하여 계산된 목표 지점으로 커서 이동시키기- 목표 지점을 안전한 작업 공간 구 내부로 제한하기 — Minverse는 Inverse3보다 작은 반경을 사용합니다
- 원점이 도달 범위의 중앙에 위치하도록 작업 공간 프리셋 (
arm_front_centered) 설정하기
작업 흐름
- 두 기기 검색:
- C++ 버전은 시작 시 HTTP을 통해
GET /devices를 조회한 다음 보정 안내 메시지를 출력하고 ENTER 키 입력을 기다립니다. - Python는 첫 번째 WebSocket 상태 프레임에서 두 기기 ID를 모두 읽습니다.
- C++ 버전은 시작 시 HTTP을 통해
- 첫 번째 메시지에서 세션 프로필을 등록하고
configure.preset: arm_front_centered를 설정합니다 (일회성 핸드셰이크). - 매 틱마다 그립의
orientation및buttons.{a, b}상태를 읽습니다. - 이동 버튼이 눌려 있으면 그립의 월드 공간 방향(
R(q) · ĵ— 회전된 단위 +Y 축)을 계산하고, 이를SPEED로 스케일링하여 목표 위치에 누적합니다. - 목표 지점을 작업 공간 구 내부로 제한한 후
set_cursor_position을 통해 전송합니다. - (Python에만 해당) 기기의
config.type에 따라 구의 반경을 조정합니다 —minverse는 0.04 m, 그 외에는 0.10 m입니다.
매개변수
| 이름 | 기본값 | 용도 |
|---|---|---|
SPEED | 0.01 m/틱 | 버튼을 누르고 있는 동안의 이동 간격 |
RADIUS_INVERSE3 | 0.10 m | Inverse3 / Inverse3x의 작업 공간 제한 반경 |
RADIUS_MINVERSE | 0.04 m | Minverse의 작업 공간 제한 반경 (Python에만 해당 — C++은 0.10으로 고정) |
PRINT_EVERY_MS | 200 | 텔레메트리 출력 주기 제한 |
| 세션 프로필 이름 | co.haply.inverse.tutorials:combined | Haply Hub에서 이 시뮬레이션을 식별하는 값 |
- Inverse3이 자동 보정을 수행하도록 두거나 (또는 그립을 잉크웰 위에 놓고 LED가 켜진 상태로 바뀔 때까지 기다리십시오).
- 그립을 잉크웰에서 분리하십시오.
- A 또는 B 버튼을 누른 상태에서 그립을 회전하십시오 — 커서는 그립이 가리키는 방향을 따라 이동합니다.
읽는 상태 필드
틱마다 전달되는 상태 프레임에서 다음 값을 읽습니다:
data.inverse3[0].state.cursor_position—vec3data.wireless_verse_grip[0].state.orientation—quaterniondata.wireless_verse_grip[0].state.buttons.{a, b, c}— 불리언 값- (Python, 첫 번째 프레임에서만)
data.inverse3[0].config.type— Inverse3과 Minverse 반경 중 하나를 선택합니다 - (Python, 첫 번째 프레임에서만)
data.inverse3[0].status.calibrated— 값이 false이면 사용자에게 알립니다
송신 / 수신
쿼터니언에서 방향을 구하는 계산(R(q)로 +Y를 회전하는 연산)과 구 내부 제한 처리는 전형적인 선형 대수 연산입니다. 자세한 내용은 소스 파일을 참고하십시오. Inverse API 측은 핸드셰이크와 틱마다 호출되는 set_cursor_position으로 구성됩니다.
- Python
- C++ (nlohmann)
- C++ (Glaze)
단일 비동기 루프로 구성됩니다. Python는 첫 번째 상태 프레임에서 두 기기 ID를 읽습니다. 핸드셰이크에서는 첫 번째 set_cursor_position 호출에 프로필과 configure.preset: arm_front_centered를 함께 첨부합니다.
async with websockets.connect(URI) as websocket:
while True:
msg = await websocket.recv()
data = json.loads(msg)
if first_message:
first_message = False
inverse3_id = data["inverse3"][0]["device_id"]
grip_id = data["wireless_verse_grip"][0]["device_id"]
radius = get_workspace_radius(data["inverse3"][0].get("config", {}))
# Handshake: profile + preset + first position command
request_msg = {
"session": {"configure": {"profile": {"name": SLUG}}},
"inverse3": [{
"device_id": inverse3_id,
"configure": {"preset": {"preset": "arm_front_centered"}},
"commands": {"set_cursor_position": {"position": position}},
}],
}
else:
# Per tick: update position from grip pointing direction (classic math, not shown), send
request_msg = {
"inverse3": [{
"device_id": inverse3_id,
"commands": {"set_cursor_position": {"position": position}},
}],
}
await websocket.send(json.dumps(request_msg))
C++는 시작 시 GET /devices를 통해(HTTP) 두 기기 ID를 검색한 후 WebSocket을 엽니다. onmessage는 libhv의 I/O 스레드에서 실행되며, 메인 스레드는 ENTER 키 입력까지 블로킹됩니다.
// Startup (synchronous):
const std::string inv3_device_id = get_first_device_id("inverse3");
const std::string grip_device_id = get_first_device_id("wireless_verse_grip");
// Per tick:
ws.onmessage = [&](const std::string &msg) {
json data = json::parse(msg);
// ... classic math (not shown): update local Inverse3State + WirelessVerseGripState,
// compute new position from grip orientation, clamp to sphere ...
json command;
command["inverse3"] = json::array();
command["inverse3"].push_back({
{"device_id", inv3_device_id},
{"commands", {{"set_cursor_position",
{{"position", {{"x", pos.x}, {"y", pos.y}, {"z", pos.z}}}}}}}
});
if (first_message) {
first_message = false;
command["session"] = {{"configure", {{"profile",
{{"name", "co.haply.inverse.tutorials:combined"}}}}}};
command["inverse3"][0]["configure"] = {
{"preset", {{"preset", "arm_front_centered"}}}};
}
ws.send(command.dump());
};
ws.open("ws://localhost:10001");
while (std::cin.get() != '\n') {} // block main thread
libhv 콜백 모델은 동일합니다. 타입이 지정된 구조체(typed struct)로 상태 프레임과 송신 명령을 모두 모델링합니다. devices_message 안의 두 개의 std::vector<> 덕분에 단일 glz::read 호출로 두 기기 유형을 모두 얻을 수 있습니다.
// Struct models
struct quat { float w{1.0f}, x{}, y{}, z{}; };
struct button_state { bool a{}, b{}, c{}; };
struct wvg_state { quat orientation{}; uint8_t hall{}; button_state buttons{}; };
struct wvg_device { std::string device_id; wvg_state state; };
struct inverse_state { vec3 cursor_position{}, cursor_velocity{}; };
struct inverse_device { std::string device_id; inverse_state state; };
struct devices_message {
std::vector<inverse_device> inverse3;
std::vector<wvg_device> wireless_verse_grip;
};
struct set_cursor_position_cmd { vec3 position; };
struct commands_message {
std::optional<session_cmd> session;
std::vector<device_commands> inverse3;
};
// Send / receive
ws.onmessage = [&](const std::string &msg) {
devices_message data{};
if (glz::read<glz_settings>(data, msg)) return;
const auto &wvg = data.wireless_verse_grip[0].state;
cursor_pos = data.inverse3[0].state.cursor_position;
// ... classic math (not shown): if (wvg.buttons.a || wvg.buttons.b)
// move in pointing dir; clamp to sphere ...
commands_message out_cmds{};
device_commands dc{ .device_id = inv3_device_id };
dc.commands.set_cursor_position = set_cursor_position_cmd{cursor_pos};
if (first_message) {
first_message = false;
out_cmds.session = session_cmd{ /* profile = combined */ };
dc.configure = device_configure{ .preset = preset_cfg{"arm_front_centered"} };
}
out_cmds.inverse3.push_back(std::move(dc));
std::string out_json;
(void)glz::write_json(out_cmds, out_json);
ws.send(out_json);
};
ws.open("ws://localhost:10001");
while (std::cin.get() != '\n') {} // block main thread
튜토리얼 06은 SDK와 함께 로컬에도 설치됩니다 — 서비스 설치 디렉터리 아래의 tutorials/06-haply-inverse-combined/ 폴더에서 확인하실 수 있습니다.
관련 항목: 제어 명령 (set_cursor_position) · 타입 (quaternion, vec3) · 마운트 및 작업 공간 (프리셋) · 튜토리얼 03 (무선 VG) · 튜토리얼 05 (위치 제어)