1
0
Fork 0
mirror of https://github.com/Zedfrigg/ironbar.git synced 2025-09-15 19:26:58 +02:00
ironbar/src/ipc/client.rs

36 lines
1.1 KiB
Rust
Raw Normal View History

2023-06-22 23:06:45 +01:00
use super::Ipc;
use crate::ipc::{Command, Response};
use color_eyre::Result;
use color_eyre::{Help, Report};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
2023-06-22 23:06:45 +01:00
use tokio::net::UnixStream;
impl Ipc {
/// Sends a command to the IPC server.
/// The server response is returned.
2024-05-18 17:00:27 +01:00
pub async fn send(&self, command: Command, debug: bool) -> Result<Response> {
2023-06-22 23:06:45 +01:00
let mut stream = match UnixStream::connect(&self.path).await {
Ok(stream) => Ok(stream),
Err(err) => Err(Report::new(err)
.wrap_err("Failed to connect to Ironbar IPC server")
.suggestion("Is Ironbar running?")),
}?;
let mut write_buffer = serde_json::to_vec(&command)?;
2024-05-18 17:00:27 +01:00
if debug {
eprintln!("REQUEST JSON: {}", serde_json::to_string(&command)?);
}
write_buffer.push(b'\n');
2023-06-22 23:06:45 +01:00
stream.write_all(&write_buffer).await?;
let mut read_buffer = String::new();
let mut reader = BufReader::new(stream);
let bytes = reader.read_line(&mut read_buffer).await?;
2023-06-22 23:06:45 +01:00
let response = serde_json::from_str(&read_buffer[..bytes])?;
2023-06-22 23:06:45 +01:00
Ok(response)
}
}