Skip to main content

seydd/
publisher_control.rs

1// Copyright 2026 Anton Gravestam
2// SPDX-License-Identifier: Apache-2.0
3//! Best-effort JSON to the robot's publisher (docs/protocol/seydd.md).
4//! Fire-and-forget and never fatal: a publisher that ignores this keeps
5//! streaming on whatever it was configured with.
6
7use std::net::UdpSocket;
8
9pub struct PublisherControl {
10    sock: Option<UdpSocket>,
11    target: String,
12}
13
14impl PublisherControl {
15    pub fn new(target: Option<&str>) -> Self {
16        let sock = target.and_then(|_| {
17            UdpSocket::bind("0.0.0.0:0")
18                .and_then(|s| s.set_nonblocking(true).map(|_| s))
19                .ok()
20        });
21        Self {
22            sock,
23            target: target.unwrap_or_default().to_string(),
24        }
25    }
26
27    pub fn enabled(&self) -> bool {
28        self.sock.is_some()
29    }
30
31    pub fn send(&self, msg: &serde_json::Value) -> bool {
32        let Some(sock) = &self.sock else { return false };
33        match sock.send_to(msg.to_string().as_bytes(), &self.target) {
34            Ok(_) => true,
35            Err(e) => {
36                tracing::debug!(error = %e, "publisher control send failed");
37                false
38            }
39        }
40    }
41}