05. 위치 제어
Inverse3 의 커서를 다음을 통해 제어합니다. set_cursor_position 목표 위치로. 상호작용 모델은 프로그래밍 언어에 따라 다릅니다. — C++는 일회성 무작위 목표 위치를 사용하는 반면, 파이썬은 키보드로 제어되는 연속적인 이동을 사용합니다.
학습 내용:
- 사용법
set_cursor_position위치 모드 제어용 - 동일한 기본 명령에 대한 두 가지 서로 다른 상호작용 모델
- 목표를 작업 공간 구로 제한 — Minverse 은 다음보다 더 작은 반경을 사용합니다. Inverse3
- 작업 공간의 중심에 원점이 오도록 작업 공간 기본 설정을 지정하기
진행 절차
C++ (무작위 목표 모델)
- 줄 단위로 버퍼링된 키 입력을 처리하는 백그라운드 입력 스레드를 시작하십시오 (
n,+,-,q) von stdin에서 읽습니다. - 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) | Zweck |
|---|---|---|---|
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 | gleich | Haply 허브에서 식별됨 |
Python 변형은 다음을 확인합니다. 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++ 다음과 같은 백그라운드 stdin 스레드를 실행합니다.
std::atomic<float>-Ziele가 데이터를 작성하면, 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스레드 모델: 백그라운드 스레드가 stdin을 읽고 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 (통합)