Spawn a task to read from the socket.
This commit is contained in:
parent
847ffe50be
commit
6dc4c28bb5
@ -2,13 +2,15 @@ use std::collections::HashMap;
|
|||||||
use std::io::Read;
|
use std::io::Read;
|
||||||
use std::os::unix::prelude::OsStrExt;
|
use std::os::unix::prelude::OsStrExt;
|
||||||
use std::{collections::BTreeMap, path::Path};
|
use std::{collections::BTreeMap, path::Path};
|
||||||
use tokio::io::AsyncWriteExt;
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
|
use tokio::net::unix::OwnedWriteHalf;
|
||||||
use tokio::net::UnixStream;
|
use tokio::net::UnixStream;
|
||||||
|
use tokio::sync::oneshot;
|
||||||
|
|
||||||
use super::command::Command;
|
use super::command::Command;
|
||||||
|
|
||||||
pub struct MpvCtl {
|
pub struct MpvCtl {
|
||||||
socket: UnixStream,
|
socket: OwnedWriteHalf,
|
||||||
next_request_id: u64,
|
next_request_id: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -17,8 +19,27 @@ impl MpvCtl {
|
|||||||
socket_path: P,
|
socket_path: P,
|
||||||
) -> Result<Self, Box<dyn std::error::Error>> {
|
) -> Result<Self, Box<dyn std::error::Error>> {
|
||||||
let socket = UnixStream::connect(socket_path).await?;
|
let socket = UnixStream::connect(socket_path).await?;
|
||||||
|
let (mut socket_read, socket_write) = socket.into_split();
|
||||||
|
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let mut buf = vec![0; 1024];
|
||||||
|
loop {
|
||||||
|
match socket_read.read(&mut buf).await {
|
||||||
|
// Remote has closed
|
||||||
|
Ok(0) => return,
|
||||||
|
Ok(n) => {
|
||||||
|
// TODO actually used the read value
|
||||||
|
}
|
||||||
|
Err(_) => {
|
||||||
|
// Ruh roh
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
Ok(MpvCtl {
|
Ok(MpvCtl {
|
||||||
socket,
|
socket: socket_write,
|
||||||
next_request_id: 0,
|
next_request_id: 0,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@ -32,6 +53,9 @@ impl MpvCtl {
|
|||||||
async fn send_command(&mut self, cmd: Command) -> Result<(), Box<dyn std::error::Error>> {
|
async fn send_command(&mut self, cmd: Command) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
let serialized = serde_json::to_string(&cmd)?;
|
let serialized = serde_json::to_string(&cmd)?;
|
||||||
println!("Sending {}", serialized);
|
println!("Sending {}", serialized);
|
||||||
|
let (response_tx, response_rx) = oneshot::channel::<serde_json::Value>();
|
||||||
|
// TODO: store one stream where the reading thread can get it? Then wait for response on this end and return it from this function.
|
||||||
|
|
||||||
self.socket.write_all(serialized.as_bytes()).await?;
|
self.socket.write_all(serialized.as_bytes()).await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user