Skip to main content

labstream_proto/
discovery.rs

1//! Discovery over UDP. SPEC.md 2.
2
3/// The default base port. `src/api_config.cpp:170`.
4pub const BASE_PORT: u16 = 16572;
5/// The default port range. `src/api_config.cpp:171`.
6pub const PORT_RANGE: u16 = 32;
7
8/// The default multicast and broadcast addresses.
9/// `src/api_config.cpp:196-202`.
10pub const LINK_ADDRESSES: [&str; 3] = ["255.255.255.255", "224.0.0.1", "224.0.0.183"];
11/// The default site address.
12pub const SITE_ADDRESSES: [&str; 1] = ["239.255.172.215"];
13
14/// Build a shortinfo query. SPEC.md 2.1.
15///
16/// The query identifier is an opaque round-trip token. liblsl builds it from
17/// `std::hash`, whose value differs between standard libraries. A caller
18/// passes any value and compares the answer with what it sent. SPEC.md 2.3.
19pub fn build_query(query: &str, return_port: u16, query_id: &str) -> Vec<u8> {
20    format!("LSL:shortinfo\r\n{query}\r\n{return_port} {query_id}\r\n").into_bytes()
21}
22
23/// A parsed shortinfo query, as an outlet reads it.
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct Query {
26    /// The XPath query. An empty value matches every stream.
27    pub query: String,
28    /// The port that the answer goes to.
29    pub return_port: u16,
30    /// The token to echo.
31    pub query_id: String,
32}
33
34/// Read a shortinfo query.
35///
36/// liblsl reads the query with `getline` and then reads the port and the
37/// identifier with the stream operator (`src/udp_server.cpp`,
38/// `process_shortinfo_request`).
39pub fn parse_query(buf: &[u8]) -> Option<Query> {
40    let text = String::from_utf8_lossy(buf);
41    let mut lines = text.split('\n');
42    let method = lines.next()?.trim_end_matches('\r').trim();
43    if method != "LSL:shortinfo" {
44        return None;
45    }
46    let query = lines.next()?.trim_end_matches('\r').trim().to_string();
47    let tail = lines.next()?;
48    let mut parts = tail.split_whitespace();
49    let return_port = parts.next()?.parse().ok()?;
50    let query_id = parts.next().unwrap_or("").to_string();
51    Some(Query {
52        query,
53        return_port,
54        query_id,
55    })
56}
57
58/// Build a shortinfo answer. SPEC.md 2.2.
59pub fn build_answer(query_id: &str, shortinfo_xml: &str) -> Vec<u8> {
60    let mut v = Vec::with_capacity(query_id.len() + 2 + shortinfo_xml.len());
61    v.extend_from_slice(query_id.as_bytes());
62    v.extend_from_slice(b"\r\n");
63    v.extend_from_slice(shortinfo_xml.as_bytes());
64    v
65}
66
67/// A parsed shortinfo answer.
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct Answer {
70    /// The token that came back.
71    pub query_id: String,
72    /// The XML description of the stream.
73    pub xml: String,
74}
75
76/// Read a shortinfo answer.
77///
78/// The caller compares `query_id` with the value that it sent. A mismatch
79/// means the answer belongs to another query, and liblsl drops it
80/// (`src/resolve_attempt_udp.cpp:114`).
81pub fn parse_answer(buf: &[u8]) -> Option<Answer> {
82    let nl = buf.iter().position(|&b| b == b'\n')?;
83    let id = String::from_utf8_lossy(&buf[..nl]).trim().to_string();
84    let xml = String::from_utf8_lossy(&buf[nl + 1..]).to_string();
85    Some(Answer { query_id: id, xml })
86}
87
88/// The fields that an inlet reads out of a short description.
89///
90/// This is a small reader and not a general XML parser. The fields sit at a
91/// fixed depth, and every one of them holds text.
92#[derive(Debug, Clone, Default, PartialEq)]
93pub struct ShortInfo {
94    /// The stream name.
95    pub name: String,
96    /// The content type.
97    pub stream_type: String,
98    /// The channel count.
99    pub channel_count: u32,
100    /// The channel format, as text.
101    pub channel_format: String,
102    /// The stream instance identifier.
103    pub uid: String,
104    /// The source identifier.
105    pub source_id: String,
106    /// The nominal rate.
107    pub nominal_srate: f64,
108    /// The host name of the sender.
109    pub hostname: String,
110    /// The TCP port that carries the data.
111    pub v4data_port: u16,
112    /// The UDP port that answers a time probe.
113    pub v4service_port: u16,
114}
115
116fn tag<'a>(xml: &'a str, name: &str) -> Option<&'a str> {
117    let open = format!("<{name}>");
118    let close = format!("</{name}>");
119    let a = xml.find(&open)? + open.len();
120    let b = xml[a..].find(&close)? + a;
121    Some(&xml[a..b])
122}
123
124impl ShortInfo {
125    /// Read the fields out of a short description.
126    pub fn parse(xml: &str) -> Option<Self> {
127        Some(ShortInfo {
128            name: tag(xml, "name")?.to_string(),
129            stream_type: tag(xml, "type").unwrap_or("").to_string(),
130            channel_count: tag(xml, "channel_count")?.trim().parse().ok()?,
131            channel_format: tag(xml, "channel_format")?.trim().to_string(),
132            uid: tag(xml, "uid")?.to_string(),
133            source_id: tag(xml, "source_id").unwrap_or("").to_string(),
134            nominal_srate: tag(xml, "nominal_srate")
135                .and_then(|s| s.trim().parse().ok())
136                .unwrap_or(0.0),
137            hostname: tag(xml, "hostname").unwrap_or("").to_string(),
138            v4data_port: tag(xml, "v4data_port")?.trim().parse().ok()?,
139            v4service_port: tag(xml, "v4service_port")?.trim().parse().ok()?,
140        })
141    }
142}
143
144#[cfg(test)]
145mod tests {
146    use super::*;
147
148    const SAMPLE: &str = "<?xml version=\"1.0\"?><info><name>Probe</name><type>EEG</type>\
149        <channel_count>8</channel_count><channel_format>float32</channel_format>\
150        <source_id>src</source_id><nominal_srate>100.0000000000000</nominal_srate>\
151        <uid>25cfa701-e55b-4e42-8fc2-103bbd2f86b6</uid><session_id>default</session_id>\
152        <hostname>box</hostname><v4data_port>16572</v4data_port>\
153        <v4service_port>16572</v4service_port></info>";
154
155    #[test]
156    fn a_query_round_trips() {
157        let bytes = build_query("name='Probe'", 40000, "token-1");
158        assert_eq!(
159            String::from_utf8_lossy(&bytes),
160            "LSL:shortinfo\r\nname='Probe'\r\n40000 token-1\r\n"
161        );
162        let q = parse_query(&bytes).expect("a query");
163        assert_eq!(q.query, "name='Probe'");
164        assert_eq!(q.return_port, 40000);
165        assert_eq!(q.query_id, "token-1");
166    }
167
168    #[test]
169    fn an_empty_query_survives_the_round_trip() {
170        let bytes = build_query("", 1, "t");
171        let q = parse_query(&bytes).expect("a query");
172        assert_eq!(q.query, "");
173    }
174
175    #[test]
176    fn another_method_is_not_a_query() {
177        assert_eq!(parse_query(b"LSL:timedata\r\n1 2.0\r\n"), None);
178    }
179
180    #[test]
181    fn an_answer_round_trips() {
182        let bytes = build_answer("token-1", SAMPLE);
183        let a = parse_answer(&bytes).expect("an answer");
184        assert_eq!(a.query_id, "token-1");
185        assert_eq!(a.xml, SAMPLE);
186    }
187
188    #[test]
189    fn the_reader_finds_every_field() {
190        let s = ShortInfo::parse(SAMPLE).expect("a description");
191        assert_eq!(s.name, "Probe");
192        assert_eq!(s.channel_count, 8);
193        assert_eq!(s.channel_format, "float32");
194        assert_eq!(s.uid, "25cfa701-e55b-4e42-8fc2-103bbd2f86b6");
195        assert_eq!(s.v4data_port, 16572);
196        assert_eq!(s.v4service_port, 16572);
197        assert!((s.nominal_srate - 100.0).abs() < 1e-9);
198    }
199}