use crate::{protocol as proto, tokio_async::R413D08, tokio_common::Result};
use std::sync::Arc;
use tokio::sync::Mutex;
use tokio_modbus::{client::Context, prelude::SlaveContext, Slave};
#[derive(Clone)]
pub struct SafeClient {
ctx: Arc<Mutex<Context>>,
}
impl SafeClient {
pub fn new(ctx: Context) -> Self {
Self {
ctx: Arc::new(Mutex::new(ctx)),
}
}
pub fn from_shared(ctx: Arc<Mutex<Context>>) -> Self {
Self { ctx }
}
pub fn clone_shared(&self) -> Arc<Mutex<Context>> {
self.ctx.clone()
}
pub async fn read_ports(&self) -> Result<proto::PortStates> {
let mut guard = self.ctx.lock().await;
R413D08::read_ports(&mut guard).await
}
pub async fn set_port_open(&self, port: proto::Port) -> Result<()> {
let mut guard = self.ctx.lock().await;
R413D08::set_port_open(&mut guard, port).await
}
pub async fn set_all_open(&self) -> Result<()> {
let mut guard = self.ctx.lock().await;
R413D08::set_all_open(&mut guard).await
}
pub async fn set_port_close(&self, port: proto::Port) -> Result<()> {
let mut guard = self.ctx.lock().await;
R413D08::set_port_close(&mut guard, port).await
}
pub async fn set_all_close(&self) -> Result<()> {
let mut guard = self.ctx.lock().await;
R413D08::set_all_close(&mut guard).await
}
pub async fn set_port_toggle(&self, port: proto::Port) -> Result<()> {
let mut guard = self.ctx.lock().await;
R413D08::set_port_toggle(&mut guard, port).await
}
pub async fn set_port_latch(&self, port: proto::Port) -> Result<()> {
let mut guard = self.ctx.lock().await;
R413D08::set_port_latch(&mut guard, port).await
}
pub async fn set_port_momentary(&self, port: proto::Port) -> Result<()> {
let mut guard = self.ctx.lock().await;
R413D08::set_port_momentary(&mut guard, port).await
}
pub async fn set_port_delay(&self, port: proto::Port, delay: u8) -> Result<()> {
let mut guard = self.ctx.lock().await;
R413D08::set_port_delay(&mut guard, port, delay).await
}
pub async fn read_address(&self) -> Result<proto::Address> {
let mut guard = self.ctx.lock().await;
R413D08::read_address(&mut guard).await
}
pub async fn set_address(&self, address: proto::Address) -> Result<()> {
let mut guard = self.ctx.lock().await;
R413D08::set_address(&mut guard, address).await?;
guard.set_slave(Slave(*address));
Ok(())
}
}