07. 기초 및 설치: 시험장
다음과 같이 대화형 방식으로 제어하세요. 편집 변환 기기의 기능을 설명하고, 다음과 같이 configure.basis, configure.preset et configure.mount 프로토콜 수준에서 함께 작동합니다. 상호작용 가능한 관심 지점이 설정 제어 항목 위에 머물 수 있도록 수평선을 고정된 상태로 유지합니다.
이 강좌에서 배우게 될 내용:
- 정의하기 기본 순열 (
"XZY"→ Y축이 위를 향하도록 정렬된 기준점) - 선택하기 사전 설정 (
arm_front) 그리고 그것이 무엇을 설정하는지 이해하기 - 실행 시의 조립 과정을 (키보드로 제어되는) 회전 쿼터니언으로 대체하기
- 상호 배타의 법칙:
mountetpreset는 같은 블록 내에서 공존할 수 없습니다. 기기 설정 - [ ]의 점별 의미론
configure: 키를 누를 때마다 정확히 하나의 구성 메시지가 전송됩니다 - (C++ Glaze) 상호 배타적인 필드의 모델링
std::optional
업무 흐름
- 첫 번째 메시지를 보내실 때: 다음을 보내주세요 세션 프로필,
configure.basis: "XZY"etconfigure.preset: arm_front. 보내기 시작하세요set_cursor_force고정 바닥용. - 각 사이클마다: 커서의 Y 값을 읽고, 다음을 계산합니다.
force_y = max(0, (floor_pos - y) * stiffness)그리고 보내주세요. - 사용자가 마운트의 회전 버튼을 누르면 다음을 설정하십시오.
pending_configure = true. - 다음 단계: 블록 만들기
configure.mount변환을 통해rotation는 유니터리 쿼터니언입니다(현재 피치 및 요각의 Z, X 순서 합성). 생략하십시오preset— 두 가지 모두 프로토콜 차원에서 상호 배타적입니다. - 재설정 버튼 (
R)는 대체 내용을 지웁니다. 다음 설정은 다음과 같은 효과를 냅니다.preset.
매개변수
| Nom | 결함 | 역할 |
|---|---|---|
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 et preset 서로 배타적이다이 서비스는 다음 블록을 거부합니다. 기기 설정 이 두 가지를 모두 포함하고 있습니다. 사용자가 마운트를 교체하면, 튜토리얼에서는 다음 내용을 생략합니다. preset 다음 각 구성에 대해. 누르십시오 R 반응형 preset 다음과 같이 구성하고 제거하십시오 mount.
C++ 버전은 백그라운드에서 stdin 실행 스레드를 통해 입력 내용을 한 줄씩 읽어들입니다(각 문자를 입력한 후 Enter 키를 누르세요). Python은 다음 패키지를 사용합니다. keyboard 주 비동기 루프에서 키 입력을 실시간으로 감지하기 위해 — ENTER 키는 필요하지 않습니다. 동일한 키, 동일한 명령어입니다.
가장 많이 읽힌 주 챔피언십 기사
~부터 data.inverse3[i].state :
cursor_position.y—vec3, 토양 침투도를 계산하는 데 사용됨current_cursor_force— 원격 측정용으로 신고됨
발송 / 수신
모든 변형에 대해 유효 부하의 구조는 동일하며, 주목할 만한 차이점은 각 변형이 상호 배타적 분기를 구성하는 방식에 있습니다. mount / preset 그리고 입력 신호가 WebSocket 신호를 어떻게 전달하는지.
- 파이썬
- 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 (un 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> et 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/ 서비스 설치 디렉터리에서.
관련 항목: 기본 순열 · 편집 및 작업 공간 · 기기 설정 · 제어 명령 (set_cursor_force) · 유형 (변환) · 튜토리얼 04 (Hello Floor)