03. 무선 VerseGrip 인쇄
튜토리얼 02모드와 동일하지만, 무선 VerseGrip에 적용됩니다. 스트리밍 상태에서 버튼(A/B/C)과 배터리 잔량이 추가되었습니다.
다음 내용을 배우게 됩니다:
- 무선 장치 고유의 상태 필드를 읽습니다:
buttons.{a,b,c}、battery_level、hall - 将
probe_orientation독립 관찰자로서의 생존 메커니즘 - 튜토리얼 02와동일한, 첫 번째 메시지만 주고받는 핸드셰이크 모드
업무 흐름
- 열기
ws://localhost:10001WebSocket을 열고 첫 번째 상태 프레임을 기다립니다. - ~부터
wireless_verse_grip배열에서 첫 번째 무선 VerseGrip을 가져오는device_id。 - 사용 세션 프로필 요청을 구성하고 각 기기에 다음을 추가합니다.
probe_orientation보육 활동 지침. - 요청을 보낸 다음, 제거하세요
session필드——이는 일회성 핸드셰이크에 불과합니다. - 그 후의 모든 프레임에서, 쿼터너리를 오일러 각도로 변환하고, 버튼 상태 및 배터리 잔량을 포함한 스로틀링 처리된 텔레메트리 데이터를 출력합니다. 매 주기마다 연결 유지 명령을 다시 전송합니다.
매개변수
| 명칭 | 기본값 | 용도 |
|---|---|---|
URI | ws://localhost:10001 | WebSocket 시뮬레이션 채널의 URL |
PRINT_EVERY_MS | 100 | 콘솔 출력 제한 |
| 세션 프로필 이름 | co.haply.inverse.tutorials:print-wireless-verse-grip | Haply Hub에서 이 시뮬레이션을 식별합니다. |
변환에는 내재적 Z-X-Y 순서(요 → 피치 → 롤)가 사용되며, 적용되는 좌표계는 다음과 같습니다. +X right, +Y forward, +Z up。하지 마십시오사용 glm::eulerAngles——이 코드는 다른 규칙을 따르기 때문에, 여기서는 잘못된 결과가 출력됩니다. 세 가지 언어 버전은 모두 동일한 수학적 계산을 구현하고 있습니다. 수식 내용은 소스 코드를 참조하십시오.
probe_orientationprobe_orientation 해당 세션에서만없음Inverse3 으로 명령을 전송할 때만 유용합니다. Inverse3 에 명령(힘, 위치, 토크 등)을 내리면, 서비스는 별도의 감지 과정 없이 각 상태 프레임마다 페어링된 VerseGrip의 방향 데이터를 자동으로 전송합니다. 본 튜토리얼과 같은 독립형 그리핑 모니터링 도구에서만 사용하십시오. probe_orientation。
읽은 상태 필드
출처: data.wireless_verse_grip[0].state:
orientation—quaternion(w, x, y, z)hall— 정수형 홀 센서 측정값buttons.a、buttons.b、buttons.c— 부울 값battery_level— 부동소수점 수 (0.0 – 1.0)transform.rotation— 작업 공간 회전(quaternion); 위치와 확대/축소는 방향만 지원하는 기기에는 적용되지 않으므로 절대 출력되지 않습니다.
그때 transform.rotation 단위 사원수와 같다 {w:1,x:0,y:0,z:0} 이 경우 해당 필드는 생략됩니다. 읽을 때는 기본값을 지정해 주십시오. 활성화 serialization/explicit_fields 이 필드는 항상 수신할 수 있습니다.
보내기 / 받기
와튜토리얼 02구조는 동일하지만, 단지 wireless_verse_grip 장치 배열. WebSocket은 상태 프레임을 주기적으로 수신하고, 핸드셰이크 정보를 반환하며 probe_orientation 활성화 명령; 첫 번째 프레임에는 세션 구성 정보가 포함되며, 그 이후의 모든 프레임에는 활성화 명령만 포함됩니다.
- 파이썬
- C++ (nlohmann)
- C++ (Glaze)
단일 비동기 루프.
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["wireless_verse_grip"][0]["device_id"]
request_msg = {
"session": {"configure": {"profile": {
"name": "co.haply.inverse.tutorials:print-wireless-verse-grip"}}},
"wireless_verse_grip": [{
"device_id": device_id,
"commands": {"probe_orientation": {}} # empty — keepalive
}]
}
await websocket.send(json.dumps(request_msg))
request_msg.pop("session", None) # one-shot handshake
ws.onmessage = [&](const std::string &msg) {
const json data = json::parse(msg);
if (first_message) {
first_message = false;
device_id = data["wireless_verse_grip"][0].at("device_id").get<std::string>();
request_msg = {
{"session", {{"configure", {{"profile",
{{"name", "co.haply.inverse.tutorials:print-wireless-verse-grip"}}}}}}},
{"wireless_verse_grip", json::array({
{{"device_id", device_id},
{"commands", {{"probe_orientation", json::object()}}}},
})},
};
}
ws.send(request_msg.dump());
request_msg.erase("session"); // one-shot handshake
};
ws.open("ws://localhost:10001");
while (std::cin.get() != '\n') {} // block main thread
강타입 구조체. 주의 button_state 명시적으로 명명된 (반면 buttons), 가림 현상을 방지하기 위해 wvg_state 위의 buttons 필드——Glaze는 이름을 기준으로 필드를 매핑하므로, 구조체의 유형명은 임의로 지정할 수 있습니다.
// 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{};
float battery_level{};
};
struct wvg_device { std::string device_id; wvg_state state; };
struct devices_message { std::vector<wvg_device> wireless_verse_grip; };
struct probe_orientation_cmd {}; // empty object on the wire
struct commands_message {
std::optional<session_cmd> session; // one-shot — omitted when unset
std::vector<device_commands> wireless_verse_grip;
};
// Send / receive
ws.onmessage = [&](const std::string &msg) {
devices_message data{};
if (glz::read<glz_settings>(data, msg)) return;
if (first_message) {
first_message = false;
request_msg.session = session_cmd{ /* profile = print-wireless-verse-grip */ };
device_commands dc{ .device_id = data.wireless_verse_grip[0].device_id };
dc.commands.probe_orientation = probe_orientation_cmd{};
request_msg.wireless_verse_grip.push_back(std::move(dc));
}
std::string out_json;
(void)glz::write_json(request_msg, out_json);
ws.send(out_json);
request_msg.session.reset(); // one-shot handshake
};
ws.open("ws://localhost:10001");
while (std::cin.get() != '\n') {} // block main thread
명령줄 인수 (Python)
이 Python 버전은튜토리얼 01과 동일한두 개의 인수를 받습니다:
--full——단일 행 요약이 아닌, 정형화된 형식으로 원본 JSON 페이로드를 출력합니다.--query-config——각 송신 주기마다 재주입session.force_render_full_state, 각 프레임이 다음을 포함하도록 하여config블록이며, 단순히 상태의 증분만이 아닙니다.
--query-config 무선 VerseGrip의 경우 특히 유용합니다. 왜냐하면 config 이 블록은 일반적인 구성 필드 외에도 WVG 전용의 sub_type 필드(stylus / prototype / ruko / kingfisher(3.5 버전에서 추가됨). 실행 python 03-haply-inverse-print-wireless-verse-grip.py --full --query-config 실시간으로 관찰할 수 있습니다 config.sub_type 다른 구성 값과 함께 업데이트됩니다.
C++ 버전에서는 이러한 매개변수를 제공하지 않습니다.
튜토리얼 03도 SDK와 함께 로컬에 설치됩니다. 서비스 설치 디렉터리 내의 tutorials/03-haply-inverse-print-wireless-verse-grip/ 에서 검색하세요.
소스 코드: Python · C++ · C++ Glaze
관련 내용: 튜토리얼 02 (유선 VG) · 유형 (사원수) · 제어 명령(probe_orientation) · WebSocket 프로토콜