> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kinatric.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Motion control and service discovery

> Use SportClient, MotionSwitcherClient, and RobotStateClient and interpret request results.

> **Compatibility**
>
> This interface applies to Kinatric D2 and D2W on RK3576. See the [Kinatric deployment repository](https://github.com/Kinatric/rl_sim2real) for published source and deployment instructions. Use SDK versions compatible with the installed gateway, which reports RPC API version `1.0.0.1`. The [Kinatric C++ SDK](https://github.com/Kinatric/dds-sdk) provides D2 and D2W examples.

## Introduction

The Kinatric D2 motion service provides two high-level interfaces over DDS.

* **High-level control** sends posture and velocity requests with `SportClient`. `MotionSwitcherClient` handles the controller handover, and `RobotStateClient` reports service availability.
* **High-level status** uses `rt/sportmodestate` for motion phase and available IMU data. Kinatric D2 also provides topics for control state, actuator feedback, and measurement validity.

## High-Level Control Interface

### Calling the High-Level Control Interface

Use the same **external DDS domain** on the board and client. The external default is `0`. The board uses a separate internal domain, `71` by default. The external and internal domain IDs must differ. Set the board interface with `KINATRIC_DDS_INTERFACE` and the external domain with `KINATRIC_DDS_DOMAIN`. For unicast discovery, set `KINATRIC_DDS_PEER` on the board to the client IP and pass the board IP as `--peer` to the Python probe. Multicast discovery can omit the peer on a compatible network.

Initialize `ChannelFactory` before creating an SDK client. The C++ example queries the gateway version and assumes DDS discovery is configured for the selected interface. For an explicit discovery peer in C++, configure it in Cyclone DDS.

```cpp theme={null}
#include <iostream>
#include <string>
#include <kinatric/robot/channel/channel_factory.hpp>
#include <kinatric/robot/d2/sport/sport_client.hpp>

int main(int argc, char* argv[]) {
    if (argc != 3) return 2;  // Arguments are the DDS domain and client interface.
    const auto domain = std::stoi(argv[1]);
    kinatric::robot::ChannelFactory::Instance()->Init(domain, argv[2]);

    kinatric::robot::d2::SportClient sport;
    sport.SetTimeout(3.0f);
    sport.Init();

    const auto version = sport.GetServerApiVersion();
    std::cout << version << '\n';
    return version == sport.GetApiVersion() ? 0 : 1;
}
```

The Python examples require the interface-test helper scripts supplied with the matching gateway deployment. Check that those scripts and their dependencies are available before running them; they are not included in the current [published deployment source](https://github.com/Kinatric/rl_sim2real). Set `D2_DOMAIN` to the external domain, `PC_IFACE` to the client interface name or IPv4 address, and `D2_IP` to the board IPv4 address. The read-only probe reports the API version, service list, `CheckMode` result, control state, and available feedback. In standby, version and service queries can succeed while live joint feedback is unavailable and `CheckMode` reports `4202`.

```sh theme={null}
python tests/sdk/support/d2_client.py --domain "$D2_DOMAIN" --interface "$PC_IFACE" --peer "$D2_IP" status
```

Before sending motion commands, start a local session with an Xbox **Select** press and release or a LiteRadio 4 **SA** off-to-on transition. Wait for the board to complete its startup checks and report `Passive` in the active session.

### High-Level Motion Control Functions

#### SportClient

Requests use `rt/api/sport/request` and replies use `rt/api/sport/response`.

| **Function Name** | **Damp** |
| - | - |
| **Prototype** | `int32_t Damp()` |
| **Function Overview** | Requests damping and clears the active motion command. |
| **Parameters** | None. |
| **Return Value** | `0` if accepted. Other values are error codes. |
| **Notes** | API ID `1001`. Use `control_state.state` to confirm `Passive`. |

| **Function Name** | **StopMove** |
| - | - |
| **Prototype** | `int32_t StopMove()` |
| **Function Overview** | Clears the SDK velocity target and requests zero velocity through the controller's ramp. |
| **Parameters** | None. |
| **Return Value** | `0` if accepted. Other values are error codes. |
| **Notes** | API ID `1003`. |

| **Function Name** | **StandUp** |
| - | - |
| **Prototype** | `int32_t StandUp()` |
| **Function Overview** | Requests a transition from ready `Passive` to `Stand`. |
| **Parameters** | None. |
| **Return Value** | `0` if accepted. Other values are error codes. |
| **Notes** | API ID `1004`. Check `control_state.state` for `Stand`. |

| **Function Name** | **StandDown** |
| - | - |
| **Prototype** | `int32_t StandDown()` |
| **Function Overview** | Clears the velocity command and requests a controlled lie-down ending in `Passive`. |
| **Parameters** | None. |
| **Return Value** | `0` if accepted. Other values are error codes. |
| **Notes** | API ID `1005`. Check `control_state.state` for `Passive`. |

| **Function Name** | **Move** |
| - | - |
| **Prototype** | `int32_t Move(float vx, float vy, float vyaw)` |
| **Function Overview** | Updates the planar velocity target. From `Stand`, an accepted command can start the locomotion policy. |
| **Parameters** | `vx` is forward velocity in m/s, `vy` is lateral velocity in m/s, and `vyaw` is yaw rate in rad/s. All three values must be finite. The JSON fields are `x`, `y`, and `z`. |
| **Return Value** | `0` means acceptance for a synchronous request. In the pinned Python client, `0` means the request was sent with `noreply`. |
| **Notes** | API ID `1008`. Read `command_max_velocity` from `rt/kinatric/robot_description` to find the limits for the active profile. The board limits and shapes the target. |

A locomotion-enabled session accepts fresh `Move` targets from `Stand`, a ready `StandFallback`, or an active locomotion phase, subject to its policy and transition checks. A stand-only session returns `3203`.

#### MotionSwitcherClient

Requests use `rt/api/motion_switcher/request` and replies use `rt/api/motion_switcher/response`.

| **Function Name** | **CheckMode** |
| - | - |
| **Prototype** | `int32_t CheckMode(std::string& form, std::string& name)` |
| **Function Overview** | Reads the active controller mode. |
| **Parameters** | Output arguments `form` and `name`. `form` is the string `"0"` when the service is available. |
| **Return Value** | `0` if the query succeeded. Other values are error codes. |
| **Notes** | API ID `1001`. `name` is `normal` while the onboard controller holds high-level control. An empty `name` indicates that high-level control is released. |

| **Function Name** | **SelectMode** |
| - | - |
| **Prototype** | `int32_t SelectMode(const std::string& nameOrAlias)` |
| **Function Overview** | Returns control to the onboard controller. |
| **Parameters** | Pass `"normal"`. This is the supported mode selection. |
| **Return Value** | `0` if accepted. Other values are error codes. |
| **Notes** | API ID `1002`. During handover, continue the low-level command stream until `CheckMode()` reports `name="normal"`. |

| **Function Name** | **ReleaseMode** |
| - | - |
| **Prototype** | `int32_t ReleaseMode()` |
| **Function Overview** | Requests release of high-level control. The board first transitions to `Passive` if needed. |
| **Parameters** | None. |
| **Return Value** | `0` if accepted. Other values are error codes. |
| **Notes** | API ID `1003`. Poll `CheckMode` until `name` is empty before publishing low-level commands. |

#### RobotStateClient and Version Query

The robot state service uses `rt/api/robot_state/request` and `rt/api/robot_state/response`.

| **Function Name** | **ServiceList** |
| - | - |
| **Prototype** | `int32_t ServiceList(std::vector<ServiceState>& serviceStateList)` |
| **Function Overview** | Queries the gateway's view of service availability for `kinatric_basicd`, `kinatric_sportd`, and `kinatric_gateway`. |
| **Parameters** | Output list of service records with `name`, `status`, and `protect`. |
| **Return Value** | `0` if the query succeeded. Other values are error codes. |
| **Notes** | API ID `1003`. `kinatric_basicd` can report `status=1` with `available=false`. Use `control_state` to determine whether a motion session is active and `state_validity.joints` to check feedback availability. |

| **Function Name** | **GetServerApiVersion** |
| - | - |
| **Prototype** | `std::string GetServerApiVersion()` |
| **Function Overview** | Reads the gateway API version. |
| **Parameters** | None. |
| **Return Value** | The gateway reports `1.0.0.1`. |
| **Notes** | API ID `1` on `sport`, `motion_switcher`, and `robot_state`. |

### Error Codes

For a synchronous motion RPC, `0` means that the board accepted the request. Observe `control_state.state` to confirm motion completion. The pinned Python `SportClient.Move()` uses `noreply`, so its `0` means the client sent the request. Use `rt/kinatric/operation_state` to see the board's acceptance or rejection. The gateway honors `noreply` for all supported calls.

| Code | Meaning |
| -: | - |
| `0` | Request accepted, or query succeeded. |
| `3202` | Gateway received an invalid or unexpected backend response. |
| `3203` | The service does not support the API ID, or the current backend does not support the action, such as `Move` in a stand-only session. |
| `3204` | Invalid request, invalid parameters, or conflicting reuse of a request ID. |
| `3205` | Control is occupied by another client or blocked by the local controller. |
| `4202` | The required backend, session, or mode is unavailable, or the request expired or was dropped before dispatch. |

Direct RPC clients use the pinned SDK's `Request_` and `Response_` types. For methods without arguments, leave the parameter string empty or send `{}`. Send `{"name":"normal"}` for mode selection. Leave the lease ID at `0` and the binary payload empty. Within its retry cache, the gateway reuses an identical request's result for the same service, DDS writer, API ID, nonzero request ID, and ownership epoch.

### Example

These commands move Kinatric D2. Start a local session with locomotion enabled. Set `VX`, `VY`, and `VYAW` to targets approved for the test setup, and `MOVE_SECONDS` to a positive duration. Run the example in Bash from the same deployment checkout as the status probe.

```sh theme={null}
PYTHONPATH=tests/sdk/support python - "$D2_DOMAIN" "$PC_IFACE" "$D2_IP" \
  "$VX" "$VY" "$VYAW" "$MOVE_SECONDS" <<'PY'
import json
import math
import sys
from queue import Queue

from d2_client import checked, connect, init_client, move_for, participant_id, wait_for_posture
from kinatric_sdk import ChannelSubscriber, SportClient, String_

domain, interface, peer, *values = sys.argv[1:]
vx, vy, vyaw, seconds = map(float, values)
if not all(map(math.isfinite, (vx, vy, vyaw, seconds))) or seconds <= 0:
    raise SystemExit("Specify finite velocities and a positive duration")

connect(int(domain), interface, peer)
sport = init_client(SportClient)
participant = participant_id()
move_codes = Queue()

def on_operation(message):
    report = json.loads(message.data)
    if (report.get("service") == "sport" and report.get("api_id") == 1008
            and report.get("participant") == participant):
        move_codes.put(report["code"])

def wait_for(expected):
    if wait_for_posture(expected).get("completed") is not True:
        raise RuntimeError(f"Board did not confirm {expected}")

operations = ChannelSubscriber("rt/kinatric/operation_state", String_)
operations.Init(on_operation, 64)
try:
    checked(sport.StandUp(), "StandUp")
    try:
        wait_for("Stand")
        sent = move_for(sport, (vx, vy, vyaw), seconds)
        for _ in range(sent["samples"]):
            checked(move_codes.get(timeout=2.0), "Move gateway result")
    finally:
        checked(sport.StandDown(), "StandDown")
        wait_for("Passive")
finally:
    operations.Close()
PY
```

The example uses one DDS participant for all three actions, waits for `Stand` and `Passive`, and checks the `Move` results in `operation_state`. The timed move refreshes the target about every 50 ms and calls `StopMove()` on exit. The helper's `move` subcommand sends a single target if `--seconds` is omitted. End the local session using the corresponding Select or SA exit gesture when finished.

### Control Ownership and Timeouts

The first eligible SDK DDS participant can acquire control automatically. The gateway releases the high-level DDS holder after **1 s** of no new admitted activity by default, or when it detects that the client has left. Commands accepted by the motion backend renew effective control authority. If the robot is already in `Stand`, it holds that posture when SDK ownership expires.

| Condition | Board behavior |
| - | - |
| Local high-level gamepad activity | Preempts the SDK. The SDK can acquire control again after fresh neutral input for the default **1 s**. Local damping locks SDK motion until an eligible local stand request while `Passive` is ready. |
| `Damp()` or `StopMove()` from another client | These commands can pass the ownership gate in an eligible active session. |
| `Move` stream lapses for **300 ms** | Clears the velocity target and requests a fallback toward standing when locomotion is active. |
| Selected `LowCmd` stream lapses for the default **60 ms** | The HAL handles external control loss with fault damping, STOP, and parameter restoration. A new local Select or SA start gesture is required before resuming motion. |
| Local controller disconnects while the SDK owns control | The SDK can continue. If the controller is still disconnected when SDK ownership ends, the default **5 s** input grace period begins. |

Use `control_state.authorization` to inspect the SDK holder, the ownership epoch, and the bound low-level writer. Use `control_state.hardware` to inspect the HAL result during a fault or session exit.

## High-Level Status Interface

### Subscribing to High-Level Status

Subscribe to `rt/sportmodestate` on the external DDS domain to read the Kinatric D2 motion mode, phase progress, and available IMU data. The example reads one sample from an active session. Run it in Bash from the same deployment checkout as the status probe, with the same network variables.

```sh theme={null}
PYTHONPATH=tests/sdk/support python - "$D2_DOMAIN" "$PC_IFACE" "$D2_IP" <<'PY'
import sys

from d2_client import connect
from kinatric_sdk import ChannelSubscriber, SportModeState_

domain, interface, peer = sys.argv[1:]
connect(int(domain), interface, peer)
subscriber = ChannelSubscriber("rt/sportmodestate", SportModeState_)
subscriber.Init()
try:
    state = subscriber.Read(2.0)
    if state is None:
        raise SystemExit("No motion status received within two seconds")
    print({"mode": state.mode, "progress": state.progress})
finally:
    subscriber.Close()
PY
```

### High-Level Status Types

The C++ `SportModeState_` accessors below expose the fields published by the Kinatric D2 runtime. `progress` depends on the current phase.

```cpp theme={null}
const TimeSpec_& stamp() const;
uint8_t mode() const;
float progress() const;
const IMUState_& imu_state() const;
```

When the IMU is valid, the orientation is in `w, x, y, z` order, angular velocity is in rad/s, and roll, pitch, and yaw are in rad. `state_validity.tick` identifies a `LowState_` sample. To read linear acceleration in m/s² with per-sample validation, match the `LowState_` tick and check `state_validity.acceleration` as described below.

```cpp theme={null}
const std::array<float, 4>& quaternion() const;
const std::array<float, 3>& gyroscope() const;
const std::array<float, 3>& accelerometer() const;
const std::array<float, 3>& rpy() const;
```

The motion state machine uses `SportModeState_.mode` as shown below. The locomotion runtime pauses this stream once `ReleaseMode()` has taken effect.

| `SportModeState_.mode` | D2 motion phase |
| -: | - |
| `0` | `Stand`, `Prepare`, `GetUp`, `Warmup`, `ReturnStand`, `StandFallback` |
| `3` | `Blend`, `RL` |
| `5` | `GetDown` |
| `7` | `Passive` |

The JSON field `control_state.mode` maps `Stand` to `0`, `RL` to `3`, `Passive` to `7`, and other FSM states to `-1`. Use `control_state.state` for the exact FSM state. In `control_state.controller`, `internal` means the onboard controller, `waiting` means high-level control is released and no low-level writer has been selected by the HAL, and `external` means a low-level writer is selected.

#### Additional Status Topics

The gateway publishes its JSON status messages as `std_msgs::msg::dds_::String_` on the external DDS domain.

| Topic | Type | Available data |
| - | - | - |
| `rt/lowstate` | `LowState_` | CRC-protected live actuator and IMU feedback. Pair it with the validity report using `tick`. |
| `rt/kinatric/control_state` | JSON string | Live FSM `state`, `action_phase`, and `controller` when available. `authorization` reports SDK ownership, `hardware` reports HAL health, and `last_motion` holds the most recent cached motion snapshot. |
| `rt/kinatric/operation_state` | JSON string | RPC results include `service`, `id`, `api_id`, `code`, `writer`, `participant`, `grant_epoch`, `status`, and `noreply`. Low-level ingress reports use `service="low"` and include a `reason` such as `forwarded` or `invalid_command`. |
| `rt/kinatric/state_validity` | JSON string | `source`, `environment`, and `joints`. When joint data is available, also includes `tick` and validity flags for IMU, acceleration, temperature, sport mode, and BMS. |
| `rt/kinatric/robot_description` | `kinatric::RobotDescriptionV1` | Robot `model`, `profile_hash`, actuator count, slot-indexed actuator names, kinds and limits, and the `x`, `y`, and yaw command limits. Use transient-local durability to receive the cached description. |
| `rt/kinatric/hal_health` | JSON string | HAL phase, faults, and hardware diagnostics when available. |
| `rt/kinatric/battery` | JSON string | BMS availability, connection, validity, and sampled pack data. `rt/kinatric/battery_state` is an alias. |
| `rt/wirelesscontroller` | `WirelessController_` | Read-only local input axes `lx`, `ly`, `rx`, `ry` and the `keys` bit mask while the input service publishes. |

For each `LowState_` sample, check the SDK CRC, match `LowState_.tick` to `state_validity.tick`, and require `joints=true` before consuming actuator measurements. Check `imu`, `acceleration`, and `temperature` before using those fields. The validity worker targets a 20 ms loop. `LowState_` itself is forwarded from the HAL as it arrives and has its own cadence.

| LowState field | Meaning |
| - | - |
| `motor_state[i].q`, `.dq`, `.tau_est` | Angle in rad, angular velocity in rad/s, and estimated torque in N·m. Use the robot description to select the configured slots. |
| `motor_state[i].temperature` | Motor temperature in °C when valid, rounded to an integer. |
| `imu_state.quaternion`, `.gyroscope`, `.rpy` | Orientation quaternion in `w, x, y, z` order, angular velocity in rad/s, and roll, pitch and yaw in rad. |
| `imu_state.accelerometer` | Linear acceleration in m/s² when `acceleration=true`. |
| `bms_state.soc` | Integer percentage when fresh BMS data is available. Use the separate battery topic for pack details and freshness. |

Foot forces, body position, and measured body velocity are unavailable in this interface. Other unpopulated SDK fields carry their IDL defaults. The Nano ROS 2 bridge converts `/cmd_vel` to `Move`, publishes matched joint and IMU feedback to `/joint_states` and `/imu/data`, and uses `base_link` for IMU messages.

#### Joint Feedback Example

This read-only example prints one validity report and its matching 12-leg-axis feedback sample when available. Run it in Bash from the same deployment checkout as the status probe, with the same network variables. The `feedback_report` helper checks the tick and CRC before returning joint data.

```sh theme={null}
PYTHONPATH=tests/sdk/support python - "$D2_DOMAIN" "$PC_IFACE" "$D2_IP" <<'PY'
import json
import sys

from d2_client import connect, feedback_report
from kinatric_sdk import ChannelSubscriber, LowState_, String_

domain, interface, peer = sys.argv[1:]
connect(int(domain), interface, peer)
validity = ChannelSubscriber("rt/kinatric/state_validity", String_)
lowstate = ChannelSubscriber("rt/lowstate", LowState_)
validity.Init()
lowstate.Init()
try:
    report, feedback = feedback_report(validity, lowstate)
    print(json.dumps({"validity": report, "feedback": feedback}))
finally:
    lowstate.Close()
    validity.Close()
PY
```

## Low-Level Control Interface

Publish `LowCmd_` on `rt/lowcmd`. Both `LowCmd_` and `LowState_` contain 20 motor slots. Within each leg, the slots are hip, thigh, and calf.

| Slots | Actuators |
| - | - |
| `0–2`, `3–5`, `6–8`, `9–11` | Front right, front left, rear right, rear left legs on D2 and D2W. |
| `12–15` | D2W velocity-controlled wheels in front right, front left, rear right, rear left order. Unused on D2. |
| `16–19` | Unused on both models. |

Use the motion command header `0xFE, 0xEF`, level flag `0xFF`, and SDK CRC. Use `mode` 0 or 1 and finite values. For unused slots or slots in mode 0, set `kp`, `kd`, and `tau` to zero, and set `q` and `dq` to zero or their respective sentinels. `PosStopF = 2.146e9f` clears `q` and `kp`, and `VelStopF = 16000.0f` clears `dq` and `kd`. Both leave `tau` unchanged. Hardware STOP uses a separate path. D2W wheel slots require `kp = 0`. Read the actuator limits from `rt/kinatric/robot_description` before building targets and use gains calibrated for the deployed robot.

1. Call `ReleaseMode()` from the SDK participant that will publish the low-level stream. Poll `CheckMode()` until `name` is empty.
2. Start the valid `LowCmd_` stream from a single writer. Confirm `controller=external`, the matching `authorization.participant`, and a populated `authorization.low_writer` in `control_state`.
3. To return control, keep the stream running during `SelectMode("normal")` and verify `CheckMode()` reports `name="normal"`. Stop publishing when the handover succeeds.

The deployment repository's test helper `tests/sdk/support/d2_client.py hold` is a 12-leg-axis hold. It takes position targets from the first CRC-checked `LowState_` sample it receives, accepts caller-supplied `--kp`, `--kd`, and `--seconds`, and publishes about every 5 ms. For D2W, use the robot description and a wheel-aware publisher when commanding the wheel axes.

### Motor Command Receipts

`rt/kinatric/lowcmd_receipt` carries `kinatric::LowCmdReceiptV1`. Join it with `rt/kinatric/external_lowcmd_origin` (`kinatric::ExternalLowCmdOriginV1`) on `owner`, `session_id`, and `tick` to trace an external command selected by the HAL. Origin data includes the participant, writer, grant epoch, and relay source timestamp. Use matching Kinatric generated types on the client and board.

| Receipt outcome | Meaning |
| - | - |
| `RECEIPT_APPLIED` | The HAL send path confirmed all requested actuator writes. Check the receipt deadline and HAL health separately. |
| `RECEIPT_PARTIAL` | The send result is known and fewer than all requested writes succeeded. `accepted_mask` can be zero. |
| `RECEIPT_REJECTED` | The HAL rejected the frame before starting actuator writes. |
| `RECEIPT_UNKNOWN` | Writes started, and the HAL could not determine which axes were sent. `accepted_mask` is zero because the result is unknown. |

`requested_mask`, `accepted_mask`, and the `applied` array use the Kinatric D2 motor slot order shown above. Inspect the corresponding `accepted_mask` bit before reading `applied[i]`. Compare `completed_ns` with `deadline_ns` to check timing, and use joint feedback to verify the resulting motion. Both HAL timestamps use the board's monotonic clock, while the origin's `relay_source_ns` is a board DDS timestamp.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.