motorcortex-rust 0.5.0

Motorcortex Rust: a Rust client for the Motorcortex Core real-time control system (async + blocking).
Documentation
//! Blocking wrapper around [`crate::core::Subscribe`].

use std::sync::Arc;

use tokio::runtime::Runtime;

use crate::client::Parameters;
use crate::connection::ConnectionOptions;
use crate::core;
use crate::error::{MotorcortexError, Result};

use super::Subscription;
use super::request::Request;

pub struct Subscribe {
    inner: core::Subscribe,
    pub(crate) rt: Arc<Runtime>,
}

impl Subscribe {
    pub fn new() -> Result<Self> {
        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .map_err(|e| MotorcortexError::Connection(e.to_string()))?;
        Ok(Self {
            inner: core::Subscribe::new(),
            rt: Arc::new(rt),
        })
    }

    pub fn connect_to(url: &str, opts: ConnectionOptions) -> Result<Self> {
        let sub = Self::new()?;
        sub.connect(url, opts)?;
        Ok(sub)
    }

    pub fn connect(&self, url: &str, opts: ConnectionOptions) -> Result<()> {
        self.rt.block_on(self.inner.connect(url, opts))
    }

    pub fn disconnect(&self) -> Result<()> {
        self.rt.block_on(self.inner.disconnect())
    }

    pub fn subscribe<I>(
        &self,
        req: &Request,
        paths: I,
        alias: &str,
        fdiv: u32,
    ) -> Result<Subscription>
    where
        I: Parameters,
    {
        let core_sub = self
            .rt
            .block_on(self.inner.subscribe(req.as_async(), paths, alias, fdiv))?;
        Ok(Subscription::new(core_sub, Arc::clone(&self.rt)))
    }

    pub fn unsubscribe(&self, req: &Request, sub: Subscription) -> Result<()> {
        self.rt
            .block_on(self.inner.unsubscribe(req.as_async(), sub.into_inner()))
    }

    pub fn as_async(&self) -> &core::Subscribe {
        &self.inner
    }
}