spvirit-py 0.1.7

Python bindings for spvirit PVAccess client and server.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
//! Python client wrappers — sync-only for phase 1.

use std::net::SocketAddr;
use std::ops::ControlFlow;
use std::time::Duration;

use pyo3::prelude::*;
use pyo3::types::{PyDict, PyList};

use spvirit_client::pva_client::PvaClient;
use spvirit_client::search::{build_auto_broadcast_targets, discover_servers};


use crate::convert::{decoded_to_py, py_to_json};
use crate::errors::to_py_err;
use crate::runtime::RUNTIME;

// ─── GetResult ───────────────────────────────────────────────────────────────

#[pyclass(name = "GetResult")]
pub struct PyGetResult {
    #[pyo3(get)]
    pub pv_name: String,
    value: PyObject,
    #[pyo3(get)]
    pub raw_pva: Vec<u8>,
    #[pyo3(get)]
    pub raw_pvd: Vec<u8>,
}

impl PyGetResult {
    pub(crate) fn new(pv_name: String, value: PyObject, raw_pva: Vec<u8>, raw_pvd: Vec<u8>) -> Self {
        Self {
            pv_name,
            value,
            raw_pva,
            raw_pvd,
        }
    }
}

#[pymethods]
impl PyGetResult {
    #[getter]
    fn value(&self, py: Python<'_>) -> PyObject {
        self.value.clone_ref(py)
    }

    fn __repr__(&self) -> String {
        format!("GetResult(pv_name={:?})", self.pv_name)
    }
}

// ─── MonitorEvent ────────────────────────────────────────────────────────────

#[pyclass(name = "MonitorEvent")]
pub struct PyMonitorEvent {
    #[pyo3(get)]
    pub pv_name: String,
    value: PyObject,
}

#[pymethods]
impl PyMonitorEvent {
    #[getter]
    fn value(&self, py: Python<'_>) -> PyObject {
        self.value.clone_ref(py)
    }

    fn __repr__(&self) -> String {
        format!("MonitorEvent(pv_name={:?})", self.pv_name)
    }
}

// ─── DiscoveredServer ────────────────────────────────────────────────────────

#[pyclass(name = "DiscoveredServer")]
#[derive(Clone)]
pub struct PyDiscoveredServer {
    #[pyo3(get)]
    pub guid: Vec<u8>,
    #[pyo3(get)]
    pub tcp_addr: String,
}

#[pymethods]
impl PyDiscoveredServer {
    fn __repr__(&self) -> String {
        format!("DiscoveredServer(tcp_addr={:?})", self.tcp_addr)
    }
}

// ─── ClientBuilder ───────────────────────────────────────────────────────────

#[pyclass(name = "ClientBuilder")]
pub struct PyClientBuilder {
    udp_port: u16,
    tcp_port: u16,
    timeout_secs: f64,
    no_broadcast: bool,
    name_servers: Vec<String>,
    authnz_user: Option<String>,
    authnz_host: Option<String>,
    server_addr: Option<String>,
    search_addr: Option<String>,
    bind_addr: Option<String>,
    debug: bool,
}

#[pymethods]
impl PyClientBuilder {
    #[new]
    fn new() -> Self {
        Self {
            udp_port: 5076,
            tcp_port: 5075,
            timeout_secs: 5.0,
            no_broadcast: false,
            name_servers: Vec::new(),
            authnz_user: None,
            authnz_host: None,
            server_addr: None,
            search_addr: None,
            bind_addr: None,
            debug: false,
        }
    }

    fn port(mut slf: PyRefMut<'_, Self>, port: u16) -> PyRefMut<'_, Self> {
        slf.tcp_port = port;
        slf
    }

    fn udp_port(mut slf: PyRefMut<'_, Self>, port: u16) -> PyRefMut<'_, Self> {
        slf.udp_port = port;
        slf
    }

    fn timeout(mut slf: PyRefMut<'_, Self>, secs: f64) -> PyRefMut<'_, Self> {
        slf.timeout_secs = secs;
        slf
    }

    fn no_broadcast(mut slf: PyRefMut<'_, Self>, enabled: bool) -> PyRefMut<'_, Self> {
        slf.no_broadcast = enabled;
        slf
    }

    fn name_server(mut slf: PyRefMut<'_, Self>, addr: String) -> PyResult<PyRefMut<'_, Self>> {
        let _: SocketAddr = addr
            .parse()
            .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("invalid address: {e}")))?;
        slf.name_servers.push(addr);
        Ok(slf)
    }

    fn authnz_user(mut slf: PyRefMut<'_, Self>, user: String) -> PyRefMut<'_, Self> {
        slf.authnz_user = Some(user);
        slf
    }

    fn authnz_host(mut slf: PyRefMut<'_, Self>, host: String) -> PyRefMut<'_, Self> {
        slf.authnz_host = Some(host);
        slf
    }

    fn server_addr(mut slf: PyRefMut<'_, Self>, addr: String) -> PyResult<PyRefMut<'_, Self>> {
        let _: SocketAddr = addr
            .parse()
            .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("invalid address: {e}")))?;
        slf.server_addr = Some(addr);
        Ok(slf)
    }

    fn search_addr(mut slf: PyRefMut<'_, Self>, addr: String) -> PyRefMut<'_, Self> {
        slf.search_addr = Some(addr);
        slf
    }

    fn bind_addr(mut slf: PyRefMut<'_, Self>, addr: String) -> PyRefMut<'_, Self> {
        slf.bind_addr = Some(addr);
        slf
    }

    fn debug(mut slf: PyRefMut<'_, Self>, enabled: bool) -> PyRefMut<'_, Self> {
        slf.debug = enabled;
        slf
    }

    fn build(&self) -> PyResult<PyClient> {
        let mut b = PvaClient::builder()
            .port(self.tcp_port)
            .udp_port(self.udp_port)
            .timeout(Duration::from_secs_f64(self.timeout_secs));
        if self.no_broadcast {
            b = b.no_broadcast();
        }
        for ns in &self.name_servers {
            let addr: SocketAddr = ns.parse().map_err(|e| {
                pyo3::exceptions::PyValueError::new_err(format!("invalid address: {e}"))
            })?;
            b = b.name_server(addr);
        }
        if let Some(ref user) = self.authnz_user {
            b = b.authnz_user(user);
        }
        if let Some(ref host) = self.authnz_host {
            b = b.authnz_host(host);
        }
        if let Some(ref addr) = self.server_addr {
            let sa: SocketAddr = addr.parse().map_err(|e| {
                pyo3::exceptions::PyValueError::new_err(format!("invalid address: {e}"))
            })?;
            b = b.server_addr(sa);
        }
        if let Some(ref addr) = self.search_addr {
            let ip: std::net::IpAddr = addr.parse().map_err(|e| {
                pyo3::exceptions::PyValueError::new_err(format!("invalid IP: {e}"))
            })?;
            b = b.search_addr(ip);
        }
        if let Some(ref addr) = self.bind_addr {
            let ip: std::net::IpAddr = addr.parse().map_err(|e| {
                pyo3::exceptions::PyValueError::new_err(format!("invalid IP: {e}"))
            })?;
            b = b.bind_addr(ip);
        }
        if self.debug {
            b = b.debug();
        }
        Ok(PyClient {
            inner: b.build(),
        })
    }
}

// ─── Client ──────────────────────────────────────────────────────────────────

#[pyclass(name = "Client")]
pub struct PyClient {
    inner: PvaClient,
}

#[pymethods]
impl PyClient {
    #[new]
    fn new() -> Self {
        Self {
            inner: PvaClient::builder().build(),
        }
    }

    /// Create a builder for fine-grained configuration.
    #[staticmethod]
    fn builder() -> PyClientBuilder {
        PyClientBuilder::new()
    }

    /// Fetch the current value of a PV (blocking).
    ///
    /// If `fields` is provided, the pvRequest restricts the returned
    /// structure to those dotted paths (e.g. `["value", "alarm.severity"]`).
    #[pyo3(signature = (pv_name, fields=None))]
    fn get(
        &self,
        py: Python<'_>,
        pv_name: String,
        fields: Option<Vec<String>>,
    ) -> PyResult<PyGetResult> {
        let client = self.inner.clone();
        let result = py
            .allow_threads(|| {
                RUNTIME.block_on(async {
                    match fields {
                        None => client.pvget(&pv_name).await,
                        Some(ref f) => {
                            let refs: Vec<&str> = f.iter().map(String::as_str).collect();
                            client.pvget_fields(&pv_name, &refs).await
                        }
                    }
                })
            })
            .map_err(to_py_err)?;
        let value = decoded_to_py(py, &result.value);
        Ok(PyGetResult {
            pv_name: result.pv_name,
            value,
            raw_pva: result.raw_pva,
            raw_pvd: result.raw_pvd,
        })
    }

    /// Write a value to a PV (blocking).
    ///
    /// `fields` selects which pvRequest fields are targeted. Defaults to
    /// `["value"]` when omitted.
    #[pyo3(signature = (pv_name, value, fields=None))]
    fn put(
        &self,
        py: Python<'_>,
        pv_name: String,
        value: PyObject,
        fields: Option<Vec<String>>,
    ) -> PyResult<()> {
        let json_val = py_to_json(value.bind(py))?;
        let client = self.inner.clone();
        py.allow_threads(|| {
            RUNTIME.block_on(async {
                match fields {
                    None => client.pvput(&pv_name, json_val).await,
                    Some(ref f) => {
                        let refs: Vec<&str> = f.iter().map(String::as_str).collect();
                        client.pvput_fields(&pv_name, json_val, &refs).await
                    }
                }
            })
        })
        .map_err(to_py_err)
    }

    /// Subscribe to a PV and call `callback(value_dict)` for each update.
    ///
    /// Blocks until the callback returns `False` or raises an exception.
    /// `fields` restricts the subscription to the given dotted paths.
    #[pyo3(signature = (pv_name, callback, fields=None))]
    fn monitor(
        &self,
        _py: Python<'_>,
        pv_name: String,
        callback: PyObject,
        fields: Option<Vec<String>>,
    ) -> PyResult<()> {
        let client = self.inner.clone();
        let fields = fields.unwrap_or_default();
        // We need the GIL inside the callback, so we cannot use allow_threads
        // for the entire operation. Instead we spawn on the runtime and
        // use Python::with_gil inside the callback.
        let result = RUNTIME.block_on(async {
            let refs: Vec<&str> = fields.iter().map(String::as_str).collect();
            client
                .pvmonitor_fields(&pv_name, &refs, |decoded| {
                    let keep_going = Python::with_gil(|py| {
                        let py_val = decoded_to_py(py, decoded);
                        match callback.call1(py, (py_val,)) {
                            Ok(ret) => {
                                // If callback returns False, stop
                                ret.extract::<bool>(py).unwrap_or(true)
                            }
                            Err(_) => false,
                        }
                    });
                    if keep_going {
                        ControlFlow::Continue(())
                    } else {
                        ControlFlow::Break(())
                    }
                })
                .await
        });
        // Release the GIL while we were waiting
        result.map_err(to_py_err)
    }

    /// Retrieve introspection (field description) for a PV.
    fn info(&self, py: Python<'_>, pv_name: String) -> PyResult<PyObject> {
        let client = self.inner.clone();
        let desc = py
            .allow_threads(|| RUNTIME.block_on(client.pvinfo(&pv_name)))
            .map_err(to_py_err)?;
        // Return as a dict: {struct_id, fields: [{name, field_type}, ...]}
        let dict = PyDict::new(py);
        dict.set_item("struct_id", &desc.struct_id)?;
        let fields: Vec<PyObject> = desc
            .fields
            .iter()
            .map(|f| {
                let fd = PyDict::new(py);
                fd.set_item("name", &f.name).expect("set");
                fd.set_item("field_type", format!("{:?}", f.field_type))
                    .expect("set");
                fd.into_any().unbind()
            })
            .collect();
        dict.set_item("fields", PyList::new(py, &fields)?)?;
        Ok(dict.into_any().unbind())
    }

    /// List PV names from a specific server.
    fn pvlist(&self, py: Python<'_>, server_addr: String) -> PyResult<Vec<String>> {
        let addr: SocketAddr = server_addr
            .parse()
            .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("invalid address: {e}")))?;
        let client = self.inner.clone();
        py.allow_threads(|| RUNTIME.block_on(client.pvlist(addr)))
            .map_err(to_py_err)
    }
}

// ─── discover_servers ────────────────────────────────────────────────────────

/// Discover PVA servers on the network via UDP beacon search.
#[pyfunction]
#[pyo3(signature = (udp_port=5076, timeout=2.0, debug=false))]
pub fn py_discover_servers(
    py: Python<'_>,
    udp_port: u16,
    timeout: f64,
    debug: bool,
) -> PyResult<Vec<PyDiscoveredServer>> {
    let targets = build_auto_broadcast_targets();
    let dur = Duration::from_secs_f64(timeout);
    let servers = py
        .allow_threads(|| RUNTIME.block_on(discover_servers(udp_port, dur, &targets, debug)))
        .map_err(to_py_err)?;
    Ok(servers
        .into_iter()
        .map(|s| PyDiscoveredServer {
            guid: s.guid.to_vec(),
            tcp_addr: s.tcp_addr.to_string(),
        })
        .collect())
}