HDC-RS
A pure Rust implementation of the HarmonyOS Device Connector (HDC) client library, providing both async and blocking APIs for interacting with HarmonyOS/OpenHarmony devices.
Note: HDC is to HarmonyOS what ADB is to Android - a bridge for device communication, debugging, and development.
β¨ Features
- π Async/await - Built on Tokio for efficient async I/O
- π Blocking API - Synchronous wrapper for FFI bindings (PyO3, JNI, etc.)
- π± Device Management - List, connect, and monitor devices
- π» Shell Commands - Execute commands on devices with full output
- π Port Forwarding - TCP, Unix sockets, JDWP, and Ark debugger support
- π¦ App Management - Install/uninstall HAP and HSP packages
- π File Transfer - Efficient bidirectional file transfer with compression
- π Device Monitoring - Real-time device connection/disconnection events
- π Log Streaming - Continuous or buffered hilog reading
- π‘οΈ Type-safe API - Rust's type system ensures correctness
- β‘ Zero-copy - Efficient data handling with
bytescrate - π― Error Handling - Comprehensive error types with context
π Table of Contents
- Features
- Installation
- Quick Start
- Examples
- API Documentation
- Architecture
- Protocol Details
- Python Bindings
- API Reference
- Development
- Troubleshooting
- Performance
- Roadmap
- Contributing
- License
- Resources
π§ Installation
Prerequisites
- Rust 1.70 or later
- HDC server must be installed and running
- A HarmonyOS/OpenHarmony device connected via USB or network
Add to Your Project
Add this to your Cargo.toml:
[]
= "0.1"
= { = "1", = ["full"] }
Feature Flags
blocking- Enable synchronous/blocking API for FFI bindings
[]
= { = "0.1", = ["blocking"] }
π Quick Start
Async API (Recommended)
use HdcClient;
async
Blocking API (for FFI/PyO3)
Enable the blocking feature for synchronous API:
[]
= { = "0.1", = ["blocking"] }
use HdcClient;
π Examples
The repository includes several examples demonstrating different features:
| Example | Description | Command |
|---|---|---|
list_devices |
List all connected devices | cargo run --example list_devices |
simple_shell |
Interactive shell session | cargo run --example simple_shell |
blocking_demo |
Synchronous API demo | cargo run --example blocking_demo --features blocking |
device_monitor |
Monitor device connections | cargo run --example device_monitor |
file_demo |
File transfer operations | cargo run --example file_demo |
forward_demo |
Port forwarding setup | cargo run --example forward_demo |
app_demo |
App install/uninstall | cargo run --example app_demo |
hilog_demo |
Device log streaming | cargo run --example hilog_demo |
comprehensive |
All features combined | cargo run --example comprehensive |
Running Examples
# List all connected devices
# Blocking API demo (synchronous)
# Monitor device connections/disconnections
# Interactive shell
# File transfer demo
# Port forwarding demo
# App installation demo
# Hilog (device logs) demo
# Comprehensive example (all features)
# Enable debug logging for troubleshooting
RUST_LOG=hdc_rs=debug
π API Documentation
For detailed API documentation, visit docs.rs/hdc-rs.
Core Types
HdcClient- Main async client for HDC communicationblocking::HdcClient- Synchronous wrapper for FFI bindingsHdcError- Comprehensive error type with contextForwardNode- Port forwarding endpoint specificationInstallOptions/UninstallOptions- App management optionsFileTransferOptions- File transfer configuration
ποΈ Architecture
System Overview
βββββββββββββββββββ
β Your App β βββ Your Rust application
ββββββββββ¬βββββββββ
β (uses hdc-rs API)
βΌ
βββββββββββββββββββ
β hdc-rs β βββ This library (Rust)
β βββββββββββββ β
β β Client β β - Connection management
β β Protocol β β - Packet codec
β β Commands β β - Error handling
β βββββββββββββ β
ββββββββββ¬βββββββββ
β (TCP socket: 127.0.0.1:8710)
βΌ
βββββββββββββββββββ
β HDC Server β βββ Native HDC daemon
β (daemon) β
ββββββββββ¬βββββββββ
β (USB/TCP connection)
βΌ
βββββββββββββββββββ
β HarmonyOS β βββ Target device
β Device β
βββββββββββββββββββ
Project Structure
hdc-rs/
βββ hdc-rs/ # Core Rust library
β βββ src/
β β βββ lib.rs # Public API
β β βββ client.rs # HdcClient implementation
β β βββ blocking.rs # Synchronous wrapper
β β βββ error.rs # Error types
β β βββ app.rs # App management
β β βββ file.rs # File transfer
β β βββ forward.rs # Port forwarding
β β βββ protocol/ # Protocol implementation
β β βββ packet.rs # Packet codec
β β βββ command.rs # Command builders
β β βββ channel.rs # Channel management
β βββ Cargo.toml
βββ hdc-py/ # Python bindings (PyO3)
β βββ src/lib.rs
β βββ Cargo.toml
βββ examples/ # Usage examples
βββ tests/ # Integration tests
π Protocol Details
Packet Format
HDC uses a simple length-prefixed binary protocol over TCP:
ββββββββββββββββββββββββββββββββ
β 4 bytes: Payload Length β (Big-endian u32)
ββββββββββββββββββββββββββββββββ€
β N bytes: Payload Data β (Command + Arguments)
ββββββββββββββββββββββββββββββββ
Connection Lifecycle
Client Server
β β
βββββ TCP Connect ββββββββββββββ>β
β β
β<ββββ Handshake (Channel ID) ββββ€
β β
βββββ Connect Key ββββββββββββββ>β
β β
β<ββββ OK βββββββββββββββββββββββββ€
β β
βββββ Command ββββββββββββββββββ>β
β β
β<ββββ Response βββββββββββββββββββ€
β β
βββββ Close ββββββββββββββββββββ>β
β β
Supported Commands
| Command | Description | Status |
|---|---|---|
list targets |
List connected devices | β Implemented |
checkserver |
Get server version | β Implemented |
tmode port <port> |
Connect device over TCP | β Implemented |
shell <cmd> |
Execute shell command | β Implemented |
file send <local> <remote> |
Upload file | β Implemented |
file recv <remote> <local> |
Download file | β Implemented |
fport <local> <remote> |
Forward port | β Implemented |
rport <remote> <local> |
Reverse forward | β Implemented |
install <path> |
Install app | β Implemented |
uninstall <pkg> |
Uninstall app | β Implemented |
hilog |
Stream device logs | β Implemented |
wait-for-device |
Wait for device | β Implemented |
π Python Bindings
This project includes Python bindings built with PyO3. See hdc-py/README.md for complete documentation.
Quick Example
# Connect and list devices
=
=
# Execute command
=
Installation
# or
π API Reference
HdcClient
Main client for HDC communication.
Connection Methods
connect(address)- Connect to HDC serverclose()- Close connectionis_connected()- Check if connected
Device Management
list_targets()- List all connected devicesconnect_device(device_id)- Select a device for subsequent commandscheck_server()- Get server versionwait_for_device()- Block until a device is connectedmonitor_devices(interval, callback)- Monitor device list changes with pollinginterval: Polling interval (e.g.,Duration::from_secs(2))callback: Function called when device list changes, returnfalseto stop
Command Execution
shell(cmd)- Execute shell command on the currently selected device- Important: Must call
connect_device()first, or server will return error
- Important: Must call
shell_on_device(device_id, cmd)- Execute shell command on specific devicetarget_command(device_id, cmd)- Execute any command on specific device
Port Forwarding
fport(local, remote)- Forward local traffic to remote device- Example:
fport(ForwardNode::Tcp(8080), ForwardNode::Tcp(8081))
- Example:
rport(remote, local)- Reverse forward remote traffic to local host- Example:
rport(ForwardNode::Tcp(9090), ForwardNode::Tcp(9091))
- Example:
fport_list()- List all active forward/reverse tasksfport_remove(task_str)- Remove a forward task by task string- Example:
fport_remove("tcp:8080 tcp:8081")
- Example:
Forward Node Types:
ForwardNode::Tcp(port)- TCP portForwardNode::LocalFilesystem(path)- Unix domain socket (filesystem)ForwardNode::LocalReserved(name)- Unix domain socket (reserved)ForwardNode::LocalAbstract(name)- Unix domain socket (abstract)ForwardNode::Dev(name)- DeviceForwardNode::Jdwp(pid)- JDWP (Java Debug Wire Protocol, remote only)ForwardNode::Ark { pid, tid, debugger }- Ark debugger (remote only)
App Management
install(paths, options)- Install application package(s)paths: Single or multiple.hap/.hspfiles or directoriesoptions:InstallOptions::new().replace(true).shared(false)replace: Replace existing applicationshared: Install shared bundle for multi-apps
uninstall(package, options)- Uninstall application packagepackage: Package name (e.g.,"com.example.app")options:UninstallOptions::new().keep_data(true).shared(false)keep_data: Keep the data and cache directoriesshared: Remove shared bundle
Log Management
hilog(args)- Read device logs (buffered mode)args: Optional hilog arguments (e.g.,"-h"for help,"-t app"for app logs)- Returns all logs as a string after timeout
hilog_stream(args, callback)- Streaming hilog to given callback
File Transfer
file_send(local, remote, options)- Send file to devicelocal: Local file pathremote: Remote device pathoptions:FileTransferOptions- configure transfer behavior
file_recv(remote, local, options)- Receive file from deviceremote: Remote device pathlocal: Local file pathoptions:FileTransferOptions- configure transfer behavior
File Transfer Options:
hold_timestamp(bool)- Preserve file timestamps (-a)sync_mode(bool)- Only update if source is newer (-sync)compress(bool)- Compress during transfer (-z)mode_sync(bool)- Sync file permissions (-m)debug_dir(bool)- Transfer to/from debug app directory (-b)am device logs continuouslyargs: Optional hilog argumentscallback: Function called for each log chunk, returnfalseto stop streaming- Useful for real-time log monitoring
Usage Pattern
Option 1: Select device first (Recommended)
let mut client = connect.await?;
let devices = client.list_targets.await?;
// Connect to device - this re-establishes connection with device ID in handshake
client.connect_device.await?;
// Now shell commands will be routed to the selected device
let output = client.shell.await?;
Option 2: Specify device per command
let mut client = connect.await?;
let devices = client.list_targets.await?;
// Execute on specific device without selecting
let output = client.shell_on_device.await?;
Option 3: Port forwarding
use ;
let mut client = connect.await?;
let devices = client.list_targets.await?;
client.connect_device.await?;
// Forward local TCP 8080 to device TCP 8081
client.fport.await?;
// List all forwards
let tasks = client.fport_list.await?;
for task in tasks
// Remove forward
client.fport_remove.await?;
Option 4: App management
use ;
let mut client = connect.await?;
let devices = client.list_targets.await?;
client.connect_device.await?;
// Install app (replace if exists)
let opts = new.replace;
client.install.await?;
// Uninstall app (keep data)
let opts = new.keep_data;
client.uninstall.await?;
Option 5: Device logs (hilog)
use HdcClient;
let mut client = connect.await?;
let devices = client.list_targets.await?;
client.connect_device.await?;
// Get logs as buffered string
let logs = client.hilog.await?;
println!;
// Stream logs continuously
client.hilog_stream
Option 7: File transfer
use ;
let mut client = connect.await?;
let devices = client.list_targets.await?;
client.connect_device.await?;
// Send file to device with options
let opts = new
.hold_timestamp // Preserve timestamp
.compress; // Compress transfer
client.file_send.await?;
// Receive file from device
let opts = new.sync_mode;
client.file_recv.await?;
``` print!;
true // Continue streaming, return false to stop
}).await?;
Error Handling
All methods return Result<T, HdcError>. The library provides comprehensive error types:
use ;
match client.shell.await
Available Error Types:
NotConnected- Not connected to HDC serverTimeout- Operation timeoutDeviceNotFound- Target device not foundProtocolError- Protocol-level errorIoError- I/O error (network, file, etc.)InvalidResponse- Invalid server responseCommandFailed- Command execution failed
π» Development
βββββββββββββββββββββββ
β 4 bytes: length β (big-endian u32)
βββββββββββββββββββββββ€
β N bytes: data β
βββββββββββββββββββββββ
Channel Handshake
- Client connects to server
- Server sends handshake with channel ID
- Client responds with connect key
- Connection established
Current Status
Implemented β
- TCP connection management
- Packet codec (length-prefixed protocol)
- Channel handshake
- Basic commands:
list targets,shell,checkserver - Error handling
- Async/await support
Planned π§
- File transfer (
file send,file recv) - Port forwarding (
fport,rport) - App install/uninstall
- USB connection support
- Encryption (TLS-PSK)
Development
Prerequisites
- Rust 1.70 or later
- HDC server installed (from HarmonyOS SDK or OpenHarmony)
- A HarmonyOS/OpenHarmony device or emulator
Building from Source
# Clone the repository
# Build the project
# Build with release optimizations
# Build with all features
Running Tests
# Run all tests
# Run integration tests (requires HDC server running)
# Run specific test
Enable Debug Logging
Set the RUST_LOG environment variable for detailed logging:
# Linux/macOS
RUST_LOG=hdc_rs=debug
# Windows PowerShell
$env:RUST_LOG="hdc_rs=debug";
# Windows CMD
&&
Code Quality
# Format code
# Lint with Clippy
# Check without building
Documentation
# Generate and open documentation
# Generate documentation for all features
π Troubleshooting
Common Issues
"No devices found"
Solution:
- Ensure HDC server is running:
hdc start - Check device connection:
hdc list targets - Verify device is authorized (check device screen for authorization prompt)
- For network devices:
hdc tconn <device_ip>:5555
Connection timeout
Symptoms: HdcError::Timeout or connection hangs
Solution:
- Check if HDC server is listening on port 8710:
- Windows:
netstat -ano | findstr 8710 - Linux/macOS:
netstat -an | grep 8710orlsof -i :8710
- Windows:
- Restart HDC server:
hdc killthenhdc start - Check firewall settings
Protocol errors
Symptoms: HdcError::ProtocolError or unexpected responses
Solution:
- Ensure HDC server version compatibility (tested with 3.2.0+)
- Check server version:
hdc versionorclient.check_server().await? - Update HDC server to the latest version
- Enable debug logging to inspect protocol messages
File transfer fails
Symptoms: HdcError::IoError during file operations
Solution:
- Verify file paths are correct
- Check device storage permissions
- Ensure target directory exists on device
- For large files, increase timeout or use compression
"Device not authorized"
Solution:
- Check device for authorization dialog
- Revoke and re-authorize:
hdc kill-serverthen reconnect device - Check device developer options are enabled
Debug Tips
-
Enable verbose logging:
RUST_LOG=hdc_rs=trace -
Use the comprehensive example:
-
Check HDC server logs:
- Server logs are typically in the HDC installation directory
- Use
hdc -l 5for verbose HDC logging
-
Test with official HDC client:
If the official client works but hdc-rs doesn't, please file an issue.
π Performance
- Zero-copy parsing with
bytescrate - Async I/O with Tokio for efficient concurrency
- Connection pooling support (reuse connections)
- Streaming support for large file transfers and log streaming
Benchmarks
Typical performance on a modern system:
- Device listing: ~10-50ms
- Shell command: ~20-100ms (depends on command)
- File transfer: ~10-50 MB/s (depends on USB/network speed and device)
πΊοΈ Roadmap
Current Status (v0.1.0)
- β TCP connection management
- β Async/await API
- β Blocking API for FFI
- β Device management (list, connect, monitor)
- β Shell command execution
- β File transfer (send/recv)
- β Port forwarding (TCP, Unix sockets, JDWP, Ark)
- β App management (install/uninstall)
- β Log streaming (hilog)
- β Python bindings (PyO3)
π€ Contributing
Contributions are welcome! Here's how you can help:
Ways to Contribute
- π Report bugs - Open an issue with reproduction steps
- π‘ Suggest features - Share your ideas for improvements
- π Improve documentation - Fix typos, add examples, clarify usage
- π§ Submit pull requests - Fix bugs or implement new features
- β Star the project - Show your support!
Development Workflow
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Make your changes
- Run tests (
cargo test) - Run formatting (
cargo fmt) - Run linting (
cargo clippy) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Code Guidelines
- Follow Rust naming conventions and idioms
- Add tests for new functionality
- Update documentation for API changes
- Keep commits atomic and well-described
- Ensure all CI checks pass
Testing
# Run all tests
# Run specific test suite
# Run with verbose output
π License
This project is dual-licensed under:
- MIT License (LICENSE-MIT or http://opensource.org/licenses/MIT)
- Apache License 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
You may choose either license for your use.
π Acknowledgments
- HarmonyOS/OpenHarmony development tools team for HDC
- Tokio project for excellent async runtime
- PyO3 project for Rust-Python bindings
- Rust community for amazing tools and libraries
π Resources
Official Documentation
Related Projects
Community
- Report issues: GitHub Issues
- Discussions: GitHub Discussions
π Project Status
Version: 0.1.0
Status: Active Development
Stability: Beta
Made with β€οΈ by the HDC-RS contributors