05. 위치 제어
set_cursor_position 을 통해Inverse3 의 커서를 목표 위치로 이동시킵니다.상호작용 모델은 언어에 따라 다릅니다 — C++는 한 번만 사용되는 무작위 목표점을 사용하는 반면, Python은 연속적인 키보드 입력을 통해 움직임을 제어합니다.
학습 내용:
- 위치 모드 제어를 위한
set_cursor_position사용법 - 동일한 기본 명령에 대한 두 가지 서로 다른 상호작용 모델
- 목표 위치의 작업 공간 구체에 클램프 — ‘ Minverse ’는 ‘ Inverse3 ’보다 작은 반지름을 사용합니다.
- 원점이 작업 영역의 중앙에 오도록작업 영역 사전 설정을 지정합니다.
워크플로우
C++ (무작위 목표 모델)
- 표준 입력에서 행 단위로 버퍼링된 키 입력(
n、+、-、q)를 읽어들이는 백그라운드 입력 스레드를 시작합니다. - WebSocket을 엽니다. 첫 번째 상태 프레임에서,세션 프로필 을 등록하고,
configure.preset: arm_front_centered을 설정합니다. 구 내부(배제 샘플링, 반경 0.08 m)에서 첫 번째 무작위 목표물을 생성합니다. - 각 틱마다, 현재 목표 대비
set_cursor_position명령을 전송합니다. 커서는 이를 부드럽게 따라갑니다 — 서비스 측에서 속도 제한 및 보간 처리가 이루어집니다. - 사용자가
n'ENTER'를 누르면 입력 스레드가 새로운 무작위 목표를 생성합니다.+/-속도를 조절하고,q로 끝납니다.
파이썬 (길게 누르면 이동하는 모델)
- 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에서 식별에 사용 |
파이썬의 변형은 첫 번째 상태 프레임에서 status.calibrated 이를 확인하고, 기기가 보정되지 않은 경우 사용자에게 알립니다. C++ 버전은 보정이 완료된 것을 전제로 합니다.
읽기 전용 상태 필드
data.inverse3[0].device_id— 명령어 구성에 사용data.inverse3[0].state.cursor_position— 텔레메트리- (파이썬, 첫 번째 프레임만)
data.inverse3[0].config.type— Inverse3 와 Minverse 중 어느 반지름을 사용할지 선택 - (파이썬, 첫 번째 프레임만)
data.inverse3[0].status.calibrated— false인 경우 사용자에게 알림
송수신
통신 워크플로우
- C++ 는,
std::atomic<float>목표값을 기록하는 백그라운드 표준 입력 스레드를 실행합니다. WebSocket 스레드는 매 틱마다 이를 읽어들입니다.n그리고 ENTER 키를 누르면 입력 스레드가 새로운 무작위 목표를 생성하고,q그러면 두 스레드 모두 종료됩니다. - 파이썬 이는 단일 스레드 비동기 처리입니다. WebSocket 루프는 매 틱마다 키보드 상태를 폴링하며,
position을 직접 업데이트합니다.
Inverse-API의 페이로드는 동일합니다. 첫 번째 틱에서는 세션 프로필과 configure.preset 을 전송하고, 이후의 틱에서는 set_cursor_position 만 전송합니다.
- 파이썬
- 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> 이는 기기별로 한 번만 적용되는 사전 설정을 유지하며, 이후의 틱에서는 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 (통합)