Skip to main content

ptzcam_mcp/
lib.rs

1//! ptzcam-mcp — PTZ camera control MCP server.
2//!
3//! Drives a PTZ camera over two transports:
4//!   - V4L2 pan/tilt/zoom controls on the video node (e.g. /dev/video2)
5//!   - Sony VISCA over serial (ttyUSB) or VISCA-over-IP (TCP)
6//!
7//! Tools:
8//!   - ptzcam_status                  overall state: transports, position, ranges
9//!   - ptzcam_v4l2_status             V4L2 position + ranges for one device
10//!   - ptzcam_v4l2_move               absolute pan/tilt/zoom over V4L2
11//!   - ptzcam_visca_inquiry           power / zoom / pan-tilt / version
12//!   - ptzcam_visca_pan_tilt          absolute or relative pan-tilt move
13//!   - ptzcam_visca_drive             continuous directional drive (arrow keys)
14//!   - ptzcam_visca_zoom              absolute zoom or tele/wide/stop
15//!   - ptzcam_visca_focus             far / near / auto / manual / absolute
16//!   - ptzcam_visca_home              go home
17//!   - ptzcam_visca_reset             pan-tilt reset
18//!   - ptzcam_visca_preset            set / recall / clear a preset
19//!   - ptzcam_visca_power             power on / off / status
20//!   - ptzcam_visca_raw               raw VISCA frame exchange
21//!   - ptzcam_calibrate_probe         calibration: probe one axis and return
22//!   - ptzcam_move_dir                logical move (up/down/left/right/zoom) via calibration
23
24pub mod calibration;
25pub mod transport;
26pub mod v4l2;
27pub mod visca;
28
29pub use transport::ViscaTransport;
30
31use std::sync::Arc;
32
33use anyhow::Result;
34use rmcp::{
35    ServerHandler,
36    handler::server::{router::tool::ToolRouter, wrapper::Parameters},
37    model::{ServerCapabilities, ServerInfo},
38    schemars, tool, tool_handler, tool_router,
39};
40use crate::v4l2::ControlBackend;
41use serde::{Deserialize, Serialize};
42
43/// Server configuration, from environment with sensible defaults.
44#[derive(Debug, Clone)]
45struct Config {
46    v4l2_device: String,
47    serial_port: String,
48    serial_baud: u32,
49    ip_host: Option<String>,
50    ip_port: u16,
51    calibration_path: std::path::PathBuf,
52}
53
54impl Config {
55    fn from_env() -> Self {
56        Self {
57            v4l2_device: std::env::var("PTZCAM_V4L2_DEVICE").unwrap_or_else(|_| "/dev/video2".into()),
58            serial_port: std::env::var("PTZCAM_SERIAL_PORT").unwrap_or_else(|_| "/dev/ttyUSB0".into()),
59            serial_baud: std::env::var("PTZCAM_SERIAL_BAUD").ok().and_then(|s| s.parse().ok()).unwrap_or(9600),
60            ip_host: std::env::var("PTZCAM_IP_HOST").ok().filter(|s| !s.is_empty()),
61            ip_port: std::env::var("PTZCAM_IP_PORT").ok().and_then(|s| s.parse().ok()).unwrap_or(52381),
62            calibration_path: std::env::var("PTZCAM_CALIBRATION")
63                .map(std::path::PathBuf::from)
64                .unwrap_or_else(|_| {
65                    std::env::var("HOME")
66                        .map(|h| std::path::PathBuf::from(h).join(".config/ptzcam-mcp/calibration.json"))
67                        .unwrap_or_else(|_| std::path::PathBuf::from("calibration.json"))
68                }),
69        }
70    }
71}
72
73pub struct PtzcamServer {
74    #[allow(dead_code)] // read by the rmcp tool router at serve time
75    tool_router: ToolRouter<Self>,
76    config: Config,
77    /// One shared serial connection, opened lazily on first use. VISCA tools
78    /// multiplex through it under a mutex: the camera's CH341 dongle cannot
79    /// cope with concurrent opens, so per-call connections collide.
80    serial: Arc<tokio::sync::Mutex<Option<transport::SerialTransport>>>,
81}
82
83impl PtzcamServer {
84    pub fn new() -> Self {
85        Self {
86            tool_router: Self::tool_router(),
87            config: Config::from_env(),
88            serial: Arc::new(tokio::sync::Mutex::new(None)),
89        }
90    }
91
92    /// Open the V4L2 backend for the configured device.
93    fn v4l2(&self) -> anyhow::Result<v4l2::V4l2Backend> {
94        v4l2::V4l2Backend::open(&self.config.v4l2_device)
95            .map_err(|e| anyhow::anyhow!("open {}: {e}", self.config.v4l2_device))
96    }
97
98    /// Send one VISCA frame and return the reply data. Serial connections are
99    /// reused via the shared mutex (opened lazily); IP connections are made
100    /// per call.
101    async fn visca_cmd(&self, transport: &str, frame: &[u8]) -> anyhow::Result<Vec<u8>> {
102        match transport {
103            "ip" => {
104                let host = self
105                    .config
106                    .ip_host
107                    .clone()
108                    .ok_or_else(|| anyhow::anyhow!("VISCA over IP not configured; set PTZCAM_IP_HOST"))?;
109                let mut t = transport::IpTransport::connect(&host, self.config.ip_port).await?;
110                t.command(frame).await
111            }
112            _ => {
113                let mut guard = self.serial.lock().await;
114                if guard.is_none() {
115                    *guard = Some(transport::SerialTransport::open(
116                        &self.config.serial_port,
117                        self.config.serial_baud,
118                    )?);
119                }
120                guard.as_mut().unwrap().command(frame).await
121            }
122        }
123    }
124}
125
126fn err_json(e: &anyhow::Error) -> String {
127    serde_json::json!({ "error": e.to_string() }).to_string()
128}
129
130// ---------------------------------------------------------------------------
131// Tool input types
132// ---------------------------------------------------------------------------
133
134#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
135struct EmptyRequest {}
136
137#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
138struct V4l2MoveRequest {
139    /// Absolute pan position in V4L2 units (device range, e.g. -612000..612000). Omit to leave unchanged.
140    pan: Option<i64>,
141    /// Absolute tilt position in V4L2 units (e.g. -324000..324000). Omit to leave unchanged.
142    tilt: Option<i64>,
143    /// Absolute zoom position in V4L2 units (e.g. 5..750). Omit to leave unchanged.
144    zoom: Option<i64>,
145    /// Pan speed (1..=24, V4L2 pan speed control). Optional.
146    pan_speed: Option<i64>,
147    /// Tilt speed (1..=24, V4L2 tilt speed control). Optional.
148    tilt_speed: Option<i64>,
149}
150
151#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
152struct ViscaBaseRequest {
153    /// Which inquiry to run: power, zoom, pan_tilt, or version.
154    kind: String,
155    /// VISCA camera address 1..=7 (default 1).
156    address: Option<u8>,
157    /// Transport: "serial" (default) or "ip" (requires PTZCAM_IP_HOST).
158    transport: Option<String>,
159}
160
161#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
162struct ViscaPanTiltRequest {
163    /// Move mode: "absolute" (default) or "relative".
164    mode: Option<String>,
165    /// Pan speed 1..=24 (default 12).
166    pan_speed: Option<u8>,
167    /// Tilt speed 1..=24 (default 12).
168    tilt_speed: Option<u8>,
169    /// Target pan position (absolute) or offset (relative), 16-bit signed.
170    pan: i16,
171    /// Target tilt position (absolute) or offset (relative), 16-bit signed.
172    tilt: i16,
173    /// VISCA camera address 1..=7 (default 1).
174    address: Option<u8>,
175    /// Transport: "serial" (default) or "ip".
176    transport: Option<String>,
177}
178
179#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
180struct ViscaZoomRequest {
181    /// Zoom mode: "absolute" (20-bit value), "tele", "wide", or "stop".
182    mode: String,
183    /// Zoom position for mode "absolute" (0..0xFFFFF, camera-dependent scale).
184    zoom: Option<u32>,
185    /// VISCA camera address 1..=7 (default 1).
186    address: Option<u8>,
187    /// Transport: "serial" (default) or "ip".
188    transport: Option<String>,
189}
190
191#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
192struct ViscaPresetRequest {
193    /// Operation: "set", "recall", or "clear".
194    op: String,
195    /// Preset number 0..=255 (most cameras support 0..=5 or 0..=9).
196    preset: u8,
197    /// VISCA camera address 1..=7 (default 1).
198    address: Option<u8>,
199    /// Transport: "serial" (default) or "ip".
200    transport: Option<String>,
201}
202
203#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
204struct ViscaPowerRequest {
205    /// "on", "off", or "status" (default status).
206    action: Option<String>,
207    /// VISCA camera address 1..=7 (default 1).
208    address: Option<u8>,
209    /// Transport: "serial" (default) or "ip".
210    transport: Option<String>,
211}
212
213#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
214struct ViscaAddrRequest {
215    /// VISCA camera address 1..=7 (default 1).
216    address: Option<u8>,
217    /// Transport: "serial" (default) or "ip".
218    transport: Option<String>,
219}
220
221#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
222struct ViscaDriveRequest {
223    /// Direction to move: "up", "down", "left", "right", or a diagonal
224    /// "upleft", "upright", "downleft", "downright"; "stop" halts immediately.
225    direction: String,
226    /// Pan speed 1..=24 (default 12).
227    pan_speed: Option<u8>,
228    /// Tilt speed 1..=24 (default 12).
229    tilt_speed: Option<u8>,
230    /// How long to hold the drive in milliseconds (default 300). The camera
231    /// stops automatically afterwards.
232    duration_ms: Option<u64>,
233    /// VISCA camera address 1..=7 (default 1).
234    address: Option<u8>,
235    /// Transport: "serial" (default) or "ip".
236    transport: Option<String>,
237}
238
239#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
240struct ViscaFocusRequest {
241    /// Focus action: "far", "near", "stop", "auto", "manual", or "absolute".
242    action: String,
243    /// Focus position for action "absolute" (20-bit, camera-dependent scale).
244    focus: Option<u32>,
245    /// VISCA camera address 1..=7 (default 1).
246    address: Option<u8>,
247    /// Transport: "serial" (default) or "ip".
248    transport: Option<String>,
249}
250
251#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
252struct CalibrateProbeRequest {
253    /// Control to probe: "pan", "tilt", or "zoom".
254    control: String,
255    /// Direction: 1 (increase the control value) or -1 (decrease it).
256    direction: i64,
257    /// How far to move in device units (default: 100000 for pan/tilt, 100 for zoom).
258    amount: Option<i64>,
259    /// Pan/tilt speed 1..=24 (default 12).
260    speed: Option<i64>,
261}
262
263#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
264struct MoveDirRequest {
265    /// Logical direction: up, down, left, right, zoom_in, zoom_out, or a
266    /// diagonal (upleft, upright, downleft, downright). Uses the calibration
267    /// file to map to the correct control and sign.
268    direction: String,
269    /// How far to move in device units (default: 80000 for pan/tilt, 50 for zoom).
270    amount: Option<i64>,
271    /// Pan/tilt speed 1..=24 (default 12).
272    speed: Option<i64>,
273    /// Calibration file path (default: $HOME/.config/ptzcam-mcp/calibration.json
274    /// or the PTZCAM_CALIBRATION env var).
275    calibration: Option<String>,
276}
277
278#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
279struct ViscaRawRequest {
280    /// Raw VISCA command frame as hex bytes without the 0xFF terminator,
281    /// e.g. "81010604" for pan-tilt home.
282    frame: String,
283    /// VISCA camera address 1..=7 (default 1; only used when frame has no header).
284    address: Option<u8>,
285    /// Transport: "serial" (default) or "ip".
286    transport: Option<String>,
287}
288
289// ---------------------------------------------------------------------------
290// Tools
291// ---------------------------------------------------------------------------
292
293#[tool_router]
294impl PtzcamServer {
295    /// Overall camera state.
296    #[tool(description = "Report the PTZ camera server state: which transports are configured (V4L2 device, VISCA serial port, VISCA over IP), the current V4L2 pan/tilt/zoom position with ranges, and whether the serial port exists. Call this first to learn what is available before issuing move commands.")]
297    async fn ptzcam_status(&self, Parameters(_req): Parameters<EmptyRequest>) -> String {
298        let mut pos = None;
299        let mut ranges = None;
300        let mut v4l2_err = None;
301        match self.v4l2() {
302            Ok(mut b) => {
303                pos = v4l2::read_position(&mut b).ok();
304                ranges = v4l2::read_ranges(&mut b).ok();
305            }
306            Err(e) => v4l2_err = Some(e.to_string()),
307        }
308        serde_json::json!({
309            "v4l2_device": self.config.v4l2_device,
310            "v4l2_open_error": v4l2_err,
311            "position": pos,
312            "ranges": ranges,
313            "serial_port": self.config.serial_port,
314            "serial_baud": self.config.serial_baud,
315            "serial_port_exists": std::path::Path::new(&self.config.serial_port).exists(),
316            "visca_ip": self.config.ip_host.as_ref().map(|h| format!("{h}:{}", self.config.ip_port)),
317        })
318        .to_string()
319    }
320
321    /// V4L2 position and ranges.
322    #[tool(description = "Read the current pan/tilt/zoom position and the device ranges from the V4L2 video node. Values are in V4L2 control units (for this camera: pan roughly -612000..612000, tilt -324000..324000, zoom 5..750). Use for monitoring before deciding a move.")]
323    async fn ptzcam_v4l2_status(&self, Parameters(_req): Parameters<EmptyRequest>) -> String {
324        let mut b = match self.v4l2() {
325            Ok(b) => b,
326            Err(e) => return err_json(&e),
327        };
328        match v4l2::read_position(&mut b) {
329            Ok(pos) => {
330                let ranges = v4l2::read_ranges(&mut b).unwrap_or(serde_json::json!({}));
331                serde_json::json!({ "device": self.config.v4l2_device, "position": pos, "ranges": ranges }).to_string()
332            }
333            Err(e) => err_json(&anyhow::anyhow!("read V4L2 position: {e}")),
334        }
335    }
336
337    /// Absolute V4L2 move.
338    #[tool(description = "Move the camera to an absolute pan/tilt/zoom position over V4L2. Provide only the axes to change; each value is clamped to the device range. Optional pan_speed/tilt_speed (1..=24) set the V4L2 speed controls. Waits briefly for the motors to settle, then returns the resulting position read back from the device.")]
339    async fn ptzcam_v4l2_move(&self, Parameters(req): Parameters<V4l2MoveRequest>) -> String {
340        let mut b = match self.v4l2() {
341            Ok(b) => b,
342            Err(e) => return err_json(&e),
343        };
344        let result = v4l2::move_absolute(
345            &mut b,
346            req.pan,
347            req.tilt,
348            req.zoom,
349            req.pan_speed,
350            req.tilt_speed,
351        );
352        if result.is_err() {
353            return err_json(&anyhow::anyhow!("V4L2 move failed: {}", result.unwrap_err()));
354        }
355        // The pan/tilt motors take a moment to reach the target; the control
356        // read-back reflects the current position, so settle before reporting.
357        tokio::time::sleep(std::time::Duration::from_millis(800)).await;
358        match v4l2::read_position(&mut b) {
359            Ok(pos) => serde_json::json!({ "ok": true, "position": pos }).to_string(),
360            Err(e) => err_json(&anyhow::anyhow!("read position after move: {e}")),
361        }
362    }
363
364    /// VISCA inquiry.
365    #[tool(description = "Run a read-only VISCA inquiry over serial or IP. kind: 'power' (on/off), 'zoom' (current zoom position), 'pan_tilt' (current pan/tilt), 'version' (model and version). Returns the parsed value plus the raw response bytes.")]
366    async fn ptzcam_visca_inquiry(&self, Parameters(req): Parameters<ViscaBaseRequest>) -> String {
367        let addr = req.address.unwrap_or(1);
368        let frame = match req.kind.as_str() {
369            "power" => visca::inq_power(addr),
370            "zoom" => visca::inq_zoom(addr),
371            "pan_tilt" => visca::inq_pan_tilt(addr),
372            "version" => visca::inq_version(addr),
373            other => return err_json(&anyhow::anyhow!("unknown inquiry kind '{other}'; use power, zoom, pan_tilt or version")),
374        };
375        match self.visca_cmd(req.transport.as_deref().unwrap_or("serial"), &frame).await {
376            Ok(data) => {
377                let parsed = match req.kind.as_str() {
378                    "power" => serde_json::json!({ "power": visca::parse_power(&data) }),
379                    "zoom" => serde_json::json!({ "zoom": visca::parse_zoom20(&data) }),
380                    "pan_tilt" => match visca::parse_pan_tilt(&data) {
381                        Some((pan, tilt)) => serde_json::json!({ "pan": pan, "tilt": tilt }),
382                        None => serde_json::json!({}),
383                    },
384                    _ => serde_json::json!({}),
385                };
386                serde_json::json!({
387                    "ok": true,
388                    "kind": req.kind,
389                    "raw_hex": hex(&data),
390                    "parsed": parsed,
391                })
392                .to_string()
393            }
394            Err(e) => err_json(&e),
395        }
396    }
397
398    /// VISCA pan-tilt move.
399    #[tool(description = "Move pan/tilt over VISCA. mode 'absolute' (default) moves to a position; mode 'relative' applies offsets. pan/tilt are 16-bit signed values; pan_speed/tilt_speed 1..=24 (default 12). Returns the raw completion plus the new position from a follow-up inquiry.")]
400    async fn ptzcam_visca_pan_tilt(&self, Parameters(req): Parameters<ViscaPanTiltRequest>) -> String {
401        let addr = req.address.unwrap_or(1);
402        let ps = req.pan_speed.unwrap_or(12).clamp(1, 24);
403        let ts = req.tilt_speed.unwrap_or(12).clamp(1, 24);
404        let frame = match req.mode.as_deref().unwrap_or("absolute") {
405            "absolute" => visca::pan_tilt_absolute(addr, ps, ts, req.pan, req.tilt),
406            "relative" => visca::pan_tilt_relative(addr, ps, ts, req.pan, req.tilt),
407            other => return err_json(&anyhow::anyhow!("unknown mode '{other}'; use absolute or relative")),
408        };
409        let transport = req.transport.as_deref().unwrap_or("serial");
410        match self.visca_cmd(transport, &frame).await {
411            Ok(data) => {
412                // confirm with an inquiry
413                let inq = match self.visca_cmd(transport, &visca::inq_pan_tilt(addr)).await {
414                    Ok(d) => visca::parse_pan_tilt(&d).map(|(p, t)| serde_json::json!({ "pan": p, "tilt": t })),
415                    Err(_) => None,
416                };
417                serde_json::json!({ "ok": true, "completion_hex": hex(&data), "position": inq }).to_string()
418            }
419            Err(e) => err_json(&e),
420        }
421    }
422
423    /// VISCA zoom.
424    #[tool(description = "Control zoom over VISCA. mode 'absolute' sets a 20-bit zoom position (zoom param); 'tele' zooms in, 'wide' zooms out, 'stop' halts. Returns the raw completion and the current zoom from an inquiry.")]
425    async fn ptzcam_visca_zoom(&self, Parameters(req): Parameters<ViscaZoomRequest>) -> String {
426        let addr = req.address.unwrap_or(1);
427        let frame = match req.mode.as_str() {
428            "absolute" => match req.zoom {
429                Some(z) => visca::zoom_absolute(addr, z & 0xFFFFF),
430                None => return err_json(&anyhow::anyhow!("mode 'absolute' requires a zoom value")),
431            },
432            "tele" => visca::zoom_speed(addr, 0x02),
433            "wide" => visca::zoom_speed(addr, 0x03),
434            "stop" => visca::zoom_speed(addr, 0x00),
435            other => return err_json(&anyhow::anyhow!("unknown mode '{other}'; use absolute, tele, wide or stop")),
436        };
437        let transport = req.transport.as_deref().unwrap_or("serial");
438        match self.visca_cmd(transport, &frame).await {
439            Ok(data) => {
440                let inq = match self.visca_cmd(transport, &visca::inq_zoom(addr)).await {
441                    Ok(d) => visca::parse_zoom20(&d).map(|z| serde_json::json!({ "zoom": z })),
442                    Err(_) => None,
443                };
444                serde_json::json!({ "ok": true, "completion_hex": hex(&data), "zoom": inq }).to_string()
445            }
446            Err(e) => err_json(&e),
447        }
448    }
449
450    /// VISCA home.
451    #[tool(description = "Send the camera to its home position (pan/tilt center) over VISCA.")]
452    async fn ptzcam_visca_home(&self, Parameters(req): Parameters<ViscaAddrRequest>) -> String {
453        let addr = req.address.unwrap_or(1);
454        match self.visca_cmd(req.transport.as_deref().unwrap_or("serial"), &visca::pan_tilt_home(addr)).await {
455            Ok(data) => serde_json::json!({ "ok": true, "completion_hex": hex(&data) }).to_string(),
456            Err(e) => err_json(&e),
457        }
458    }
459
460    /// VISCA preset.
461    #[tool(description = "Manage pan/tilt/zoom presets over VISCA. op 'set' stores the current position, 'recall' moves to a stored preset, 'clear' removes it. preset is the preset number (0..=255; camera-dependent, commonly 0..=5).")]
462    async fn ptzcam_visca_preset(&self, Parameters(req): Parameters<ViscaPresetRequest>) -> String {
463        let addr = req.address.unwrap_or(1);
464        let op = match req.op.as_str() {
465            "set" => visca::PresetOp::Set,
466            "recall" => visca::PresetOp::Recall,
467            "clear" => visca::PresetOp::Clear,
468            other => return err_json(&anyhow::anyhow!("unknown op '{other}'; use set, recall or clear")),
469        };
470        match self.visca_cmd(req.transport.as_deref().unwrap_or("serial"), &visca::preset(addr, op, req.preset)).await {
471            Ok(data) => serde_json::json!({ "ok": true, "op": req.op, "preset": req.preset, "completion_hex": hex(&data) }).to_string(),
472            Err(e) => err_json(&e),
473        }
474    }
475
476    /// VISCA power.
477    #[tool(description = "Control camera power over VISCA. action 'on' powers the camera, 'off' powers it down, 'status' (default) reports whether it is on. Returns the power state.")]
478    async fn ptzcam_visca_power(&self, Parameters(req): Parameters<ViscaPowerRequest>) -> String {
479        let addr = req.address.unwrap_or(1);
480        let transport = req.transport.as_deref().unwrap_or("serial");
481        let action = req.action.as_deref().unwrap_or("status");
482        let frame = match action {
483            "on" => visca::power(addr, true),
484            "off" => visca::power(addr, false),
485            "status" => visca::inq_power(addr),
486            other => return err_json(&anyhow::anyhow!("unknown action '{other}'; use on, off or status")),
487        };
488        match self.visca_cmd(transport, &frame).await {
489            Ok(data) => {
490                let on = visca::parse_power(&data);
491                serde_json::json!({ "ok": true, "action": action, "power_on": on, "raw_hex": hex(&data) }).to_string()
492            }
493            Err(e) => err_json(&e),
494        }
495    }
496
497    /// VISCA raw frame.
498    #[tool(description = "Send a raw VISCA command frame as hex (without the 0xFF terminator) and return the raw completion bytes. Use for commands the structured tools do not cover. Example: '81010604' sends pan-tilt home.")]
499    async fn ptzcam_visca_raw(&self, Parameters(req): Parameters<ViscaRawRequest>) -> String {
500        let payload = match hex_decode(&req.frame) {
501            Ok(b) => b,
502            Err(e) => return err_json(&e),
503        };
504        if payload.is_empty() || payload.len() > 16 {
505            return err_json(&anyhow::anyhow!("frame must be 1..=16 bytes of hex"));
506        }
507        let addr = req.address.unwrap_or(1);
508        let frame = visca::frame(addr, &payload);
509        match self.visca_cmd(req.transport.as_deref().unwrap_or("serial"), &frame).await {
510            Ok(data) => serde_json::json!({ "ok": true, "tx_hex": hex(&frame), "completion_hex": hex(&data) }).to_string(),
511            Err(e) => err_json(&e),
512        }
513    }
514
515    /// VISCA pan-tilt drive (remote arrow buttons).
516    #[tool(description = "Drive the camera continuously in a direction, like the remote's arrow buttons: up, down, left, right, or a diagonal (upleft, upright, downleft, downright). The camera moves for duration_ms (default 300) at the given speeds and then stops automatically. Pass direction 'stop' to halt an in-progress move immediately.")]
517    async fn ptzcam_visca_drive(&self, Parameters(req): Parameters<ViscaDriveRequest>) -> String {
518        let addr = req.address.unwrap_or(1);
519        let ps = req.pan_speed.unwrap_or(12).clamp(1, 24);
520        let ts = req.tilt_speed.unwrap_or(12).clamp(1, 24);
521        let dir = match req.direction.as_str() {
522            "stop" => visca::DIR_STOP,
523            "up" => visca::DIR_UP,
524            "down" => visca::DIR_DOWN,
525            "left" => visca::DIR_LEFT,
526            "right" => visca::DIR_RIGHT,
527            "upleft" => visca::DIR_UP | visca::DIR_LEFT,
528            "upright" => visca::DIR_UP | visca::DIR_RIGHT,
529            "downleft" => visca::DIR_DOWN | visca::DIR_LEFT,
530            "downright" => visca::DIR_DOWN | visca::DIR_RIGHT,
531            other => return err_json(&anyhow::anyhow!("unknown direction '{other}'; use up, down, left, right, diagonals, or stop")),
532        };
533        let transport = req.transport.as_deref().unwrap_or("serial");
534        let start = visca::pan_tilt_drive(addr, ps, ts, dir);
535        let stop = visca::pan_tilt_drive(addr, 0, 0, visca::DIR_STOP);
536        if let Err(e) = self.visca_cmd(transport, &start).await {
537            return err_json(&e);
538        }
539        let duration = if req.direction == "stop" { 0 } else { req.duration_ms.unwrap_or(300).min(5000) };
540        if duration > 0 {
541            tokio::time::sleep(std::time::Duration::from_millis(duration)).await;
542        }
543        match self.visca_cmd(transport, &stop).await {
544            Ok(data) => serde_json::json!({
545                "ok": true,
546                "direction": req.direction,
547                "duration_ms": duration,
548                "completion_hex": hex(&data),
549            })
550            .to_string(),
551            Err(e) => err_json(&e),
552        }
553    }
554
555    /// VISCA focus.
556    #[tool(description = "Control focus over VISCA, matching the remote's Far/Near/Auto buttons: 'far' moves focus outward, 'near' inward, 'stop' halts, 'auto' enables autofocus, 'manual' disables it, 'absolute' sets a 20-bit focus position (focus param).")]
557    async fn ptzcam_visca_focus(&self, Parameters(req): Parameters<ViscaFocusRequest>) -> String {
558        let addr = req.address.unwrap_or(1);
559        let frame = match req.action.as_str() {
560            "far" => visca::focus_far_near(addr, 0x02),
561            "near" => visca::focus_far_near(addr, 0x03),
562            "stop" => visca::focus_far_near(addr, 0x00),
563            "auto" => visca::focus_auto_manual(addr, true),
564            "manual" => visca::focus_auto_manual(addr, false),
565            "absolute" => match req.focus {
566                Some(f) => visca::focus_absolute(addr, f & 0xFFFFF),
567                None => return err_json(&anyhow::anyhow!("action 'absolute' requires a focus value")),
568            },
569            other => return err_json(&anyhow::anyhow!("unknown action '{other}'; use far, near, stop, auto, manual or absolute")),
570        };
571        match self.visca_cmd(req.transport.as_deref().unwrap_or("serial"), &frame).await {
572            Ok(data) => serde_json::json!({ "ok": true, "action": req.action, "completion_hex": hex(&data) }).to_string(),
573            Err(e) => err_json(&e),
574        }
575    }
576
577    /// VISCA reset.
578    #[tool(description = "Send the camera's pan-tilt reset command, which returns it to the mechanically centered position — the remote's Reset button.")]
579    async fn ptzcam_visca_reset(&self, Parameters(req): Parameters<ViscaAddrRequest>) -> String {
580        let addr = req.address.unwrap_or(1);
581        match self.visca_cmd(req.transport.as_deref().unwrap_or("serial"), &visca::pan_tilt_reset(addr)).await {
582            Ok(data) => serde_json::json!({ "ok": true, "completion_hex": hex(&data) }).to_string(),
583            Err(e) => err_json(&e),
584        }
585    }
586
587    /// Calibration probe: move one control and return to origin.
588    #[tool(description = "Calibration helper: move ONE control by `direction` * `amount`, wait for the motors to settle, report the position, then return to the starting position. Use this while the user watches the camera: for each of pan/tilt/zoom in both directions, run the probe and ask the user which physical way the camera moved. Record the answers in the calibration file (see the ptzcam-calibrate skill), then use ptzcam-move-dir for logical directions.")]
589    async fn ptzcam_calibrate_probe(&self, Parameters(req): Parameters<CalibrateProbeRequest>) -> String {
590        let mut b = match self.v4l2() {
591            Ok(b) => b,
592            Err(e) => return err_json(&e),
593        };
594        let (id, control) = match req.control.as_str() {
595            "pan" => (v4l2::CID_PAN, "pan"),
596            "tilt" => (v4l2::CID_TILT, "tilt"),
597            "zoom" => (v4l2::CID_ZOOM, "zoom"),
598            other => return err_json(&anyhow::anyhow!("unknown control '{other}'; use pan, tilt or zoom")),
599        };
600        let speed = req.speed.unwrap_or(12).clamp(1, 24);
601        let start = match b.get(id) {
602            Ok(v) => v,
603            Err(e) => return err_json(&anyhow::anyhow!("read {control}: {e}")),
604        };
605        let amount = req.amount.unwrap_or(if control == "zoom" { 100 } else { 100000 });
606        let target = start + req.direction.signum() * amount;
607
608        let moved = match control {
609            "pan" => v4l2::move_absolute(&mut b, Some(target), None, None, Some(speed), Some(speed)),
610            "tilt" => v4l2::move_absolute(&mut b, None, Some(target), None, Some(speed), Some(speed)),
611            _ => v4l2::move_absolute(&mut b, None, None, Some(target), None, None),
612        };
613        if let Err(e) = moved {
614            return err_json(&anyhow::anyhow!("move {control}: {e}"));
615        }
616        tokio::time::sleep(std::time::Duration::from_millis(800)).await;
617        let moved_to = b.get(id).unwrap_or(target);
618
619        // Return to the starting position.
620        let _ = match control {
621            "pan" => v4l2::move_absolute(&mut b, Some(start), None, None, Some(speed), Some(speed)),
622            "tilt" => v4l2::move_absolute(&mut b, None, Some(start), None, Some(speed), Some(speed)),
623            _ => v4l2::move_absolute(&mut b, None, None, Some(start), None, None),
624        };
625        tokio::time::sleep(std::time::Duration::from_millis(800)).await;
626        let returned_to = b.get(id).unwrap_or(start);
627
628        serde_json::json!({
629            "ok": true,
630            "control": control,
631            "direction": req.direction.signum(),
632            "start": start,
633            "target": target,
634            "moved_to": moved_to,
635            "returned_to": returned_to,
636        })
637        .to_string()
638    }
639
640    /// Logical-direction move using the calibration file.
641    #[tool(description = "Move the camera in a logical direction using the calibration file: up, down, left, right, zoom_in, zoom_out, or diagonals. Maps the direction through the calibration to the correct V4L2 control and sign, so 'up' moves up even on cameras with swapped or inverted axes. If the direction is not calibrated, run the ptzcam-calibrate procedure first.")]
642    async fn ptzcam_move_dir(&self, Parameters(req): Parameters<MoveDirRequest>) -> String {
643        let cal_path = req
644            .calibration
645            .as_ref()
646            .map(std::path::PathBuf::from)
647            .unwrap_or_else(|| self.config.calibration_path.clone());
648        let cal = match calibration::Calibration::load(&cal_path) {
649            Ok(c) => c,
650            Err(e) => return err_json(&e),
651        };
652        let mut b = match self.v4l2() {
653            Ok(b) => b,
654            Err(e) => return err_json(&e),
655        };
656        let cur = match v4l2::read_position(&mut b) {
657            Ok(p) => p,
658            Err(e) => return err_json(&anyhow::anyhow!("read position: {e}")),
659        };
660        let amount = req.amount.unwrap_or(80000);
661        let target = match cal.target(&req.direction, amount, cur) {
662            Ok(t) => t,
663            Err(e) => return err_json(&e),
664        };
665        let speed = req.speed.unwrap_or(12).clamp(1, 24);
666        if let Err(e) = v4l2::move_absolute(
667            &mut b,
668            Some(target.pan),
669            Some(target.tilt),
670            Some(target.zoom),
671            Some(speed),
672            Some(speed),
673        ) {
674            return err_json(&anyhow::anyhow!("move: {e}"));
675        }
676        tokio::time::sleep(std::time::Duration::from_millis(800)).await;
677        match v4l2::read_position(&mut b) {
678            Ok(pos) => serde_json::json!({ "ok": true, "direction": req.direction, "target": target, "position": pos }).to_string(),
679            Err(e) => err_json(&anyhow::anyhow!("read position after move: {e}")),
680        }
681    }
682}
683
684#[tool_handler]
685impl ServerHandler for PtzcamServer {
686    fn get_info(&self) -> ServerInfo {
687        ServerInfo::new(ServerCapabilities::builder().enable_tools().build()).with_instructions(
688            "PTZ camera control server. Two transports: V4L2 controls on the video node \
689             (ptzcam_status, ptzcam_v4l2_status, ptzcam_v4l2_move) and Sony VISCA over serial \
690             or IP (ptzcam_visca_inquiry, ptzcam_visca_pan_tilt, ptzcam_visca_drive, \
691             ptzcam_visca_zoom, ptzcam_visca_focus, ptzcam_visca_home, ptzcam_visca_reset, \
692             ptzcam_visca_preset, ptzcam_visca_power, ptzcam_visca_raw). \
693             Calibration: ptzcam_calibrate_probe tests one axis (the user confirms the \
694             physical direction), and ptzcam_move_dir moves in logical directions \
695             (up/down/left/right/zoom) using the calibration file. \
696             The VISCA tools mirror the camera remote: Home -> ptzcam_visca_home, Reset -> \
697             ptzcam_visca_reset, arrows -> ptzcam_visca_drive, Zoom +/- -> ptzcam_visca_zoom \
698             tele/wide, Far/Near/Auto -> ptzcam_visca_focus. \
699             Typical flow: ptzcam_status to see what is available, ptzcam_visca_inquiry with \
700             kind pan_tilt/zoom to read position, then move and confirm with another inquiry. \
701             All values are in camera-specific units; the V4L2 ranges come from the device.",
702        )
703    }
704}
705
706// ---------------------------------------------------------------------------
707// helpers
708// ---------------------------------------------------------------------------
709
710fn hex(bytes: &[u8]) -> String {
711    bytes.iter().map(|b| format!("{b:02x}")).collect()
712}
713
714fn hex_decode(s: &str) -> anyhow::Result<Vec<u8>> {
715    let s: String = s.chars().filter(|c| !c.is_whitespace()).collect();
716    if s.len() % 2 != 0 {
717        return Err(anyhow::anyhow!("hex string must have an even number of digits"));
718    }
719    (0..s.len())
720        .step_by(2)
721        .map(|i| {
722            u8::from_str_radix(&s[i..i + 2], 16)
723                .map_err(|_| anyhow::anyhow!("invalid hex byte '{}'", &s[i..i + 2]))
724        })
725        .collect()
726}
727
728#[cfg(test)]
729mod tests {
730    use super::*;
731
732    #[test]
733    fn hex_roundtrip() {
734        assert_eq!(hex(&[0x81, 0x01, 0x06, 0x04]), "81010604");
735        assert_eq!(hex_decode("81 01 06 04").unwrap(), vec![0x81, 0x01, 0x06, 0x04]);
736        assert_eq!(hex_decode("8101").unwrap(), vec![0x81, 0x01]);
737        assert!(hex_decode("810").is_err());
738        assert!(hex_decode("zz").is_err());
739    }
740}