leejunyoung5819wayland-android-remote

공개

Ubuntu(Wayland/X11)에서 Android 기기 화면 미러링 및 원격 제어 (Rust)

265줄9.5 KB
1//! 기기 연결 점검 도구. GUI 없이 접속, 인증, PING 왕복, 영상 설정, 시스템 버튼을 확인한다.
2//!
3//! `cargo run --example probe -- 127.0.0.1:27200 [--key back|home|recents] [--record out.h264 --seconds 3]`
4//!
5//! `--record`를 주면 영상 채널로 받은 Annex-B 스트림을 파일로 저장한다(ffprobe/ffplay로 확인).
6//!
7//! 입력 주입 점검(좌표는 영상 프레임 기준, 주어진 순서대로 실행):
8//! `--tap x,y`, `--swipe x1,y1,x2,y2`, `--scroll x,y,v120`, `--text 문자열`, `--keycode N`, `--wait ms`
9//!
10//! GUI와 같은 PC 키(`~/.config/android-remote/device_key`)와 기기 지문 목록을 쓰므로,
11//! 여기서 허용된 PC는 GUI에서도 승인 없이 연결된다.
12
13use std::time::{Duration, Instant};
14
15use wayland_android_remote::net::{
16 ConnectOptions, FramedError, HostIdentity, KnownDevices, connect,
17};
18use wayland_android_remote::protocol::{
19 AuthGrant, CodecMask, Message, SystemAction, VideoConfigRequest, fingerprint_hex,
20};
21
22#[tokio::main]
23async fn main() -> Result<(), Box<dyn std::error::Error>> {
24 let args: Vec<String> = std::env::args().skip(1).collect();
25 let target = args
26 .first()
27 .ok_or("사용법: probe <IP:포트> [--key back|home|recents]")?;
28 let target = wayland_android_remote_target(target)?;
29 let key = args
30 .iter()
31 .position(|a| a == "--key")
32 .and_then(|i| args.get(i + 1))
33 .map(|k| match k.as_str() {
34 "back" => Ok(SystemAction::Back),
35 "home" => Ok(SystemAction::Home),
36 "recents" => Ok(SystemAction::Recents),
37 other => Err(format!("알 수 없는 키: {other}")),
38 })
39 .transpose()?;
40
41 let path = HostIdentity::default_path().ok_or("설정 디렉터리를 찾지 못했습니다")?;
42 let identity = HostIdentity::load_or_create(&path)?;
43 let mut known = KnownDevices::load_default();
44 let pinned = known.get(target.ip());
45 println!("접속: {target} (저장된 지문: {})", pinned.is_some());
46
47 let started = Instant::now();
48 let mut session = connect(target, &identity, pinned, ConnectOptions::default(), |e| {
49 println!(" {e:?}")
50 })
51 .await?;
52 println!(
53 "인증 완료 {:?}: grant={:?} daemon_version={} 지문={}",
54 started.elapsed(),
55 session.grant,
56 session.daemon_version,
57 fingerprint_hex(&session.fingerprint)
58 );
59 if session.grant == AuthGrant::Always {
60 known.insert(target.ip(), session.fingerprint)?;
61 }
62
63 let control = session.control();
64 for _ in 0..5 {
65 let t = Instant::now();
66 let seq = control.send(&Message::Ping).await?;
67 loop {
68 let (s, msg) = control.read_message().await?;
69 if s == seq && msg == Message::Pong {
70 break;
71 }
72 }
73 println!("PING 왕복 {:?}", t.elapsed());
74 }
75
76 control
77 .send(&Message::VideoConfigRequest(VideoConfigRequest {
78 max_size: 1920,
79 max_fps: 60,
80 codecs: CodecMask::H264 | CodecMask::H265,
81 bitrate: 8_000_000,
82 }))
83 .await?;
84 let reply = tokio::time::timeout(Duration::from_secs(3), control.read_message()).await??;
85 println!("영상 설정 응답: {:?}", reply.1);
86 let (fw, fh) = match &reply.1 {
87 Message::VideoConfig(c) => (c.width, c.height),
88 _ => (864, 1920),
89 };
90 run_input_ops(control, &args, fw, fh).await?;
91
92 if let Some(action) = key {
93 control.send(&Message::SystemAction(action)).await?;
94 println!("SYSTEM_ACTION {action:?} 전송");
95 }
96
97 let record = option(&args, "--record");
98 let seconds: u64 = option(&args, "--seconds")
99 .and_then(|s| s.parse().ok())
100 .unwrap_or(3);
101 if seconds == 0 {
102 return Ok(());
103 }
104 let mut video = session.open_video(Duration::from_secs(5)).await?;
105 let opened = Instant::now();
106 let mut file = record.map(std::fs::File::create).transpose()?;
107 let (mut frames, mut bytes, mut keyframes) = (0u64, 0u64, 0u64);
108 let mut first_frame = None;
109 let deadline = opened + Duration::from_secs(seconds);
110 loop {
111 let left = deadline.saturating_duration_since(Instant::now());
112 if left.is_zero() {
113 break;
114 }
115 match tokio::time::timeout(left, video.read_packet()).await {
116 Err(_) => break,
117 Ok(Ok((h, data))) => {
118 if let Some(f) = file.as_mut() {
119 std::io::Write::write_all(f, &data)?;
120 }
121 if h.is_config {
122 println!("CONFIG 패킷 gen={} {}바이트", h.config_gen, data.len());
123 continue;
124 }
125 first_frame.get_or_insert_with(|| opened.elapsed());
126 frames += 1;
127 bytes += data.len() as u64;
128 keyframes += u64::from(h.is_keyframe);
129 }
130 Ok(Err(FramedError::Closed)) => {
131 println!("영상 채널이 닫혔습니다");
132 break;
133 }
134 Ok(Err(e)) => {
135 println!("영상 채널 오류: {e}");
136 break;
137 }
138 }
139 }
140 let secs = seconds as f64;
141 println!(
142 "영상: 첫 프레임까지 {:?}, {frames}프레임({:.1}fps), 키프레임 {keyframes}, 평균 {:.2} Mbps",
143 first_frame,
144 frames as f64 / secs,
145 bytes as f64 * 8.0 / secs / 1e6
146 );
147 Ok(())
148}
149
150async fn run_input_ops(
151 control: &mut wayland_android_remote::net::FramedStream<
152 wayland_android_remote::net::DeviceStream,
153 >,
154 args: &[String],
155 fw: u16,
156 fh: u16,
157) -> Result<(), Box<dyn std::error::Error>> {
158 use wayland_android_remote::protocol::{
159 KeyAction, KeyEvent, TextInput, TouchAction, TouchEvent,
160 };
161 let touch = |action, x: u32, y: u32| {
162 Message::TouchEvent(TouchEvent {
163 action,
164 pointer_id: 0,
165 x,
166 y,
167 frame_width: fw,
168 frame_height: fh,
169 pressure: if action == TouchAction::Up { 0 } else { 0xFFFF },
170 })
171 };
172 let nums =
173 |s: &str| -> Vec<u32> { s.split(',').filter_map(|v| v.trim().parse().ok()).collect() };
174 let mut i = 0;
175 while i < args.len() {
176 let value = args.get(i + 1).map(String::as_str).unwrap_or("");
177 match args[i].as_str() {
178 "--tap" => {
179 let v = nums(value);
180 control.send(&touch(TouchAction::Down, v[0], v[1])).await?;
181 tokio::time::sleep(Duration::from_millis(60)).await;
182 control.send(&touch(TouchAction::Up, v[0], v[1])).await?;
183 println!("탭 {},{}", v[0], v[1]);
184 }
185 "--swipe" => {
186 let v = nums(value);
187 control.send(&touch(TouchAction::Down, v[0], v[1])).await?;
188 for step in 1..=15u32 {
189 tokio::time::sleep(Duration::from_millis(16)).await;
190 let x = v[0] as i64 + (v[2] as i64 - v[0] as i64) * step as i64 / 15;
191 let y = v[1] as i64 + (v[3] as i64 - v[1] as i64) * step as i64 / 15;
192 control
193 .send(&touch(TouchAction::Move, x as u32, y as u32))
194 .await?;
195 }
196 control.send(&touch(TouchAction::Up, v[2], v[3])).await?;
197 println!("스와이프 {value}");
198 }
199 "--scroll" => {
200 // x,y,v120 (양수 = 위로)
201 let v: Vec<i64> = value
202 .split(',')
203 .filter_map(|n| n.trim().parse().ok())
204 .collect();
205 control
206 .send(&Message::ScrollEvent(
207 wayland_android_remote::protocol::ScrollEvent {
208 x: v[0] as u32,
209 y: v[1] as u32,
210 frame_width: fw,
211 frame_height: fh,
212 h_scroll: 0,
213 v_scroll: v[2] as i16,
214 },
215 ))
216 .await?;
217 println!("스크롤 {value}");
218 }
219 "--text" => {
220 control
221 .send(&Message::TextInput(TextInput {
222 text: value.to_owned(),
223 }))
224 .await?;
225 println!("텍스트 {value:?}");
226 }
227 "--keycode" => {
228 let keycode: u16 = value.parse()?;
229 control
230 .send(&Message::KeyEvent(KeyEvent {
231 action: KeyAction::Click,
232 keycode,
233 meta_state: 0,
234 repeat: 0,
235 scancode: 0,
236 }))
237 .await?;
238 println!("키 {keycode}");
239 }
240 "--wait" => tokio::time::sleep(Duration::from_millis(value.parse()?)).await,
241 _ => {
242 i += 1;
243 continue;
244 }
245 }
246 i += 2;
247 }
248 Ok(())
249}
250
251fn option<'a>(args: &'a [String], name: &str) -> Option<&'a str> {
252 args.iter()
253 .position(|a| a == name)
254 .and_then(|i| args.get(i + 1))
255 .map(String::as_str)
256}
257
258fn wayland_android_remote_target(s: &str) -> Result<std::net::SocketAddr, String> {
259 if let Ok(a) = s.parse() {
260 return Ok(a);
261 }
262 s.parse::<std::net::IpAddr>()
263 .map(|ip| std::net::SocketAddr::new(ip, 27200))
264 .map_err(|_| format!("주소 형식 오류: {s}"))
265}