Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/language-interop/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ Demonstrates controlling a dimos robot from non-Python languages.
- [TypeScript](ts/) - CLI and browser-based web UI
- [C++](cpp/)
- [Lua](lua/)
- [Rust](rust/)

3. (Optional) Monitor traffic with `lcmspy`

Expand Down
1 change: 1 addition & 0 deletions examples/language-interop/rust/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/target/
123 changes: 123 additions & 0 deletions examples/language-interop/rust/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 10 additions & 0 deletions examples/language-interop/rust/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
[package]
name = "robot-control"
version = "0.1.0"
edition = "2021"

[dependencies]
# TODO: switch to version once dimos-lcm#20 merges
dimos-lcm = { git = "https://github.com/dimensionalOS/dimos-lcm.git", rev = "474b25d0f9f88b8430753df2453fd2c988a514d1" }
# TODO: switch to version once dimos-lcm#20 merges
lcm-msgs = { git = "https://github.com/dimensionalOS/dimos-lcm.git", rev = "474b25d0f9f88b8430753df2453fd2c988a514d1" }
14 changes: 14 additions & 0 deletions examples/language-interop/rust/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# Rust Robot Control Example

Subscribes to `/odom` and publishes velocity commands to `/cmd_vel` via LCM UDP multicast.

## Build & Run

```bash
cargo run
```

## Dependencies

- [Rust toolchain](https://rustup.rs/)
- Message types fetched automatically from [dimos-lcm](https://github.com/dimensionalOS/dimos-lcm) (`rust-codegen` branch)
78 changes: 78 additions & 0 deletions examples/language-interop/rust/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// Rust robot control example
// Subscribes to robot pose and publishes twist commands via LCM

use dimos_lcm::Lcm;
use lcm_msgs::geometry_msgs::{PoseStamped, Twist, Vector3};
use std::thread;
use std::time::{Duration, Instant};

const ODOM_CHANNEL: &str = "/odom#geometry_msgs.PoseStamped";
const CMD_VEL_CHANNEL: &str = "/cmd_vel#geometry_msgs.Twist";
const PUBLISH_INTERVAL: Duration = Duration::from_millis(100); // 10 Hz

fn main() {
let lcm = Lcm::new().expect("Failed to create LCM transport");

println!("Robot control started");
println!("Subscribing to /odom, publishing to /cmd_vel");
println!("Press Ctrl+C to stop.\n");

let mut t: f64 = 0.0;
let mut next_publish = Instant::now();

loop {
// Poll for incoming messages
match lcm.try_recv() {
Ok(Some(msg)) if msg.channel == ODOM_CHANNEL => {
match PoseStamped::decode(&msg.data) {
Ok(pose) => {
let pos = &pose.pose.position;
let ori = &pose.pose.orientation;
println!(
"[pose] x={:.2} y={:.2} z={:.2} | qw={:.2}",
pos.x, pos.y, pos.z, ori.w
);
}
Err(e) => eprintln!("[pose] decode error: {e}"),
}
}
Ok(Some(_)) => {} // ignore other channels
Ok(None) => {}
Err(e) => eprintln!("recv error: {e}"),
}

// Publish twist at 10 Hz
let now = Instant::now();
if now >= next_publish {
let twist = Twist {
linear: Vector3 {
x: 0.5,
y: 0.0,
z: 0.0,
},
angular: Vector3 {
x: 0.0,
y: 0.0,
z: t.sin() * 0.3,
},
};

let data = twist.encode();
if let Err(e) = lcm.publish(CMD_VEL_CHANNEL, &data) {
eprintln!("[twist] publish error: {e}");
} else {
println!(
"[twist] linear={:.2} angular={:.2}",
twist.linear.x, twist.angular.z
);
}

t += 0.1;
next_publish = now + PUBLISH_INTERVAL;
}

// Sleep until next publish deadline (capped at 10ms) to avoid busy-spinning
let sleep_dur = next_publish.saturating_duration_since(Instant::now()).min(Duration::from_millis(10));
thread::sleep(sleep_dur);
}
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please delete.

Empty file.
146 changes: 146 additions & 0 deletions examples/language-interop/tests/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
# Copyright 2026 Dimensional Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Fixtures for language-interop integration tests."""

from __future__ import annotations

from collections.abc import Generator
import os
from pathlib import Path
import signal
import subprocess
import sys
import time

import pytest

EXAMPLES_DIR = Path(__file__).resolve().parent.parent # language-interop/
SIMPLEROBOT_DIR = EXAMPLES_DIR.parent / "simplerobot"
RUST_DIR = EXAMPLES_DIR / "rust"
TS_DIR = EXAMPLES_DIR / "ts"
CPP_DIR = EXAMPLES_DIR / "cpp"
LUA_DIR = EXAMPLES_DIR / "lua"


def pytest_configure(config: pytest.Config) -> None:
config.addinivalue_line("markers", "interop: cross-language interop integration test")


@pytest.fixture(scope="module")
def simplerobot() -> Generator[subprocess.Popen[str], None, None]:
"""Start simplerobot.py --headless as a subprocess, tear down after tests."""
proc = subprocess.Popen(
[sys.executable, str(SIMPLEROBOT_DIR / "simplerobot.py"), "--headless"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
text=True,
cwd=str(SIMPLEROBOT_DIR),
)
# Give it time to start publishing
time.sleep(2)
yield proc
proc.send_signal(signal.SIGTERM)
try:
proc.wait(timeout=5)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait(timeout=5)


@pytest.fixture(scope="module")
def rust_binary() -> Path:
"""Build the Rust interop binary and return its path."""
cargo_toml = RUST_DIR / "Cargo.toml"
if not cargo_toml.exists():
pytest.skip("Rust example not found")

env = os.environ.copy()
cargo_home = Path.home() / ".cargo" / "bin"
if cargo_home.is_dir():
env["PATH"] = str(cargo_home) + os.pathsep + env.get("PATH", "")

result = subprocess.run(
["cargo", "build", "--release"],
cwd=str(RUST_DIR),
capture_output=True,
text=True,
timeout=120,
env=env,
)
if result.returncode != 0:
pytest.skip(f"cargo build failed: {result.stderr}")

# Binary name from Cargo.toml [package] name = "robot-control"
binary = RUST_DIR / "target" / "release" / "robot-control"
if not binary.exists():
# Try to find any binary in release
release_dir = RUST_DIR / "target" / "release"
found = next(
(
f
for f in release_dir.iterdir()
if f.is_file() and os.access(f, os.X_OK) and not f.suffix and ".so" not in f.name
),
None,
)
if found is None:
pytest.skip("No binary found after cargo build")
binary = found

return binary


@pytest.fixture(scope="module")
def cpp_binary() -> Path:
"""Build the C++ interop binary and return its path."""
cmakelists = CPP_DIR / "CMakeLists.txt"
if not cmakelists.exists():
pytest.skip("C++ example not found")

build_dir = CPP_DIR / "build"
build_dir.mkdir(exist_ok=True)

cmake_result = subprocess.run(
["cmake", ".."],
cwd=str(build_dir),
capture_output=True,
text=True,
timeout=30,
)
if cmake_result.returncode != 0:
pytest.skip(f"cmake failed: {cmake_result.stderr}")

make_result = subprocess.run(
["make", "-j4"],
cwd=str(build_dir),
capture_output=True,
text=True,
timeout=60,
)
if make_result.returncode != 0:
pytest.skip(f"make failed: {make_result.stderr}")

# Find the built binary
binary = next(
(
f
for f in build_dir.iterdir()
if f.is_file() and os.access(f, os.X_OK) and not f.suffix and ".so" not in f.name
),
None,
)
if binary is None:
pytest.skip("No C++ binary found after build")
return binary
Loading