hdc-rs 0.1.2

Rust client library for HarmonyOS Device Connector (HDC)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
# HDC-RS


[![Crates.io](https://img.shields.io/crates/v/hdc-rs.svg)](https://crates.io/crates/hdc-rs)
[![Documentation](https://docs.rs/hdc-rs/badge.svg)](https://docs.rs/hdc-rs)
[![License](https://img.shields.io/badge/license-MIT%2FApache--2.0-blue.svg)](LICENSE-MIT)
[![Rust Version](https://img.shields.io/badge/rust-1.70%2B-orange.svg)](https://www.rust-lang.org)

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 `bytes` crate
- 🎯 **Error Handling** - Comprehensive error types with context

## πŸ“‹ Table of Contents


- [Features]#-features
- [Installation]#-installation
- [Quick Start]#-quick-start
- [Examples]#-examples
- [API Documentation]#-api-documentation
- [Architecture]#️-architecture
- [Protocol Details]#-protocol-details
- [Python Bindings]#-python-bindings
- [API Reference]#-api-reference
- [Development]#-development
- [Troubleshooting]#-troubleshooting
- [Performance]#-performance
- [Roadmap]#️-roadmap
- [Contributing]#-contributing
- [License]#-license
- [Resources]#-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`:

```toml
[dependencies]
hdc-rs = "0.1"
tokio = { version = "1", features = ["full"] }
```

### Feature Flags


- `blocking` - Enable synchronous/blocking API for FFI bindings

```toml
[dependencies]
hdc-rs = { version = "0.1", features = ["blocking"] }
```

## πŸš€ Quick Start


### Async API (Recommended)


```rust
use hdc_rs::HdcClient;

#[tokio::main]

async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Connect to HDC server
    let mut client = HdcClient::connect("127.0.0.1:8710").await?;
    
    // List connected devices
    let devices = client.list_targets().await?;
    println!("Devices: {:?}", devices);
    
    if devices.is_empty() {
        println!("No devices connected!");
        return Ok(());
    }
    
    // Select and connect to first device
    client.connect_device(&devices[0]).await?;
    println!("Connected to device: {}", devices[0]);
    
    // Execute shell command on the selected device
    let output = client.shell("ls -l /data").await?;
    println!("Output:\n{}", output);
    
    Ok(())
}
```

### Blocking API (for FFI/PyO3)


Enable the `blocking` feature for synchronous API:

```toml
[dependencies]
hdc-rs = { version = "0.1", features = ["blocking"] }
```

```rust
use hdc_rs::blocking::HdcClient;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Connect to HDC server (synchronous!)
    let mut client = HdcClient::connect("127.0.0.1:8710")?;
    
    // List connected devices
    let devices = client.list_targets()?;
    println!("Devices: {:?}", devices);
    
    if !devices.is_empty() {
        // Connect and execute command
        client.connect_device(&devices[0])?;
        let output = client.shell("uname -a")?;
        println!("Output: {}", output);
    }
    
    Ok(())
}
```

## πŸ“š 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


```bash
# List all connected devices

cargo run --example list_devices

# Blocking API demo (synchronous)

cargo run --example blocking_demo --features blocking

# Monitor device connections/disconnections

cargo run --example device_monitor

# Interactive shell

cargo run --example simple_shell

# File transfer demo

cargo run --example file_demo

# Port forwarding demo

cargo run --example forward_demo

# App installation demo

cargo run --example app_demo

# Hilog (device logs) demo

cargo run --example hilog_demo

# Comprehensive example (all features)

cargo run --example comprehensive

# Enable debug logging for troubleshooting

RUST_LOG=hdc_rs=debug cargo run --example list_devices
```

## πŸ“– API Documentation


For detailed API documentation, visit [docs.rs/hdc-rs](https://docs.rs/hdc-rs).

### Core Types


- **`HdcClient`** - Main async client for HDC communication
- **`blocking::HdcClient`** - Synchronous wrapper for FFI bindings
- **`HdcError`** - Comprehensive error type with context
- **`ForwardNode`** - Port forwarding endpoint specification
- **`InstallOptions`** / **`UninstallOptions`** - App management options
- **`FileTransferOptions`** - 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`](hdc-py/README.md) for complete documentation.

### Quick Example


```python
from hdc_rs import HdcClient

# Connect and list devices

client = HdcClient("127.0.0.1:8710")
devices = client.list_targets()
print(f"Devices: {devices}")

if devices:
    # Execute command
    client.connect_device(devices[0])
    output = client.shell("uname -a")
    print(output)
```

### Installation


```bash
cd hdc-py
pip install maturin
maturin develop  # Development mode
# or

maturin build --release  # Build wheel
pip install target/wheels/hdc_rs-*.whl
```

## πŸ” API Reference


### HdcClient


Main client for HDC communication.

#### Connection Methods


- `connect(address)` - Connect to HDC server
- `close()` - Close connection
- `is_connected()` - Check if connected

#### Device Management


- `list_targets()` - List all connected devices
- `connect_device(device_id)` - Select a device for subsequent commands
- `check_server()` - Get server version
- `wait_for_device()` - Block until a device is connected
- `monitor_devices(interval, callback)` - Monitor device list changes with polling
  - `interval`: Polling interval (e.g., `Duration::from_secs(2)`)
  - `callback`: Function called when device list changes, return `false` to stop

#### Command Execution


- `shell(cmd)` - Execute shell command on the currently selected device
  - **Important**: Must call `connect_device()` first, or server will return error
- `shell_on_device(device_id, cmd)` - Execute shell command on specific device
- `target_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))`
- `rport(remote, local)` - Reverse forward remote traffic to local host
  - Example: `rport(ForwardNode::Tcp(9090), ForwardNode::Tcp(9091))`
- `fport_list()` - List all active forward/reverse tasks
- `fport_remove(task_str)` - Remove a forward task by task string
  - Example: `fport_remove("tcp:8080 tcp:8081")`

**Forward Node Types:**
- `ForwardNode::Tcp(port)` - TCP port
- `ForwardNode::LocalFilesystem(path)` - Unix domain socket (filesystem)
- `ForwardNode::LocalReserved(name)` - Unix domain socket (reserved)
- `ForwardNode::LocalAbstract(name)` - Unix domain socket (abstract)
- `ForwardNode::Dev(name)` - Device
- `ForwardNode::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`/`.hsp` files or directories
  - `options`: `InstallOptions::new().replace(true).shared(false)`
    - `replace`: Replace existing application
    - `shared`: Install shared bundle for multi-apps
- `uninstall(package, options)` - Uninstall application package
  - `package`: Package name (e.g., `"com.example.app"`)
  - `options`: `UninstallOptions::new().keep_data(true).shared(false)`
    - `keep_data`: Keep the data and cache directories
    - `shared`: 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 device
  - `local`: Local file path
  - `remote`: Remote device path
  - `options`: `FileTransferOptions` - configure transfer behavior
- `file_recv(remote, local, options)` - Receive file from device
  - `remote`: Remote device path
  - `local`: Local file path
  - `options`: `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 continuously
  - `args`: Optional hilog arguments
  - `callback`: Function called for each log chunk, return `false` to stop streaming
  - Useful for real-time log monitoring

### Usage Pattern


**Option 1: Select device first (Recommended)**
```rust
let mut client = HdcClient::connect("127.0.0.1:8710").await?;
let devices = client.list_targets().await?;

// Connect to device - this re-establishes connection with device ID in handshake
client.connect_device(&devices[0]).await?;

// Now shell commands will be routed to the selected device
let output = client.shell("ls /data").await?;
```

**Option 2: Specify device per command**
```rust
let mut client = HdcClient::connect("127.0.0.1:8710").await?;
let devices = client.list_targets().await?;

// Execute on specific device without selecting
let output = client.shell_on_device(&devices[0], "ls /data").await?;
```

**Option 3: Port forwarding**
```rust
use hdc_rs::{HdcClient, ForwardNode};

let mut client = HdcClient::connect("127.0.0.1:8710").await?;
let devices = client.list_targets().await?;
client.connect_device(&devices[0]).await?;

// Forward local TCP 8080 to device TCP 8081
client.fport(ForwardNode::Tcp(8080), ForwardNode::Tcp(8081)).await?;

// List all forwards
let tasks = client.fport_list().await?;
for task in tasks {
    println!("Forward: {}", task);
}

// Remove forward
client.fport_remove("tcp:8080 tcp:8081").await?;
```

**Option 4: App management**
```rust
use hdc_rs::{HdcClient, InstallOptions, UninstallOptions};

let mut client = HdcClient::connect("127.0.0.1:8710").await?;
let devices = client.list_targets().await?;
client.connect_device(&devices[0]).await?;

// Install app (replace if exists)
let opts = InstallOptions::new().replace(true);
client.install(&["app.hap"], opts).await?;

// Uninstall app (keep data)
let opts = UninstallOptions::new().keep_data(true);
client.uninstall("com.example.app", opts).await?;
```

**Option 5: Device logs (hilog)**
```rust
use hdc_rs::HdcClient;

let mut client = HdcClient::connect("127.0.0.1:8710").await?;
let devices = client.list_targets().await?;
client.connect_device(&devices[0]).await?;

// Get logs as buffered string
let logs = client.hilog(Some("-t app")).await?;
println!("App logs:\n{}", logs);

// Stream logs continuously
client.hilog_stream(None, |log_chunk| {
   

**Option 6: Monitor device connections**
```rust
use hdc_rs::HdcClient;
use std::time::Duration;

let mut client = HdcClient::connect("127.0.0.1:8710").await?;

// Wait for any device to connect (blocks until a device is available)
let device = client.wait_for_device().await?;
println!("Device connected: {}", device);

// Monitor device list changes in real-time
client.monitor_devices(Duration::from_secs(2), |devices| {
    println!("Device list updated: {} device(s)", devices.len());
    for device in devices {
        println!("  - {}", device);
    }
    true // Continue monitoring, return false to stop
}).await?;
```

**Option 7: File transfer**
```rust
use hdc_rs::{HdcClient, FileTransferOptions};

let mut client = HdcClient::connect("127.0.0.1:8710").await?;
let devices = client.list_targets().await?;
client.connect_device(&devices[0]).await?;

// Send file to device with options
let opts = FileTransferOptions::new()
    .hold_timestamp(true)   // Preserve timestamp
    .compress(true);         // Compress transfer
client.file_send("local.txt", "/data/local/tmp/remote.txt", opts).await?;

// Receive file from device
let opts = FileTransferOptions::new().sync_mode(true);
client.file_recv("/data/local/tmp/remote.txt", "local.txt", opts).await?;
``` print!("{}", log_chunk);
    true // Continue streaming, return false to stop
}).await?;
```

### Error Handling


All methods return `Result<T, HdcError>`. The library provides comprehensive error types:

```rust
use hdc_rs::{HdcClient, HdcError};

match client.shell("ls").await {
    Ok(output) => println!("{}", output),
    Err(HdcError::NotConnected) => eprintln!("Not connected to HDC server!"),
    Err(HdcError::Timeout) => eprintln!("Command timeout!"),
    Err(HdcError::DeviceNotFound) => eprintln!("Device not found!"),
    Err(HdcError::ProtocolError(msg)) => eprintln!("Protocol error: {}", msg),
    Err(e) => eprintln!("Error: {}", e),
}
```

**Available Error Types:**
- `NotConnected` - Not connected to HDC server
- `Timeout` - Operation timeout
- `DeviceNotFound` - Target device not found
- `ProtocolError` - Protocol-level error
- `IoError` - I/O error (network, file, etc.)
- `InvalidResponse` - Invalid server response
- `CommandFailed` - Command execution failed

## πŸ’» Development


```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ 4 bytes: length     β”‚ (big-endian u32)
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ N bytes: data       β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

### Channel Handshake


1. Client connects to server
2. Server sends handshake with channel ID
3. Client responds with connect key
4. 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


```bash
# Clone the repository

git clone https://github.com/oslo254804746/hdc-rs.git
cd hdc-rs

# Build the project

cargo build

# Build with release optimizations

cargo build --release

# Build with all features

cargo build --all-features
```

### Running Tests


```bash
# Run all tests

cargo test

# Run integration tests (requires HDC server running)

cargo test --test integration_test

# Run specific test

cargo test test_name
```

### Enable Debug Logging


Set the `RUST_LOG` environment variable for detailed logging:

```bash
# Linux/macOS

RUST_LOG=hdc_rs=debug cargo run --example list_devices

# Windows PowerShell

$env:RUST_LOG="hdc_rs=debug"; cargo run --example list_devices

# Windows CMD

set RUST_LOG=hdc_rs=debug && cargo run --example list_devices
```

### Code Quality


```bash
# Format code

cargo fmt

# Lint with Clippy

cargo clippy -- -D warnings

# Check without building

cargo check
```

### Documentation


```bash
# Generate and open documentation

cargo doc --open

# Generate documentation for all features

cargo doc --all-features --no-deps --open
```

## πŸ› 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 8710` or `lsof -i :8710`
- Restart HDC server: `hdc kill` then `hdc 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 version` or `client.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-server` then reconnect device
- Check device developer options are enabled

### Debug Tips


1. **Enable verbose logging:**
   ```bash
   RUST_LOG=hdc_rs=trace cargo run --example your_example

   ```

2. **Use the comprehensive example:**
   ```bash
   cargo run --example comprehensive

   ```

3. **Check HDC server logs:**
   - Server logs are typically in the HDC installation directory
   - Use `hdc -l 5` for verbose HDC logging

4. **Test with official HDC client:**
   ```bash
   hdc list targets

   hdc shell ls /data

   ```
   If the official client works but hdc-rs doesn't, please file an issue.

## πŸ“Š Performance


- **Zero-copy parsing** with `bytes` crate
- **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


1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Make your changes
4. Run tests (`cargo test`)
5. Run formatting (`cargo fmt`)
6. Run linting (`cargo clippy`)
7. Commit your changes (`git commit -m 'Add amazing feature'`)
8. Push to the branch (`git push origin feature/amazing-feature`)
9. 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


```bash
# Run all tests

cargo test

# Run specific test suite

cargo test --lib
cargo test --test integration_test

# Run with verbose output

cargo test -- --nocapture
```

## πŸ“„ License


This project is dual-licensed under:

- **MIT License** ([LICENSE-MIT]LICENSE-MIT or http://opensource.org/licenses/MIT)
- **Apache License 2.0** ([LICENSE-APACHE]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


- [HDC Official Docs]https://gitee.com/openharmony/developtools_hdc
- [HarmonyOS Developer Portal]https://developer.harmonyos.com/
- [OpenHarmony Documentation]https://docs.openharmony.cn/

### Related Projects


- [hdc-rs on crates.io]https://crates.io/crates/hdc-rs
- [hdc-rs documentation]https://docs.rs/hdc-rs
- [GitHub Repository]https://github.com/oslo254804746/hdc-rs

### Community


- Report issues: [GitHub Issues]https://github.com/oslo254804746/hdc-rs/issues
- Discussions: [GitHub Discussions]https://github.com/oslo254804746/hdc-rs/discussions

## πŸ“ˆ Project Status


![Build Status](https://img.shields.io/github/actions/workflow/status/oslo254804746/hdc-rs/ci.yml?branch=main)
![License](https://img.shields.io/badge/license-MIT%2FApache--2.0-blue.svg)
![Rust Version](https://img.shields.io/badge/rust-1.70%2B-orange.svg)

**Version:** 0.1.0  
**Status:** Active Development  
**Stability:** Beta

---

Made with ❀️ by the HDC-RS contributors