惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Jina AI
Jina AI
博客园 - Franky
Apple Machine Learning Research
Apple Machine Learning Research
酷 壳 – CoolShell
酷 壳 – CoolShell
阮一峰的网络日志
阮一峰的网络日志
量子位
雷峰网
雷峰网
宝玉的分享
宝玉的分享
V
Visual Studio Blog
博客园_首页
小众软件
小众软件
The Cloudflare Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
大猫的无限游戏
大猫的无限游戏
博客园 - 聂微东
S
SegmentFault 最新的问题
博客园 - 【当耐特】
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 叶小钗
月光博客
月光博客
博客园 - 三生石上(FineUI控件)
人人都是产品经理
人人都是产品经理
WordPress大学
WordPress大学

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
USB Hotplug Detection in Rust on macOS — Reacting to Devi...
hiyoyo · 2026-06-18 · via DEV Community
Cover image for USB Hotplug Detection in Rust on macOS — Reacting to Device Connect/Disconnect

hiyoyo

All tests run on an 8-year-old MacBook Air. All results from shipping 7 Mac apps as a solo developer. No sponsored opinion.

HiyokoAutoSync and HiyokoMTP both react instantly when an Android device is connected. No polling. No "refresh" button. Just plug in and it works. Here's how USB hotplug detection works in Rust on macOS.


The approach: nusb hotplug API

nusb provides a hotplug watch API that wraps macOS's IOKit USB notifications:

use nusb::hotplug::{HotplugEvent, HotplugWatch};

fn watch_usb_devices(app_handle: AppHandle) {
    std::thread::spawn(move || {
        let watch = nusb::watch_devices().expect("Failed to start USB watch");

        for event in watch {
            match event {
                HotplugEvent::Connected(device_info) => {
                    if is_android_device(&device_info) {
                        app_handle.emit("device-connected", DeviceInfo {
                            name: device_info.product_string().unwrap_or_default(),
                            vendor_id: device_info.vendor_id(),
                            product_id: device_info.product_id(),
                        }).ok();
                    }
                }
                HotplugEvent::Disconnected(device_info) => {
                    if is_android_device(&device_info) {
                        app_handle.emit("device-disconnected", ()).ok();
                    }
                }
            }
        }
    });
}

The watch runs in a dedicated thread — it's a blocking iterator. Emit Tauri events to notify the frontend.


Identifying Android devices

Android devices have well-known vendor IDs. A non-exhaustive list:

const ANDROID_VENDOR_IDS: &[u16] = &[
    0x18D1, // Google
    0x04E8, // Samsung
    0x22D9, // OPPO/OnePlus
    0x2717, // Xiaomi
    0x12D1, // Huawei
    0x0BB4, // HTC
    0x1004, // LG
    0x0FCE, // Sony
];

fn is_android_device(info: &nusb::DeviceInfo) -> bool {
    ANDROID_VENDOR_IDS.contains(&info.vendor_id())
}

This catches most Android devices. ADB provides a more reliable check, but vendor ID filtering is fast and works before ADB connects.


ADB confirmation

After detecting a USB device with a known Android vendor ID, confirm with ADB:

async fn confirm_adb_device() -> bool {
    let output = Command::new("adb")
        .args(["devices", "-l"])
        .output()
        .await;

    match output {
        Ok(out) => {
            let stdout = String::from_utf8_lossy(&out.stdout);
            stdout.lines()
                .skip(1) // skip "List of devices attached"
                .any(|line| line.contains("device"))
        }
        Err(_) => false,
    }
}

Vendor ID for fast detection, ADB for confirmation. Two-step keeps the UX instant while ensuring accuracy.


The frontend experience

The user plugs in their Android device. Within 1-2 seconds:

  1. USB hotplug fires
  2. ADB confirms the device
  3. Frontend receives device-connected event
  4. UI updates to show the device and enable sync

No button. No refresh. It just works.


TL;DR: Use nusb::watch_devices() in a dedicated thread to get IOKit USB hotplug events on macOS. Filter by vendor ID for instant detection, then confirm with adb devices for accuracy. Emit Tauri events to the frontend — plug in and it works within 1-2 seconds, no refresh button needed.


If this was useful, a ❤️ helps more than you'd think — thanks!

HiyokoAutoSync | X → @hiyoyok