Merge pull request #156 from cocool97/mdns-feature

feat(mdns): add feature flag + example
This commit is contained in:
cocool97
2025-12-26 12:24:00 +01:00
committed by GitHub
14 changed files with 160 additions and 30 deletions

View File

@@ -36,10 +36,10 @@ jobs:
CRATES_IO_TOKEN: ${{ secrets.CRATES_IO_TOKEN }}
- name: Build release
run: cargo build --all-features --release
run: cargo build -p adb_cli --release
- name: Rename binary
run: mv target/release/adb_cli target/release/adb_cli-linux
run: cp target/release/adb_cli target/release/adb_cli-linux
- name: Build DEB package
run: cargo deb -p adb_cli
@@ -69,10 +69,10 @@ jobs:
override: true
- name: Build release
run: cargo build --all-features --release
run: cargo build -p adb_cli --release
- name: Rename binary
run: mv target/release/adb_cli target/release/adb_cli-macos
run: cp target/release/adb_cli target/release/adb_cli-macos
- name: Upload macOS binary
uses: softprops/action-gh-release@v2
@@ -98,7 +98,7 @@ jobs:
python-version: "3.10"
- name: Build release
run: cargo build --all-features --release
run: cargo build -p adb_cli --release
- name: Rename binary
run: Rename-Item -Path target/release/adb_cli.exe -NewName adb_cli-windows.exe

View File

@@ -1,5 +1,5 @@
[workspace]
members = ["adb_cli", "adb_client", "pyadb_client"]
members = ["adb_cli", "adb_client", "pyadb_client", "examples/mdns"]
resolver = "2"
[workspace.package]

View File

@@ -42,6 +42,12 @@ Rust library implementing both ADB protocols (server and end-devices) and provid
Improved documentation available [here](./adb_client/README.md).
## examples
Some examples showing of to use this library are available in the `examples` directory:
- `examples/mdns`: mDNS device discovery
## adb_cli
Rust binary providing an improved version of Google's official `adb` CLI, by using `adb_client` library.

View File

@@ -11,7 +11,7 @@ rust-version.workspace = true
version.workspace = true
[dependencies]
adb_client = { version = "^2.1.18" }
adb_client = { version = "^2.1.19", features = ["mdns"] }
clap = { version = "4.5.53", features = ["derive"] }
env_logger = { version = "0.11.8" }
log = { version = "0.4.29" }

View File

@@ -9,7 +9,7 @@ mod utils;
use adb_client::{
ADBDeviceExt, ADBListItemType, ADBServer, ADBServerDevice, ADBTcpDevice, ADBUSBDevice,
MDNSDiscoveryService,
mdns::MDNSDiscoveryService,
};
#[cfg(any(target_os = "linux", target_os = "macos"))]
@@ -184,9 +184,10 @@ fn inner_main() -> ADBCliResult<()> {
log::info!("Starting mdns discovery...");
while let Ok(device) = rx.recv() {
log::info!(
"Found device {} with addresses {:?}",
"Found device fullname='{}' with ipv4 addresses={:?} and ipv6 addresses={:?}",
device.fullname,
device.addresses
device.ipv4_addresses(),
device.ipv6_addresses()
);
}

View File

@@ -67,7 +67,7 @@ impl From<adb_client::RustADBError> for ADBCliError {
| RustADBError::PoisonError
| RustADBError::UpgradeError(_)
| RustADBError::MDNSError(_)
| RustADBError::SendError(_)
| RustADBError::SendError
| RustADBError::UnknownFileMode(_)
| RustADBError::UnknownTransport(_) => Self::MayNeedAnIssue(value),
// List of [`RustADBError`] that may occur in standard contexts and therefore do not require for issues

View File

@@ -10,6 +10,14 @@ repository.workspace = true
rust-version.workspace = true
version.workspace = true
[package.metadata.docs.rs]
all-features = true
rustdoc-args = ["--cfg", "docsrs"]
[features]
default = []
mdns = ["dep:mdns-sd"]
[dependencies]
base64 = { version = "0.22.1" }
bincode = { version = "2.0.1", features = ["serde"] }
@@ -17,9 +25,6 @@ byteorder = { version = "1.5.0" }
chrono = { version = "0.4.42", default-features = false, features = ["std"] }
image = { version = "0.25.9", default-features = false, features = ["png"] }
log = { version = "0.4.29" }
mdns-sd = { version = "0.17.1", default-features = false, features = [
"logging",
] }
num-bigint = { version = "0.8.6", package = "num-bigint-dig" }
num-traits = { version = "0.2.19" }
quick-protobuf = { version = "0.8.1" }
@@ -35,6 +40,13 @@ serde_repr = { version = "0.1.20" }
sha1 = { version = "0.10.6", features = ["oid"] }
thiserror = { version = "2.0.17" }
#########
# `mdns` feature-specific dependencies
mdns-sd = { version = "0.17.1", default-features = false, features = [
"logging",
], optional = true }
#########
[dev-dependencies]
anyhow = { version = "1.0.100" }
criterion = { version = "0.7.0" } # Used for benchmarks

View File

@@ -16,6 +16,19 @@ Add `adb_client` crate as a dependency by simply adding it to your `Cargo.toml`:
adb_client = "*"
```
## Crate features
| Feature | Description | Default? |
| :-----: | :---------------------------------------------: | :------: |
| `mdns` | Enables mDNS device discovery on local network. | No |
To deactivate some default features you can use the `default-features = false` option in your `Cargo.toml` file and manually specify the features you want to activate:
```toml
[dependencies]
adb_client = { version = "*", default-features = false, features = ["mdns"] }
```
## Benchmarks
Benchmarks run on `v2.0.6`, on a **Samsung S10 SM-G973F** device and an **Intel i7-1265U** CPU laptop
@@ -24,11 +37,11 @@ Benchmarks run on `v2.0.6`, on a **Samsung S10 SM-G973F** device and an **Intel
`ADBServerDevice` performs all operations by using adb server as a bridge.
|File size|Sample size|`ADBServerDevice`|`adb`|Difference|
|:-------:|:---------:|:----------:|:---:|:-----:|
|10 MB|100|350,79 ms|356,30 ms|<div style="color:green">-1,57 %</div>|
|500 MB|50|15,60 s|15,64 s|<div style="color:green">-0,25 %</div>|
|1 GB|20|31,09 s|31,12 s|<div style="color:green">-0,10 %</div>|
| File size | Sample size | `ADBServerDevice` | `adb` | Difference |
| :-------: | :---------: | :---------------: | :-------: | :------------------------------------: |
| 10 MB | 100 | 350,79 ms | 356,30 ms | <div style="color:green">-1,57 %</div> |
| 500 MB | 50 | 15,60 s | 15,64 s | <div style="color:green">-0,25 %</div> |
| 1 GB | 20 | 31,09 s | 31,12 s | <div style="color:green">-0,10 %</div> |
## Examples

View File

@@ -115,11 +115,13 @@ pub enum RustADBError {
#[error("upgrade error: {0}")]
UpgradeError(String),
/// An error occurred while getting mdns devices
#[cfg(feature = "mdns")]
#[cfg_attr(docsrs, doc(cfg(feature = "mdns")))]
#[error(transparent)]
MDNSError(#[from] mdns_sd::Error),
/// An error occurred while sending data to channel
#[error(transparent)]
SendError(#[from] std::sync::mpsc::SendError<crate::MDNSDevice>),
#[error("error sending data to channel")]
SendError,
/// An unknown transport has been provided
#[error("unknown transport: {0}")]
UnknownTransport(String),

View File

@@ -3,13 +3,23 @@
#![forbid(missing_debug_implementations)]
#![forbid(missing_docs)]
#![doc = include_str!("../README.md")]
// Feature `doc_cfg` is currently only available on nightly builds.
// It is activated when cfg `docsrs` is enabled.
// Documentation can be build locally using:
// `RUSTDOCFLAGS="--cfg docsrs" cargo +nightly doc --no-deps --all-features`
#![cfg_attr(docsrs, feature(doc_cfg))]
mod adb_device_ext;
mod constants;
mod device;
mod emulator_device;
mod error;
mod mdns;
/// MDNS-related definitions
#[cfg(feature = "mdns")]
#[cfg_attr(docsrs, doc(cfg(feature = "mdns")))]
pub mod mdns;
mod models;
mod server;
mod server_device;
@@ -20,7 +30,6 @@ pub use adb_device_ext::ADBDeviceExt;
pub use device::{ADBTcpDevice, ADBUSBDevice, is_adb_device, search_adb_devices};
pub use emulator_device::ADBEmulatorDevice;
pub use error::{Result, RustADBError};
pub use mdns::*;
pub use models::{ADBListItem, ADBListItemType, AdbStatResponse, RebootType};
pub use server::*;
pub use server_device::ADBServerDevice;

View File

@@ -1,4 +1,8 @@
use std::{collections::HashSet, net::IpAddr};
use std::{
collections::HashSet,
fmt::Display,
net::{IpAddr, Ipv4Addr, Ipv6Addr},
};
use mdns_sd::{ResolvedService, ScopedIp};
@@ -8,7 +12,41 @@ pub struct MDNSDevice {
/// Full device address when resolved
pub fullname: String,
/// Device IP addresses
pub addresses: HashSet<IpAddr>,
addresses: HashSet<IpAddr>,
}
impl MDNSDevice {
/// Return all adresses linked to this device
#[must_use]
pub fn addresses(&self) -> HashSet<IpAddr> {
self.addresses.clone()
}
/// Return all IPv4 addresses linked to this device
#[must_use]
pub fn ipv4_addresses(&self) -> HashSet<Ipv4Addr> {
self.addresses
.iter()
.filter_map(|addr| match addr {
IpAddr::V4(addr) => Some(addr),
IpAddr::V6(_) => None,
})
.copied()
.collect()
}
/// Return all IPv6 addresses linked to this device
#[must_use]
pub fn ipv6_addresses(&self) -> HashSet<Ipv6Addr> {
self.addresses
.iter()
.filter_map(|addr| match addr {
IpAddr::V4(_) => None,
IpAddr::V6(addr) => Some(addr),
})
.copied()
.collect()
}
}
impl From<Box<ResolvedService>> for MDNSDevice {
@@ -19,3 +57,13 @@ impl From<Box<ResolvedService>> for MDNSDevice {
}
}
}
impl Display for MDNSDevice {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "Device fullname: {}", self.fullname)?;
writeln!(f, "IPv4 Addresses: {:?}", self.ipv4_addresses())?;
write!(f, "IPv6 Addresses: {:?}", self.ipv6_addresses())?;
Ok(())
}
}

View File

@@ -1,7 +1,8 @@
use mdns_sd::{ServiceDaemon, ServiceEvent};
use std::{sync::mpsc::Sender, thread::JoinHandle};
use crate::{MDNSDevice, Result, RustADBError};
use super::MDNSDevice;
use crate::{Result, RustADBError};
const ADB_SERVICE_NAME: &str = "_adb-tls-connect._tcp.local.";
@@ -29,7 +30,7 @@ impl MDNSDiscoveryService {
})
}
/// Start discovery by spawning a new thread responsible of getting events.
/// Start discovery by spawning a new background thread responsible of getting events.
pub fn start(&mut self, sender: Sender<MDNSDevice>) -> Result<()> {
let receiver = self.daemon.browse(ADB_SERVICE_NAME)?;
@@ -44,9 +45,9 @@ impl MDNSDiscoveryService {
// Ignoring these events. We are only interesting in found devices
}
ServiceEvent::ServiceResolved(service_info) => {
if let Err(e) = sender.send(MDNSDevice::from(service_info)) {
return Err(e.into());
}
sender
.send(MDNSDevice::from(service_info))
.map_err(|_| RustADBError::SendError)?;
}
e => {
log::warn!("received unknown event type {e:?}");

19
examples/mdns/Cargo.toml Normal file
View File

@@ -0,0 +1,19 @@
[package]
name = "mdns"
authors.workspace = true
edition.workspace = true
homepage.workspace = true
keywords.workspace = true
license.workspace = true
repository.workspace = true
version.workspace = true
rust-version.workspace = true
[[bin]]
name = "mdns"
path = "main.rs"
[dependencies]
adb_client = { path = "../../adb_client", default-features = false, features = [
"mdns",
] }

19
examples/mdns/main.rs Normal file
View File

@@ -0,0 +1,19 @@
use std::sync::mpsc;
use adb_client::mdns::{MDNSDevice, MDNSDiscoveryService};
fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("Starting mDNS device discovery...");
// Create a channel to receive discovered devices information
let (sender, receiver) = mpsc::channel::<MDNSDevice>();
// Create and start the discovery service
let mut discovery = MDNSDiscoveryService::new()?;
discovery.start(sender)?;
loop {
let device = receiver.recv()?;
println!("{device}");
}
}