Metadata-Version: 2.4
Name: lekit-robot
Version: 0.6.0
Summary: Small Python SDK for observing and controlling Lekit Robot App
Project-URL: Repository, https://github.com/sorelferris/lekit-robot
Project-URL: Issues, https://github.com/sorelferris/lekit-robot/issues
Author: Sorel Ferris
License-Expression: Apache-2.0
License-File: LICENSE
Requires-Python: >=3.10
Requires-Dist: eclipse-zenoh<2,>=1.10
Requires-Dist: exceptiongroup<2,>=1.2; python_version < '3.11'
Requires-Dist: httpx<1,>=0.28
Requires-Dist: lz4<5,>=4.4
Requires-Dist: numpy<3,>=1.26
Requires-Dist: pillow<13,>=10
Requires-Dist: pydantic<3,>=2
Requires-Dist: rich<16,>=13.7
Requires-Dist: simplejpeg<2,>=1.9
Requires-Dist: typing-extensions<5,>=4.6
Requires-Dist: zstandard<1,>=0.23
Provides-Extra: images
Description-Content-Type: text/markdown

# lekit-robot

> `observation()` always includes body state and defaults to each camera's
> advertised image streams. Use `cameras="none"` for body-only reads or a mapping
> such as `cameras={"head_view": ["color", "depth"]}` for a specific selection.

Python SDK for a running **Lekit Robot App**, requiring Python 3.10+.
Each application owns its SDK, subscriptions and caches. There is no shared SDK
server. The client does not install Robot App, Web, LeRobot, Torch, OpenCV or
hardware drivers.

## Install

Install or upgrade the client from PyPI (Python 3.10+):

```sh
python -m pip install --upgrade lekit-robot
```

Protocol and transport implementations are included inside this SDK distribution.
No separate `lekit-robot-protocol` or `lekit-robot-transport` PyPI packages are required.

The default installation includes JPEG/PNG and LZ4/Zstandard decoding: NumPy,
Pillow, simplejpeg, lz4 and zstandard are installed together. `lekit-robot[images]`
remains accepted as a compatibility alias with the same capabilities.
Public camera observations return decoded NumPy arrays.

Build the single SDK distribution from the repository root:

```sh
uv build --package lekit-robot --out-dir /tmp/lekit-client-wheels
python -m pip install /tmp/lekit-client-wheels/lekit_robot-0.6.0-py3-none-any.whl
```

For editable development, use the repository workspace, which supplies the canonical
shared sources used by Robot App as well:

```sh
uv sync --all-packages
```

Robot App must already be running and advertise name discovery. Connect by its
configured robot name on the same LAN; no URL is needed. Zenoh multicast discovery
must be reachable. Routed VPNs or networks that block multicast are not discovered
automatically. A loopback-only App remains accessible only on its own host.
Updating SDK packages does not deploy or restart a robot.

## What's new in 0.6.0

- Connect to UR3 Dual and NERO with the same descriptor-driven client. UR3
  exposes six joints per arm; the client installs no robot hardware drivers.
- Control protocol 4 supports arrival waiting with `send_action(..., wait=True)`
  and confirmed holding with `stop(timeout=...)`; protocol 3 remains compatible.
- `observation()` defaults to all advertised cameras and latest samples. Use
  `cameras="none"` for body-only reads, `freshness="all"` to wait for new samples,
  and handle `None` on ordinary timeout. See [migration notes](CHANGELOG.md).

## UR3 Dual

Start the independent UR3 body service on the controller-side host first.
Then use the published client from another computer with network access:

```python
from lekit_robot import connect

with connect("ur3-dual") as robot:
    obs = robot.observation(cameras="none", freshness="all", timeout=2)
    if obs is not None and obs.robot.state is not None:
        state = obs.robot.state
        left = [state.get(f"left.joint_{i}") for i in range(1, 7)]
        right = [state.get(f"right.joint_{i}") for i in range(1, 7)]
        print(left, right)  # radians; no motion is sent by this example
```

Name discovery requires reachable LAN multicast. On a routed network, select the
body service explicitly: `connect(name="ur3-dual", url="http://BODY_HOST:8002",
transport="http")`. The URL selects the body service, not a robot controller.
The App owns the left/right controller mapping and motion limits.

After the operator enables motion on the App, the same API accepts absolute
six-joint targets, for example `robot.send_action({"left": {"joints": q_left},
"right": {"joints": q_right}}, wait=True, timeout=10)`. Targets are radians and
must satisfy the App's current limits. `robot.stop(timeout=3)` requests and waits
for a measured hold; it is not a mechanical emergency stop. UR3 does not acquire
NERO gripper or Cartesian capabilities by upgrading this client.

## What's new in 0.5.2

- Default installation includes all RGB/depth decoding dependencies.
- The legacy `[images]` extra remains a compatibility alias.

## What's new in 0.5.1

- Observation-source renewal and clock queries recover from transient timeouts
  while their previously confirmed validity bounds remain active.
- True expiry, identity changes and protocol errors still fail explicitly; late
  replies cannot revive expired or closed subscriptions. Observation freshness
  checks and motion-command retry behavior are unchanged.
- This patch preserves the 0.5.0 public API and needs no Robot App restart.

## What's new in 0.5.0

- The 0.5.0 release introduced a camera-name mapping to select color, depth or
  both and unified image decoding to arrays. Its default was body only.
- Quality checks are strict and timeouts raise; obsolete observation switches
  and invalid-cache timeout fallback are removed from the public method.
- `after=previous` and `freshness="all"` retain explicit new-sample semantics.
  `connect("robot name")` and advanced `DeviceObservations` remain available.
- Control receipt correlation and timeout handling are hardened without
  replaying uncertain actions or treating local submission as arrival.

The current source targets control protocol 4 and accepts protocol 3 compatibility connections.
Applications using the old server-aligned observation mode must migrate for
device-source operation. Full release notes are included as `CHANGELOG.md` in
the source distribution.

## Public application API

| Entry | Purpose |
| --- | --- |
| `connect("NERO Dual")` | Discover an App by name, verify its identity and register a control session without acquiring control |
| `robot.meta_info` | Read a copy of cached metadata; no network request |
| `robot.observation(...)` | Read selected observations and current control feedback |
| `robot.send_action(action, wait=False, timeout=10.0)` | Update the current absolute target; optionally wait for arrival |
| `robot.stop(timeout=2.0)` | Request stop and wait for confirmed hold |
| `robot.control` | Read cached control state, arrival and error information |
| `robot.close()` | Close resources; `with` does this automatically |
| `connect_devices(directory, ...)` | Explicit read-only subscriptions to a fixed set of sources |

```python
from lekit_robot import connect

with connect("NERO Dual") as robot:
    meta = robot.meta_info
    for _ in range(2):
        current = robot.observation(cameras="none", freshness="all", timeout=.5)
        if current is None:
            continue
        print(meta.manifest.robot_name, current.robot.state)
        print(current.quality.ages_s)
        print(current.control.feedback)
```

[basic_api.py](examples/basic_api.py) demonstrates the complete lifecycle. It
runs read-only unless an action file is supplied:

```sh
python packages/lekit_robot/examples/basic_api.py --name "NERO Dual"
```

The demo's observations read only the body and need no image extra.
Passing `--action-file target.json`
explicitly enables its control loop; `--steps` sets the number of iterations.
The loop targets 60 Hz but observation, computation and scheduling share that
budget. It does not treat local submission or a stop ID as physical completion.

For a finite, observation-only example, use [read_observation.py](examples/read_observation.py):

```sh
python packages/lekit_robot/examples/read_observation.py --name "NERO Dual" --mode body --count 5
python packages/lekit_robot/examples/read_observation.py --name "NERO Dual" --mode rgbd --camera head_view --count 5
```

Omit `--camera` to select all advertised cameras in image modes. This example
uses `freshness="all"` to wait for each selected source after the first read, reports
quality and per-source ages, and closes subscriptions automatically. Use
`--full-state` to print the complete body state dictionary.

### NERO gripper feedback

When provided by the Robot App, `left.gripper_feedback_fresh` and
`right.gripper_feedback_fresh` indicate whether the respective measured width
is valid and available. Read `left.gripper.pos` or `right.gripper.pos` only
when its flag is `True` and the key is present. The overall arm feedback may
remain fresh while gripper width is unavailable, for example when the device
reports an angle instead of a width. An older App may omit the dedicated flag;
do not infer a usable width from the overall arm flag alone.

### NERO joint torque

An updated NERO Robot App includes joint torque in the same body samples as
joint positions. The existing client reads it from `observation.robot.state`:

```python
with connect("NERO Dual") as robot:
    for _ in range(60):
        observation = robot.observation(cameras="none", freshness="all", timeout=.5)
        if observation is None:
            continue
        state = observation.robot.state or {}
        key = "left.joint_1"  # left/right, joint_1 through joint_7
        torque = state.get(key + ".torque")
        if state.get(key + ".torque_feedback_fresh"):
            print(state.get(key), torque, state["joint_torque.unit"])
```

`joint_torque.estimated=True` identifies the vendor SDK's current-derived
estimate in N·m, not a torque sensor or an external-contact torque measurement.
Each joint includes `.torque_feedback_timestamp_s` (device-host Unix receive
time), `.torque_feedback_age_s` (age when sampled), and `.torque_feedback_fresh`.
Missing, nonfinite, expired or disconnected feedback has no `.torque` value;
zero is a valid measurement. Torque freshness is independent of position and
the overall observation quality. Use the per-joint flag, and do not subtract
this device timestamp from a different host's clock.

Torque is read directly from the latest motor feedback on **every body sampling
cycle**, bypassing the slower diagnostic snapshot. It uses the existing body
stream, with no extra HTTP request or subscription. A 60 Hz body stream does not
guarantee 60 distinct torque readings if the motor feedback is slower; compare
the per-joint timestamps to detect updates. Deploying the server change is
required; installing the client alone cannot add absent server fields.

## Production discovery and process boundaries

`connect("NERO Dual")` queries the LAN discovery responders for that robot
name (trimmed and case-insensitive; other characters must match). It rejects
duplicate names and conflicting robot/instance identities instead of choosing
the first response. The announcement supplies `robot_id`, process instance,
generation and API addresses; the caller supplies no URL. Discovery is part of
each App process, not a central registry or an additional process.

The client reads `GET /api/robots/<robot-id>/manifest` at a discovered address,
with the ID encoded as one URL path segment. The unified manifest describes
identity, capabilities, sources and interfaces. It must match the discovery
announcement before the SDK registers a control session. An explicit
`mode="device-sources"` selects the production source architecture:

1. Project the source directory from `manifest.sources`, using the same
   manifest's embedded body identity; verify its manager, body instance and
   generation. This does not require separate directory and v1 manifest reads.
2. Establish the original App control backend. `auto` / `zenoh` read
   `/api/robots/<robot-id>/realtime` and verify the control identity; an explicit
   `endpoint=` changes that control endpoint, not the individual source addresses.
3. On the first `observation()`, connect directly to the selected body and camera
   sources. Validate each descriptor and clock bound, then combine in this process.

Robot App's public robot APIs use `/api/robots/<robot-id>/<api-name>`, including
configuration, diagnostics, observation and control. Schema versions remain in
payloads. `/api/robots/<robot-id>/legacy-manifest` exposes the old v1 body-only
contract; it is distinct from the unified `/manifest` document.

Only HTTP 404 during initial read-only discovery permits trying the older
`/api/device-manifest` and `/api/manifest/v2` aliases. If no unified manifest is
available, older services can use `/api/transport`, `/api/devices` and
`/api/manifest` as the compatibility description path. Invalid documents,
identity conflicts and non-404 responses do not select an older alias. Once the
robot-scoped API is verified, later reads and actions stay bound to that robot;
a missing scoped endpoint never downgrades to an unscoped default robot.

The body source runs inside Robot App beside local feedback sampling and control.
Each camera child owns its acquisition, RGB-D pairing, encoded cache, source
publisher and finite subscription leases. App manages their lifecycle and the
read-only directory; it does not default to receiving and rebroadcasting all images.
Source listening ports come from the directory and are not all port 7447.
Zenoh is the current replaceable network adapter; no router process is required.
Web uses a fixed App HTTP/WebSocket upstream. Its browser first reads the
Web-owned `/api/robots` list, then the selected robot's scoped manifest; this
single-upstream list is not automatic Fleet discovery. Previews connect directly
to the camera MJPG ports declared in the manifest. Those camera-owned endpoints
retain their own URLs. Web does not import this SDK or combine observations.

For compatibility or debugging, `connect(url="http://ROBOT_IP:8000")` explicitly
selects an API endpoint; adding `name="NERO Dual"` checks its name. A Web backend
that proxies the API is also valid, while a static UI server alone is not.
Neither omitted arguments nor failed name discovery fall back to localhost.
`endpoint=` overrides the control middleware endpoint after resolving the App;
it is not a robot-discovery address. HTTP-only or older Apps without the
`name_discovery` capability still require this explicit URL path.

With `transport="http"`, use `observation(cameras="none")` to read body state.
The default camera selection raises an error if the manifest advertises image
streams, because HTTP-only observation supports body state. `auto` falls back to
the original HTTP control backend only when realtime discovery returns
404; transport failures do not silently change routes or replay motion.
An App declaring `integrated-body`, or a legacy App without the new mode, keeps
its own advertised compatibility behavior. New static diagrams and SDK installs
are not evidence that a particular running App has been upgraded.

## Source subscription and observation contract

The public method accepts a camera selection, quality limits and new-sample controls:

```python
def observation(
    *,
    cameras="all",     # "all", "none", or a mapping of camera names to streams.
    timeout=3.0,
    max_age=None,      # None means .25 seconds; scalar or per-source mapping allowed.
    max_skew=None,     # No cross-source skew limit by default.
    after=None,
    freshness=None,   # None reads latest, "any"/"all" wait for new usable samples.
): ...
```

```python
with connect("NERO Dual") as robot:
    all_streams = robot.observation()
    body = robot.observation(cameras="none")
    rgb = robot.observation(cameras={"head_view": ["color"]})
    rgbd = robot.observation(cameras={"head_view": ["color", "depth"]})
    mixed = robot.observation(cameras={
        "head_view": ["color", "depth"],
        "left_view": ["color"],
    })
    if rgbd is not None:
        color = rgbd.camera("head_view").color
        if color is not None:
            print(color.shape)
```

The body is always included. `cameras="all"` is the default and requests the
nonempty stream list advertised by each camera in the manifest. A camera with no
advertised streams contributes no images. If no camera advertises any stream,
`"all"` reads body state only.

`cameras="none"`, `None`, and `{}` select body state only. A camera-name mapping
requests exactly the listed streams. Names must be unique in the manifest and
stream lists must be nonempty and supported by the camera. Requesting depth from
a camera without depth raises an error. Images are decoded NumPy arrays.

The legacy snapshot transport uses a single shared stream mask. It accepts a
common color-only or color-and-depth mask for all selected cameras. Per-camera
masks require `device-sources`.

For metadata-only, encoded-image, camera-only or other advanced source
workflows, use the separate `connect_devices()` / `DeviceObservations` interface
described below.

`observation()` returns an `Observation` or `None`. If the deadline expires
before the SDK can return a result, it returns `None`. Check this before
accessing fields and keep the previous `after` cursor when a call times out.
Identity and protocol errors and clock evidence expiring on its own still
raise.

`max_age` applies to each source separately. An over-age source keeps its
metadata and cursor, with its body state or camera color, depth and encoded
frames set to `None`. The result has `quality.valid=False`. A latest read can return only metadata
and cursors when all samples are over age. Check `quality.valid` if your
application requires all sources. The skew limit applies to usable samples only.

The following describes `connect()` against `device-sources`:

- One active source/stream selection is retained per client. Repeated calls reuse
  its subscriptions and bounded latest caches. Changing source or stream selection
  closes the old set before opening the new one. Image subscriptions remain active
  between calls until selection changes or the client closes; there is **no idle
  automatic unsubscribe**. Lost clients are bounded by source lease expiry.
- During subscription setup, the SDK retries transient `describe`, `clock` and
  `open` timeouts within the observation deadline. An `open` retry uses the
  same client ID and stream set to update the same lease. If the optional
  `latest` prefill times out, the SDK waits for the first sample from the
  subscription within the remaining time.
- If an observation lease expires, the public `observation()` call closes the
  affected source's scope and rebuilds its subscriber and lease within the call
  deadline. It checks the App's current directory when reachable, then verifies
  the same device, instance and generation at the source. It establishes a clock
  bound and waits for a fresh post-recovery sample. The selection and
  its logical cursors stay valid. If the deadline passes, the call returns
  `None` and the next call can retry. The control session uses its own path.
  The fixed-source `DeviceObservations` API continues to report lease expiry.
- With `max_skew=None`, cross-source skew is reported in `quality.skew_s`.
  Pass a limit in seconds, such as `max_skew=.05`, to require alignment.
- With `freshness=None` and no `after`, a call reads the latest available
  samples and can repeat a cached result. Set `freshness="any"` to wait for at
  least one selected source to deliver a new usable sample. Set `freshness="all"`
  to wait for a new usable sample from the body and every selected camera.
  The first call and changes in source or stream selection establish a baseline.
- Automatic freshness compares each source with the last usable sample delivered
  on this robot object, including latest reads and explicit `after` calls. The
  SDK keeps cursor metadata. A source whose data is set to `None` keeps its
  previous baseline, as does a timed-out call. Consumers of the same robot
  object share this progress.
- Pass `after=previous` to manage a separate cursor. The observation must come
  from this robot connection and the same source/stream selection. This
  compares the supplied source cursors, using `"any"` when `freshness` is omitted.
- Sources have independent identity, instance, generation, sequence and clock.
  RGB-D blocks belong to the same camera frameset. A different source identity,
  instance or generation requires a new connection.
- Only latest sampling is supported by this public method. Latest software combination is not hardware synchronization
  or a lossless recording API. There is no cross-device atomic configuration revision.
- Default maximum ages are 250 ms for body and cameras; maximum skew is 50 ms.
  Override all sources with `max_age=.2`, or use
  `max_age={"robot": .1, "camera": .2, "head_view": .15}` or source
  IDs, and `max_skew=.03`. Quality is checked again at delivery after decoding and
  management refresh. `timeout` also bounds subscription setup and serialized waits;
  it is not a hard realtime completion guarantee.
- For public `RemoteRobot.observation()` calls using `device-sources`,
  `DeviceObservation.sample_age_bounds_s` maps source IDs to `(lower, upper)`
  capture-to-delivery ages in seconds for usable samples in this result.
  `quality.ages_s` still reports capture-age upper bounds for quality checks.
  `receipt_ages_s` measures local time since receipt and `clock_uncertainty_s`
  reports clock interval width. Cross-domain skew uses conservative transformed
  intervals.
- The SDK uses its own send and receive timestamps and the source's
  `server_receive_ns` and `server_send_ns` from `/clock`. It supports older
  sources that only send `server_ns`, and combines up to eight recent compatible
  measurements per source. Bounds include a 1 ms allowance plus 100 ppm drift
  and expire after 10 seconds.
- When a packet is corrupt or an image fails to decode, the client marks that
  sample and waits for a new packet from the affected source. The observation
  deadline applies to that wait.
- Returned `source_cursors` and `source_calibrations` preserve per-source
  evidence. The explicit `connect_devices()` client also exposes its selected
  descriptors through `devices`. The body carries its sampled App config revision.
  Camera-only results from the explicit device API use zero rather than inventing a global revision. Metadata refresh happens
  during observation delivery when needed; property reads remain local.

The App's bounded HTTP/LOBS compatibility snapshots remain separate. Some old
services support server-side aligned/historical selection and idle stream release;
those semantics do not apply to device-source subscriptions. See the
[device API](../../docs/device-api.md),
[source contracts](../../docs/device-services-plan.md) and
[middleware contract](../../docs/realtime-middleware.md).

## Explicit read-only device API

`connect_devices()` accepts an App base URL or a `DeviceDirectory` snapshot.
For name-based discovery without a control session, obtain the unified manifest
with the SDK discovery helper and project its directory as shown below.
`connect_devices()` opens a fixed set of source subscriptions immediately and creates no control
session. Use the actual registered IDs; production body IDs are `body:<robot_id>`.

```python
from lekit_robot import connect_devices
from lekit_robot.discovery import discover_manifest

found = discover_manifest("NERO Dual")
directory = found.manifest.source_directory()
body_ids = tuple(entry.device.identity.device_id
                 for entry in directory.devices if entry.device.kind == "body")
with connect_devices(directory, source_ids=body_ids, streams=()) as sources:
    previous = sources.observation(images=False)
    current = sources.observation(after=previous, freshness="all", images=False, timeout=.5)
    print(current.robot.state, current.source_cursors)
```

`streams=()` creates no image demand. For this fixed-selection API,
`observation(images=False)` skips decoding but **does not change** already selected
image streams or release their leases. Choose streams when connecting and close
when finished. It has latest/after any/all quality checks but no timeout-reuse
option, actions or automatic re-registration after source replacement.

Reading the directory does not establish subscriptions or wake cameras. Established
subscriptions do not need directory HTTP on every frame. However, production App
owns body and camera lifetimes: App exit closes the body source and stops camera
children. The separate-manager simulation's sources surviving manager exit is
not a claim that production cameras survive App exit.

## Read-only diagnostics and examples

To show this SDK instance in `/monitor` → “观测链路”, explicitly enable
`robot.start_observation_diagnostics(label="policy")` after `connect("NERO Dual")`.
It reports bounded counters and timing summaries every two seconds over the
existing management session; enabling reporting does not start observations or
wake cameras. Continue calling `observation()` in your application.
`robot.observation_diagnostics()` reads a local snapshot and
`robot.stop_observation_diagnostics()` sends a final report on a best-effort basis
and stops reporting while the observation subscription continues. Closing the
robot also stops reporting. Updated Apps persist one completed report per client
key. The SDK uses the local hostname by default. Pass `client_key="mac/rgbd"`
to keep different workloads on the same machine separate. The display label and
live instance ID are independent of the archive key.
Requires the App's `observation_diagnostics.version=1` source-middleware capability.

```sh
python packages/lekit_robot/examples/diagnostics_observation.py --name "NERO Dual" --seconds 30 --mode rgbd
```

The flow view separates source capture/send from SDK receive/decode/return and
all-source advancement. Reports are client measurements, not server certification;
stale or absent reports are explicitly labeled. See
[observation diagnostics](../../docs/observation-observability.md) for clocks,
bounded windows, failure categories and cleanup semantics.

```sh
lekit-robot --help
python -m lekit_robot --help
lekit-robot --name "NERO Dual" --observation --mode robot --count 300
lekit-robot --name "NERO Dual" --observation --mode rgb --camera head_view
lekit-robot --name "NERO Dual" --observation --mode rgbd --verbose
python packages/lekit_robot/examples/benchmark_observation.py --name "NERO Dual" --mode robot --count 300
```

The benchmark example reads a warm-up observation to establish the baseline,
then uses `freshness="all"` to wait for a new usable sample from every selected
source. It reports return intervals, unique updates per source and gaps between
valid results separately.
It does not add a second 60 Hz sleep after waiting for the devices. Use
`--poll-latest --hz 60` only to measure periodic cache reads; repeated reads do
not demonstrate 60 Hz fresh delivery.

The CLI runs on the client computer and never sends motion. `--hz` sets the
application's target call rate, not the device capture rate. Source subscriptions
remain active between calls; each call does not create a new request/reply stream.
The default is 60 Hz and all configured RGB-D cameras. Choose `--mode robot` for
no image demand, or `rgb`/`rgbd` for decoded images (see the installation note for
released 0.5.1). These modes construct an
explicit camera/stream mapping after connection; `rgbd` requires both streams on
each selected camera. `--camera` accepts a name or ID and is repeatable; IDs are
resolved to unique camera names. Ctrl+C / SIGTERM closes the client; `--count` bounds calls.
The positional form `lekit-robot "NERO Dual" --observation` is also supported.
Provide a name or an explicit `--url`; there is no default local robot.

The dashboard reports return Hz, call percentiles, per-source updates and repeats,
failures, CPU and memory in a bounded three-second window. CPU 100%
is one core. Returned count and update Hz are not capture frequency, and repeats
are not proof of dropped frames. Diagnostic work adds overhead.

In device-source mode, displayed sample age is the SDK's capture-age upper bound.
Legacy selection-time differences are a separate metric. Optional
`--clocks-synchronized` enables client UTC minus source capture UTC estimates;
it is a user assertion, not automatic clock synchronization. Negative estimates
are labeled clock error and excluded from percentiles. Hardware CAN message age
is separate from the body snapshot age.

The CLI has no `encoded` or aligned-read mode. Public observation timeouts are
failures, not successful reused returns.
Its JSON labels source-mode age upper bounds separately from compatibility
selection-time age. Neither tool certifies stable 60 Hz or real robot stopping.

For a hardware-free transport rehearsal, the repository provides:

```sh
.venv/bin/python scripts/exercise-device-services.py --seconds 60 --cameras 3
```

Its separate simulated processes send pre-encoded frames. It does not validate
physical capture, per-frame encoding, hardware motion or another machine's network.

## Control and safety

The simplified control interface uses one current absolute target.

```python
robot.send_action(target)                         # Update without waiting for arrival.
robot.send_action(target, wait=True, timeout=10)  # Wait for this target to arrive.
robot.stop(timeout=2)                            # Wait for confirmed hold.
print(robot.control.state, robot.control.at_target, robot.control.error)
```

- `send_action()` returns an action ID after local enqueue. With `wait=True`, it
  returns that ID only after all selected parts report fresh, matching `reached`
  feedback. Rejection, replacement and execution failures raise an error.
- The arrival timeout requests a stop only while that target is still current,
  waits for hold confirmation, then raises `TimeoutError`. A failed hold is
  reported as unconfirmed and retains the device safety barrier. Stop confirmation
  has its own bounded wait, so the call can outlast the arrival timeout.
- Connecting registers a read-only session. The first accepted target acquires
  whole-robot control. Protocol 4 replaces the entire pending target frame;
  removed parts are held before the new selection dispatches. Physical writes to
  different arms still happen separately.
- Protocol 4 SDK and Web sessions send background heartbeats. The App declares
  the timeout, currently 2 seconds. Closing a session or missing its heartbeat
  revokes current work and requests measured-position hold. A connected client
  can keep a single target active without repeatedly sending it. Lost commands
  are never replayed on reconnection.
- Protocol 3 compatibility retains per-part coalescing and its original
  close/silence behavior. It does not provide protocol 4 disconnect protection.
- Targets are absolute. Joint/gripper fields and units come from metadata. Pose
  supports `{position, orientation, frame}` with an xyzw unit quaternion, or
  `{position, rpy, frame}`. IK, feedback freshness, limits, device generation and
  final dispatch authorization are enforced in Robot App.
- `robot.control` and `obs.control` are cached control snapshots with feedback
  receipt age. Feedback updates independently of observations and camera reads.
  `state`, `at_target` and `error` offer a compact view; `feedback` retains
  per-part evidence. The name `move` is reserved for future chassis movement.

See [CONTROL_PROTOCOL.md](CONTROL_PROTOCOL.md) and the complete
[basic_api.py](examples/basic_api.py) demo for control confirmation.
`get_observation`, iterators, explicit acquire/release and old target setters are
not public compatibility aliases. Use `observation`, `send_action`, `stop`,
`control` and `meta_info`. The wire namespace alone does not guarantee compatibility; upgrade
App and SDK together and reconnect after instance or generation changes.

## Distribution verification

Build/install the single SDK wheel, outside the source
workspace with no `PYTHONPATH`. Verify imports, both CLI help entry points, the
read-only demo, `connect()` and `connect_devices()` against an isolated Mock App.
The default installation must pass JPEG, PNG, LZ4 and Zstandard decode checks;
separately check that the legacy `[images]` spelling remains compatible. Package
installation and Mock checks do not imply deployment, real camera throughput or physical safety
acceptance. Publish only after separately verifying the intended registry/version;
this repository's source version is not automatically a released artifact.

Release builds package the canonical shared sources under `lekit_robot._vendor`
and relocate internal imports at build time. They neither install nor alias the
top-level shared modules used by Robot App. The sdist includes the shared source
and licenses and can rebuild without this repository. Use `lekit_robot` public
types in SDK applications; serialized protocol compatibility is retained, while
private bundled classes are not the same Python class objects as separately
loaded App classes. Editable workspace development continues to share App types.

License: Apache-2.0.
