Dual synchronous and asynchronous API

Tests don't work in async mode
main
Laurent Pelecq 2 years ago
parent add553a270
commit 73b2531c4f

@ -1,6 +1,6 @@
[package] [package]
name = "ssip-client" name = "ssip-client"
version = "0.2.0" version = "0.3.0"
authors = ["Laurent Pelecq <lpelecq+rust@circoise.eu>"] authors = ["Laurent Pelecq <lpelecq+rust@circoise.eu>"]
edition = "2018" edition = "2018"
description = "Client API for Speech Dispatcher" description = "Client API for Speech Dispatcher"
@ -11,9 +11,17 @@ repository = "https://gitlab.com/lp-accessibility/ssip-client"
[dependencies] [dependencies]
dirs = "4" dirs = "4"
mio = { version = "0", optional = true }
thiserror = "1" thiserror = "1"
strum = "0.24" strum = "0.24"
strum_macros = "0.24" strum_macros = "0.24"
[dev-dependencies] [dev-dependencies]
libc = "0" libc = "0"
[features]
metal-io = ["mio/net", "mio/os-poll"]
[[example]]
name = "async-mio"
required-features = ["metal-io"]

@ -8,6 +8,8 @@ Rust SSIP Client
Speech Dispatcher [SSIP client library](http://htmlpreview.github.io/?https://github.com/brailcom/speechd/blob/master/doc/ssip.html) in pure rust. Speech Dispatcher [SSIP client library](http://htmlpreview.github.io/?https://github.com/brailcom/speechd/blob/master/doc/ssip.html) in pure rust.
- [x] Unix socket.
- [ ] TCP socket.
- [x] Stop, cancel, pause and resume. - [x] Stop, cancel, pause and resume.
- [x] List, set voices. - [x] List, set voices.
- [x] Set rate, pitch, volume. - [x] Set rate, pitch, volume.

@ -0,0 +1,51 @@
use mio::{Events, Poll, Token};
use ssip_client::{ClientName, ClientResult};
fn main() -> ClientResult<()> {
let mut poll = Poll::new()?;
let mut events = Events::with_capacity(128);
let mut client = ssip_client::new_default_fifo_client()?;
let token = Token(0);
client.register(&poll, token)?;
poll.poll(&mut events, None)?;
let mut is_opened = false;
while !is_opened {
for event in &events {
if event.token() == token && event.is_writable() {
println!("opening client");
match client.open(ClientName::new("joe", "hello")) {
Ok(()) => {
is_opened = true;
break;
}
Err(err) if err.kind() == io::ErrorKing::WouldBlock => {}
Err(err) => panic!("Error opening client: {:?}", err),
}
break;
}
}
}
poll.poll(&mut events, None)?;
for event in &events {
if event.token() == token && event.is_writable() {
println!("sending message");
let msg_id = client.say_line("hello")?;
println!("message: {}", msg_id);
break;
}
}
poll.poll(&mut events, None)?;
for event in &events {
if event.token() == token && event.is_writable() {
println!("quitting");
client.quit()?;
break;
}
}
Ok(())
}

@ -1,8 +1,11 @@
use ssip_client::{ClientName, ClientResult}; use ssip_client::{new_default_fifo_client, ClientName, ClientResult, OK_CLIENT_NAME_SET};
fn main() -> ClientResult<()> { fn main() -> ClientResult<()> {
let mut client = ssip_client::new_default_fifo_client(&ClientName::new("joe", "hello"), None)?; let mut client = new_default_fifo_client(None)?;
let msg_id = client.say_line("hello")?; client
.open(ClientName::new("joe", "hello"))?
.check_status(OK_CLIENT_NAME_SET)?;
let msg_id = client.speak()?.send_line("hello")?.receive_message_id()?;
println!("message: {}", msg_id); println!("message: {}", msg_id);
client.quit()?; client.quit()?;
Ok(()) Ok(())

@ -1,4 +1,7 @@
use ssip_client::{ClientName, ClientResult, SynthesisVoice}; use ssip_client::{
ClientName, ClientResult, SynthesisVoice, OK_CLIENT_NAME_SET, OK_OUTPUT_MODULES_LIST_SENT,
OK_VOICES_LIST_SENT,
};
fn voice_to_string(voice: &SynthesisVoice) -> String { fn voice_to_string(voice: &SynthesisVoice) -> String {
match &voice.language { match &voice.language {
@ -18,28 +21,32 @@ fn print_list(title: &str, values: &[String]) {
} }
fn main() -> ClientResult<()> { fn main() -> ClientResult<()> {
let mut client = ssip_client::new_default_fifo_client(&ClientName::new("joe", "list"), None)?; let mut client = ssip_client::new_default_fifo_client(None)?;
client
.open(ClientName::new("joe", "list"))?
.check_status(OK_CLIENT_NAME_SET)?;
const OUTPUT_MODULE_TITLE: &str = "output modules"; const OUTPUT_MODULE_TITLE: &str = "output modules";
match client.list_output_modules() { let modules = client
Ok(values) => print_list(OUTPUT_MODULE_TITLE, &values), .list_output_modules()?
Err(err) => eprintln!("{}: {}", OUTPUT_MODULE_TITLE, err), .receive_lines(OK_OUTPUT_MODULES_LIST_SENT)?;
}; print_list(OUTPUT_MODULE_TITLE, &modules);
const VOICE_TYPES_TITLE: &str = "voice types"; const VOICE_TYPES_TITLE: &str = "voice types";
match client.list_voice_types() { let vtypes = client
Ok(values) => print_list(VOICE_TYPES_TITLE, &values), .list_voice_types()?
Err(err) => eprintln!("{}: {}", VOICE_TYPES_TITLE, err), .receive_lines(OK_VOICES_LIST_SENT)?;
}; print_list(VOICE_TYPES_TITLE, &vtypes);
const SYNTHESIS_VOICES_TITLE: &str = "synthesis voices"; const SYNTHESIS_VOICES_TITLE: &str = "synthesis voices";
match client.list_synthesis_voices() { let voices = client.list_synthesis_voices()?.receive_synthesis_voices()?;
Ok(values) => print_list( print_list(
SYNTHESIS_VOICES_TITLE, SYNTHESIS_VOICES_TITLE,
&values &voices
.iter() .iter()
.map(|ref v| voice_to_string(v)) .map(|ref v| voice_to_string(v))
.collect::<Vec<String>>(), .collect::<Vec<String>>(),
), );
Err(err) => eprintln!("{}: {}", VOICE_TYPES_TITLE, err),
};
client.quit().unwrap(); client.quit().unwrap();
Ok(()) Ok(())

@ -1,10 +1,12 @@
use ssip_client::{ClientName, ClientResult, EventType, NotificationType}; use ssip_client::{ClientName, ClientResult, EventType, NotificationType, OK_CLIENT_NAME_SET};
fn main() -> ClientResult<()> { fn main() -> ClientResult<()> {
let mut client = let mut client = ssip_client::new_default_fifo_client(None)?;
ssip_client::new_default_fifo_client(&ClientName::new("joe", "notifications"), None)?; client
.open(ClientName::new("joe", "notifications"))?
.check_status(OK_CLIENT_NAME_SET)?;
client.enable_notification(NotificationType::All).unwrap(); client.enable_notification(NotificationType::All).unwrap();
let msg_id = client.say_line("hello")?; let msg_id = client.speak()?.send_line("hello")?.receive_message_id()?;
println!("message: {}", msg_id); println!("message: {}", msg_id);
loop { loop {
match client.receive_event() { match client.receive_event() {

@ -11,10 +11,11 @@ use std::io::{self, Read, Write};
use std::str::FromStr; use std::str::FromStr;
use thiserror::Error as ThisError; use thiserror::Error as ThisError;
use crate::constants::OK_RECEIVING_DATA; use crate::constants::{OK_MESSAGE_QUEUED, OK_VOICES_LIST_SENT};
use crate::protocol::{send_lines, write_lines};
use crate::types::{ use crate::types::{
CapitalLettersRecognitionMode, ClientScope, Event, KeyName, MessageId, MessageScope, CapitalLettersRecognitionMode, ClientScope, Event, KeyName, MessageId, MessageScope,
NotificationType, Priority, PunctuationMode, StatusLine, SynthesisVoice, NotificationType, Priority, PunctuationMode, ReturnCode, Source, StatusLine, SynthesisVoice,
}; };
/// Client error, either I/O error or SSIP error. /// Client error, either I/O error or SSIP error.
@ -32,6 +33,8 @@ pub enum ClientError {
TooManyLines, TooManyLines,
#[error("Truncated message")] #[error("Truncated message")]
TruncatedMessage, TruncatedMessage,
#[error("Unexpected status: {0}")]
UnexpectedStatus(ReturnCode),
} }
impl From<io::Error> for ClientError { impl From<io::Error> for ClientError {
@ -76,20 +79,26 @@ fn on_off(value: bool) -> &'static str {
} }
} }
macro_rules! client_setter { macro_rules! client_send {
($name:ident, $doc:expr, $scope:ident, $value_name:ident as $value_type:ty, $fmt:expr, $value:expr) => { ($name:ident, $doc:expr, $scope:ident, $value_name:ident as $value_type:ty, $fmt:expr, $value:expr) => {
#[doc=$doc] #[doc=$doc]
pub fn $name(&mut self, $scope: ClientScope, $value_name: $value_type) -> ClientStatus { pub fn $name(
&mut self,
$scope: ClientScope,
$value_name: $value_type,
) -> ClientResult<&mut Client<S>> {
let line = match $scope { let line = match $scope {
ClientScope::Current => format!($fmt, "self", $value), ClientScope::Current => format!($fmt, "self", $value),
ClientScope::All => format!($fmt, "all", $value), ClientScope::All => format!($fmt, "all", $value),
ClientScope::Client(id) => format!($fmt, id, $value), ClientScope::Client(id) => format!($fmt, id, $value),
}; };
send_lines!(&mut self.input, &mut self.output, &[line.as_str()])
send_lines(&mut self.output, &[line.as_str()])?;
Ok(self)
} }
}; };
($name:ident, $doc:expr, $scope:ident, $value_name:ident as $value_type:ty, $fmt:expr) => { ($name:ident, $doc:expr, $scope:ident, $value_name:ident as $value_type:ty, $fmt:expr) => {
client_setter!( client_send!(
$name, $name,
$doc, $doc,
$scope, $scope,
@ -100,24 +109,26 @@ macro_rules! client_setter {
}; };
($name:ident, $doc:expr, $value_name:ident as $value_type:ty, $fmt:expr, $value:expr) => { ($name:ident, $doc:expr, $value_name:ident as $value_type:ty, $fmt:expr, $value:expr) => {
#[doc=$doc] #[doc=$doc]
pub fn $name(&mut self, $value_name: $value_type) -> ClientStatus { pub fn $name(&mut self, $value_name: $value_type) -> ClientResult<&mut Client<S>> {
send_line!(&mut self.input, &mut self.output, $fmt, $value) send_lines(&mut self.output, &[format!($fmt, $value).as_str()])?;
Ok(self)
} }
}; };
($name:ident, $doc:expr, $value_name:ident as $value_type:ty, $fmt:expr) => { ($name:ident, $doc:expr, $value_name:ident as $value_type:ty, $fmt:expr) => {
client_setter!($name, $doc, $value_name as $value_type, $fmt, $value_name); client_send!($name, $doc, $value_name as $value_type, $fmt, $value_name);
}; };
($name:ident, $doc:expr, $line:expr) => { ($name:ident, $doc:expr, $line:expr) => {
#[doc=$doc] #[doc=$doc]
pub fn $name(&mut self) -> ClientStatus { pub fn $name(&mut self) -> ClientResult<&mut Client<S>> {
send_line!(&mut self.input, &mut self.output, $line) send_lines(&mut self.output, &[$line])?;
Ok(self)
} }
}; };
} }
macro_rules! client_boolean_setter { macro_rules! client_send_boolean {
($name:ident, $doc:expr, $scope:ident, $value_name:ident, $fmt:expr) => { ($name:ident, $doc:expr, $scope:ident, $value_name:ident, $fmt:expr) => {
client_setter!( client_send!(
$name, $name,
$doc, $doc,
$scope, $scope,
@ -127,13 +138,13 @@ macro_rules! client_boolean_setter {
); );
}; };
($name:ident, $doc:expr, $value_name:ident, $fmt:expr) => { ($name:ident, $doc:expr, $value_name:ident, $fmt:expr) => {
client_setter!($name, $doc, $value_name as bool, $fmt, on_off($value_name)); client_send!($name, $doc, $value_name as bool, $fmt, on_off($value_name));
}; };
} }
macro_rules! client_range_setter { macro_rules! client_send_range {
($name:ident, $doc:expr, $scope:ident, $value_name:ident, $fmt:expr) => { ($name:ident, $doc:expr, $scope:ident, $value_name:ident, $fmt:expr) => {
client_setter!( client_send!(
$name, $name,
$doc, $doc,
$scope, $scope,
@ -144,63 +155,40 @@ macro_rules! client_range_setter {
}; };
} }
macro_rules! client_getter {
($name:ident, $doc:expr, $line:expr) => {
#[doc=$doc]
pub fn $name(&mut self) -> ClientResult<Vec<String>> {
let mut result = Vec::new();
send_lines!(&mut self.input, &mut self.output, &[&$line], &mut result)?;
Ok(result)
}
};
}
macro_rules! client_single_getter {
($name:ident, $doc:expr, $value_type:ty, $line:expr) => {
#[doc=$doc]
pub fn $name(&mut self) -> ClientResult<$value_type> {
let mut lines = Vec::new();
send_lines!(&mut self.input, &mut self.output, &[&$line], &mut lines)?;
let result = Client::<S>::parse_single_value(&lines)?
.parse()
.map_err(|_| ClientError::InvalidType)?;
Ok(result)
}
};
($name:ident, $doc:expr, $line:expr) => {
#[doc=$doc]
pub fn $name(&mut self) -> ClientResult<String> {
let mut lines = Vec::new();
send_lines!(&mut self.input, &mut self.output, &[&$line], &mut lines)?;
Client::<S>::parse_single_value(&lines)
}
};
}
/// SSIP client on generic stream /// SSIP client on generic stream
#[cfg(not(feature = "metal-io"))]
pub struct Client<S: Read + Write> { pub struct Client<S: Read + Write> {
input: io::BufReader<S>, input: io::BufReader<S>,
output: io::BufWriter<S>, output: io::BufWriter<S>,
} }
impl<S: Read + Write> Client<S> { #[cfg(feature = "metal-io")]
pub(crate) fn new( pub struct Client<S: Read + Write + Source> {
mut input: io::BufReader<S>, input: io::BufReader<S>,
mut output: io::BufWriter<S>, output: io::BufWriter<S>,
client_name: &ClientName, socket: S,
) -> ClientResult<Self> { }
impl<S: Read + Write + Source> Client<S> {
#[cfg(not(feature = "metal-io"))]
pub(crate) fn new(input: io::BufReader<S>, output: io::BufWriter<S>) -> ClientResult<Self> {
// https://stackoverflow.com/questions/58467659/how-to-store-tcpstream-with-bufreader-and-bufwriter-in-a-data-structure // https://stackoverflow.com/questions/58467659/how-to-store-tcpstream-with-bufreader-and-bufwriter-in-a-data-structure
send_line!(
&mut input,
&mut output,
"SET self CLIENT_NAME {}:{}:{}",
client_name.user,
client_name.application,
client_name.component
)?;
Ok(Self { input, output }) Ok(Self { input, output })
} }
#[cfg(feature = "metal-io")]
pub(crate) fn new(
input: io::BufReader<S>,
output: io::BufWriter<S>,
socket: S,
) -> ClientResult<Self> {
Ok(Self {
socket,
input,
output,
})
}
fn parse_single_value(lines: &[String]) -> ClientResult<String> { fn parse_single_value(lines: &[String]) -> ClientResult<String> {
match lines.len() { match lines.len() {
0 => Err(ClientError::NoLine), 0 => Err(ClientError::NoLine),
@ -209,88 +197,98 @@ impl<S: Read + Write> Client<S> {
} }
} }
/// Send text to server pub fn open(&mut self, client_name: ClientName) -> ClientResult<&mut Client<S>> {
pub fn say_text(&mut self, lines: &[&str]) -> ClientResult<MessageId> { send_lines(
let status = send_line!(&mut self.input, &mut self.output, "SPEAK")?; &mut self.output,
if status.code == OK_RECEIVING_DATA { &[format!(
const END_OF_DATA: [&str; 1] = ["."]; "SET self CLIENT_NAME {}:{}:{}",
crate::protocol::write_lines(&mut self.output, lines)?; client_name.user, client_name.application, client_name.component
let mut answer = Vec::new(); )
send_lines!(&mut self.input, &mut self.output, &END_OF_DATA, &mut answer)?; .as_str()],
Client::<S>::parse_single_value(&answer) )?;
} else { Ok(self)
Err(ClientError::Ssip(status)) }
}
/// Initiate communitation to send text to speak
pub fn speak(&mut self) -> ClientResult<&mut Client<S>> {
send_lines(&mut self.output, &["SPEAK"])?;
Ok(self)
}
/// Send lines
pub fn send_lines(&mut self, lines: &[&str]) -> ClientResult<&mut Client<S>> {
const END_OF_DATA: [&str; 1] = ["."];
write_lines(&mut self.output, lines)?;
send_lines(&mut self.output, &END_OF_DATA)?;
Ok(self)
} }
/// Send a single line to the server /// Send a line
pub fn say_line(&mut self, line: &str) -> ClientResult<MessageId> { pub fn send_line(&mut self, line: &str) -> ClientResult<&mut Client<S>> {
let lines: [&str; 1] = [line]; const END_OF_DATA: &str = ".";
self.say_text(&lines) self.send_lines(&[line, END_OF_DATA])
} }
/// Send a char to the server /// Send a char
pub fn say_char(&mut self, ch: char) -> ClientResult<MessageId> { pub fn send_char(&mut self, ch: char) -> ClientResult<&mut Client<S>> {
let line = format!("CHAR {}", ch); self.send_lines(&[format!("CHAR {}", ch).as_str()])
let mut answer = Vec::new();
send_lines!(&mut self.input, &mut self.output, &[&line], &mut answer)?;
Client::<S>::parse_single_value(&answer)
} }
/// Send a symbolic key name /// Send a symbolic key name
pub fn say_key_name(&mut self, keyname: KeyName) -> ClientResult<MessageId> { pub fn say_key_name(&mut self, keyname: KeyName) -> ClientResult<&mut Client<S>> {
let line = format!("KEY {}", keyname); self.send_lines(&[format!("KEY {}", keyname).as_str()])
let mut answer = Vec::new();
send_lines!(&mut self.input, &mut self.output, &[&line], &mut answer)?;
Client::<S>::parse_single_value(&answer)
} }
/// Action on a message or a group of messages /// Action on a message or a group of messages
fn send_message_command(&mut self, command: &str, scope: MessageScope) -> ClientStatus { fn send_message_command(
&mut self,
command: &str,
scope: MessageScope,
) -> ClientResult<&mut Client<S>> {
let line = match scope { let line = match scope {
MessageScope::Last => format!("{} self", command), MessageScope::Last => format!("{} self", command),
MessageScope::All => format!("{} all", command), MessageScope::All => format!("{} all", command),
MessageScope::Message(id) => format!("{} {}", command, id), MessageScope::Message(id) => format!("{} {}", command, id),
}; };
send_lines!(&mut self.input, &mut self.output, &[line.as_str()]) send_lines(&mut self.output, &[line.as_str()])?;
Ok(self)
} }
/// Stop current message /// Stop current message
pub fn stop(&mut self, scope: MessageScope) -> ClientStatus { pub fn stop(&mut self, scope: MessageScope) -> ClientResult<&mut Client<S>> {
self.send_message_command("STOP", scope) self.send_message_command("STOP", scope)
} }
/// Cancel current message /// Cancel current message
pub fn cancel(&mut self, scope: MessageScope) -> ClientStatus { pub fn cancel(&mut self, scope: MessageScope) -> ClientResult<&mut Client<S>> {
self.send_message_command("CANCEL", scope) self.send_message_command("CANCEL", scope)
} }
/// Pause current message /// Pause current message
pub fn pause(&mut self, scope: MessageScope) -> ClientStatus { pub fn pause(&mut self, scope: MessageScope) -> ClientResult<&mut Client<S>> {
self.send_message_command("PAUSE", scope) self.send_message_command("PAUSE", scope)
} }
/// Resume current message /// Resume current message
pub fn resume(&mut self, scope: MessageScope) -> ClientStatus { pub fn resume(&mut self, scope: MessageScope) -> ClientResult<&mut Client<S>> {
self.send_message_command("RESUME", scope) self.send_message_command("RESUME", scope)
} }
client_setter!( client_send!(
set_priority, set_priority,
"Set message priority", "Set message priority",
priority as Priority, priority as Priority,
"SET self PRIORITY {}" "SET self PRIORITY {}"
); );
/// Set debug mode. Return the log location. client_send_boolean!(
pub fn set_debug(&mut self, value: bool) -> ClientResult<String> { set_debug,
let line = format!("SET all DEBUG {}", on_off(value)); "Set debug mode. Return the log location",
let mut answer = Vec::new(); value,
send_lines!(&mut self.input, &mut self.output, &[&line], &mut answer)?; "SET all DEBUG {}"
Client::<S>::parse_single_value(&answer) );
}
client_setter!( client_send!(
set_output_module, set_output_module,
"Set output module", "Set output module",
scope, scope,
@ -298,19 +296,19 @@ impl<S: Read + Write> Client<S> {
"SET {} OUTPUT_MODULE {}" "SET {} OUTPUT_MODULE {}"
); );
client_single_getter!( client_send!(
get_output_module, get_output_module,
"Get the current output module", "Get the current output module",
"GET OUTPUT_MODULE" "GET OUTPUT_MODULE"
); );
client_getter!( client_send!(
list_output_modules, list_output_modules,
"List the available output modules", "List the available output modules",
"LIST OUTPUT_MODULES" "LIST OUTPUT_MODULES"
); );
client_setter!( client_send!(
set_language, set_language,
"Set language code", "Set language code",
scope, scope,
@ -318,16 +316,16 @@ impl<S: Read + Write> Client<S> {
"SET {} LANGUAGE {}" "SET {} LANGUAGE {}"
); );
client_single_getter!(get_language, "Get the current language", "GET LANGUAGE"); client_send!(get_language, "Get the current language", "GET LANGUAGE");
client_boolean_setter!( client_send_boolean!(
set_ssml_mode, set_ssml_mode,
"Set SSML mode (Speech Synthesis Markup Language)", "Set SSML mode (Speech Synthesis Markup Language)",
value, value,
"SET self SSML_MODE {}" "SET self SSML_MODE {}"
); );
client_setter!( client_send!(
set_punctuation_mode, set_punctuation_mode,
"Set punctuation mode", "Set punctuation mode",
scope, scope,
@ -335,7 +333,7 @@ impl<S: Read + Write> Client<S> {
"SET {} PUNCTUATION {}" "SET {} PUNCTUATION {}"
); );
client_boolean_setter!( client_send_boolean!(
set_spelling, set_spelling,
"Set spelling on or off", "Set spelling on or off",
scope, scope,
@ -343,7 +341,7 @@ impl<S: Read + Write> Client<S> {
"SET {} SPELLING {}" "SET {} SPELLING {}"
); );
client_setter!( client_send!(
set_capital_letter_recogn, set_capital_letter_recogn,
"Set capital letters recognition mode", "Set capital letters recognition mode",
scope, scope,
@ -351,7 +349,7 @@ impl<S: Read + Write> Client<S> {
"SET {} CAP_LET_RECOGN {}" "SET {} CAP_LET_RECOGN {}"
); );
client_setter!( client_send!(
set_voice_type, set_voice_type,
"Set the voice type (MALE1, FEMALE1, …)", "Set the voice type (MALE1, FEMALE1, …)",
scope, scope,
@ -359,19 +357,19 @@ impl<S: Read + Write> Client<S> {
"SET {} VOICE_TYPE {}" "SET {} VOICE_TYPE {}"
); );
client_single_getter!( client_send!(
get_voice_type, get_voice_type,
"Get the current pre-defined voice", "Get the current pre-defined voice",
"GET VOICE_TYPE" "GET VOICE_TYPE"
); );
client_getter!( client_send!(
list_voice_types, list_voice_types,
"List the available symbolic voice names", "List the available symbolic voice names",
"LIST VOICES" "LIST VOICES"
); );
client_setter!( client_send!(
set_synthesis_voice, set_synthesis_voice,
"Set the voice", "Set the voice",
scope, scope,
@ -379,24 +377,13 @@ impl<S: Read + Write> Client<S> {
"SET {} SYNTHESIS_VOICE {}" "SET {} SYNTHESIS_VOICE {}"
); );
/// Lists the available voices for the current synthesizer. client_send!(
pub fn list_synthesis_voices(&mut self) -> ClientResult<Vec<SynthesisVoice>> { list_synthesis_voices,
let mut result = Vec::new(); "Lists the available voices for the current synthesizer",
send_lines!( "LIST SYNTHESIS_VOICES"
&mut self.input, );
&mut self.output,
&["LIST SYNTHESIS_VOICES"],
&mut result
)?;
let mut voices = Vec::new();
for name in result.iter() {
let voice = SynthesisVoice::from_str(name.as_str())?;
voices.push(voice);
}
Ok(voices)
}
client_range_setter!( client_send_range!(
set_rate, set_rate,
"Set the rate of speech. n is an integer value within the range from -100 to 100, lower values meaning slower speech.", "Set the rate of speech. n is an integer value within the range from -100 to 100, lower values meaning slower speech.",
scope, scope,
@ -404,9 +391,9 @@ impl<S: Read + Write> Client<S> {
"SET {} RATE {}" "SET {} RATE {}"
); );
client_single_getter!(get_rate, "Get the current rate of speech.", u8, "GET RATE"); client_send!(get_rate, "Get the current rate of speech.", "GET RATE");
client_range_setter!( client_send_range!(
set_pitch, set_pitch,
"Set the pitch of speech. n is an integer value within the range from -100 to 100.", "Set the pitch of speech. n is an integer value within the range from -100 to 100.",
scope, scope,
@ -414,9 +401,9 @@ impl<S: Read + Write> Client<S> {
"SET {} PITCH {}" "SET {} PITCH {}"
); );
client_single_getter!(get_pitch, "Get the current pitch value.", u8, "GET PITCH"); client_send!(get_pitch, "Get the current pitch value.", "GET PITCH");
client_range_setter!( client_send_range!(
set_volume, set_volume,
"Set the volume of speech. n is an integer value within the range from -100 to 100.", "Set the volume of speech. n is an integer value within the range from -100 to 100.",
scope, scope,
@ -424,7 +411,7 @@ impl<S: Read + Write> Client<S> {
"SET {} VOLUME {}" "SET {} VOLUME {}"
); );
client_setter!( client_send!(
set_pause_context, set_pause_context,
"Set the number of (more or less) sentences that should be repeated after a previously paused text is resumed.", "Set the number of (more or less) sentences that should be repeated after a previously paused text is resumed.",
scope, scope,
@ -432,7 +419,7 @@ impl<S: Read + Write> Client<S> {
"SET {} PAUSE_CONTEXT {}" "SET {} PAUSE_CONTEXT {}"
); );
client_boolean_setter!( client_send_boolean!(
set_history, set_history,
"Enable or disable history of received messages.", "Enable or disable history of received messages.",
scope, scope,
@ -440,28 +427,85 @@ impl<S: Read + Write> Client<S> {
"SET {} HISTORY {}" "SET {} HISTORY {}"
); );
client_single_getter!(get_volume, "Get the current volume.", u8, "GET VOLUME"); client_send!(get_volume, "Get the current volume.", "GET VOLUME");
client_setter!(block_begin, "Open a block", "BLOCK BEGIN"); client_send!(block_begin, "Open a block", "BLOCK BEGIN");
client_setter!(block_end, "End a block", "BLOCK END"); client_send!(block_end, "End a block", "BLOCK END");
client_setter!(quit, "Close the connection", "QUIT"); client_send!(quit, "Close the connection", "QUIT");
client_setter!( client_send!(
enable_notification, enable_notification,
"Enable notification events", "Enable notification events",
value as NotificationType, value as NotificationType,
"SET self NOTIFICATION {} on" "SET self NOTIFICATION {} on"
); );
client_setter!( client_send!(
disable_notification, disable_notification,
"Disable notification events", "Disable notification events",
value as NotificationType, value as NotificationType,
"SET self NOTIFICATION {} off" "SET self NOTIFICATION {} off"
); );
/// Receive answer from server
pub fn receive(&mut self, lines: &mut Vec<String>) -> ClientStatus {
crate::protocol::receive_answer(&mut self.input, Some(lines))
}
/// Check status of answer, discard lines.
pub fn check_status(&mut self, expected_code: ReturnCode) -> ClientResult<&mut Client<S>> {
crate::protocol::receive_answer(&mut self.input, None).and_then(|status| {
if status.code == expected_code {
Ok(self)
} else {
Err(ClientError::UnexpectedStatus(status.code))
}
})
}
/// Receive lines
pub fn receive_lines(&mut self, expected_code: ReturnCode) -> ClientResult<Vec<String>> {
let mut lines = Vec::new();
let status = self.receive(&mut lines)?;
if status.code == expected_code {
Ok(lines)
} else {
Err(ClientError::UnexpectedStatus(status.code))
}
}
/// Receive a single string
pub fn receive_string(&mut self, expected_code: ReturnCode) -> ClientResult<String> {
self.receive_lines(expected_code)
.and_then(|lines| Client::<S>::parse_single_value(&lines))
}
/// Receive integer
pub fn receive_u8(&mut self, expected_code: ReturnCode) -> ClientResult<u8> {
self.receive_string(expected_code)
.and_then(|s| s.parse().map_err(|_| ClientError::InvalidType))
}
/// Receive message id
pub fn receive_message_id(&mut self) -> ClientResult<MessageId> {
self.receive_string(OK_MESSAGE_QUEUED)
.and_then(|s| s.parse().map_err(|_| ClientError::InvalidType))
}
/// Receive a list of synthesis voices
pub fn receive_synthesis_voices(&mut self) -> ClientResult<Vec<SynthesisVoice>> {
self.receive_lines(OK_VOICES_LIST_SENT).and_then(|lines| {
let mut voices = Vec::new();
for name in lines.iter() {
let voice = SynthesisVoice::from_str(name.as_str())?;
voices.push(voice);
}
Ok(voices)
})
}
/// Receive a notification /// Receive a notification
pub fn receive_event(&mut self) -> ClientResult<Event> { pub fn receive_event(&mut self) -> ClientResult<Event> {
let mut lines = Vec::new(); let mut lines = Vec::new();
@ -490,13 +534,27 @@ impl<S: Read + Write> Client<S> {
} }
}) })
} }
#[cfg(feature = "metal-io")]
pub fn register(&mut self, poll: &mio::Poll, token: mio::Token) -> ClientResult<()> {
poll.registry().register(
&mut self.socket,
token,
mio::Interest::READABLE | mio::Interest::WRITABLE,
)?;
Ok(())
}
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
#[cfg(not(feature = "metal-io"))]
use std::net::TcpStream; use std::net::TcpStream;
#[cfg(feature = "metal-io")]
use mio::net::TcpStream;
use super::{Client, ClientError}; use super::{Client, ClientError};
#[test] #[test]

@ -7,12 +7,8 @@
// option. All files in the project carrying such notice may not be copied, // option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms. // modified, or distributed except according to those terms.
use std::io::{self, BufReader, BufWriter}; use std::io;
use std::os::unix::net::UnixStream; use std::path::PathBuf;
use std::path::{Path, PathBuf};
use std::time::Duration;
use crate::client::{Client, ClientName, ClientResult};
const SPEECHD_APPLICATION_NAME: &str = "speech-dispatcher"; const SPEECHD_APPLICATION_NAME: &str = "speech-dispatcher";
const SPEECHD_SOCKET_NAME: &str = "speechd.sock"; const SPEECHD_SOCKET_NAME: &str = "speechd.sock";
@ -30,41 +26,73 @@ fn speech_dispatcher_socket() -> io::Result<PathBuf> {
} }
} }
/// Create a pair of FIFO reader and writer #[cfg(not(feature = "metal-io"))]
fn new_pair<P>( mod synchronous {
socket_path: P, use std::io::{BufReader, BufWriter};
read_timeout: Option<Duration>, pub use std::os::unix::net::UnixStream;
) -> io::Result<(BufReader<UnixStream>, BufWriter<UnixStream>)> use std::path::Path;
where use std::time::Duration;
P: AsRef<Path>,
{
let stream = UnixStream::connect(socket_path.as_ref())?;
stream.set_read_timeout(read_timeout)?;
Ok((BufReader::new(stream.try_clone()?), BufWriter::new(stream)))
}
/// New FIFO client use crate::client::{Client, ClientResult};
pub fn new_client<P>(
socket_path: P, /// New FIFO client
client_name: &ClientName, pub fn new_fifo_client<P>(
read_timeout: Option<Duration>, socket_path: P,
) -> ClientResult<Client<UnixStream>> read_timeout: Option<Duration>,
where ) -> ClientResult<Client<UnixStream>>
P: AsRef<Path>, where
{ P: AsRef<Path>,
let (input, output) = new_pair(&socket_path, read_timeout)?; {
Client::new(input, output, client_name) let stream = UnixStream::connect(socket_path.as_ref())?;
stream.set_read_timeout(read_timeout)?;
Client::new(BufReader::new(stream.try_clone()?), BufWriter::new(stream))
}
/// New FIFO client on the standard socket `${XDG_RUNTIME_DIR}/speech-dispatcher/speechd.sock`
pub fn new_default_fifo_client(
read_timeout: Option<Duration>,
) -> ClientResult<Client<UnixStream>> {
let socket_path = super::speech_dispatcher_socket()?;
new_fifo_client(socket_path.as_path(), read_timeout)
}
} }
/// New FIFO client on the standard socket `${XDG_RUNTIME_DIR}/speech-dispatcher/speechd.sock` #[cfg(not(feature = "metal-io"))]
pub fn new_default_client( pub use synchronous::{new_default_fifo_client, new_fifo_client, UnixStream};
client_name: &ClientName,
read_timeout: Option<Duration>, #[cfg(feature = "metal-io")]
) -> ClientResult<Client<UnixStream>> { mod asynchronous {
let socket_path = speech_dispatcher_socket()?; pub use mio::net::UnixStream;
new_client(socket_path.as_path(), client_name, read_timeout) use std::io::{BufReader, BufWriter};
use std::os::unix::net::UnixStream as StdUnixStream;
use std::path::Path;
use crate::client::{Client, ClientResult};
/// New FIFO client
pub fn new_fifo_client<P>(socket_path: P) -> ClientResult<Client<UnixStream>>
where
P: AsRef<Path>,
{
let stream = StdUnixStream::connect(socket_path.as_ref())?;
stream.set_nonblocking(true)?;
Client::new(
BufReader::new(UnixStream::from_std(stream.try_clone()?)),
BufWriter::new(UnixStream::from_std(stream.try_clone()?)),
UnixStream::from_std(stream),
)
}
/// New FIFO client on the standard socket `${XDG_RUNTIME_DIR}/speech-dispatcher/speechd.sock`
pub fn new_default_fifo_client() -> ClientResult<Client<UnixStream>> {
let socket_path = super::speech_dispatcher_socket()?;
new_fifo_client(socket_path.as_path())
}
} }
#[cfg(feature = "metal-io")]
pub use asynchronous::{new_default_fifo_client, new_fifo_client, UnixStream};
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {

@ -16,9 +16,12 @@
//! //!
//! Example //! Example
//! ```no_run //! ```no_run
//! use ssip_client::{new_default_fifo_client, ClientName}; //! use ssip_client::{new_default_fifo_client, ClientName, OK_CLIENT_NAME_SET};
//! let mut client = new_default_fifo_client(&ClientName::new("joe", "hello"), None)?; //! let mut client = new_default_fifo_client(None)?;
//! let msg_id = client.say_line("hello")?; //! client
//! .open(ClientName::new("joe", "hello"))?
//! .check_status(OK_CLIENT_NAME_SET)?;
//! let msg_id = client.speak()?.send_line("hello")?.receive_message_id()?;
//! client.quit()?; //! client.quit()?;
//! # Ok::<(), ssip_client::ClientError>(()) //! # Ok::<(), ssip_client::ClientError>(())
//! ``` //! ```
@ -33,7 +36,6 @@ mod types;
pub use client::{Client, ClientError, ClientName, ClientResult, ClientStatus}; pub use client::{Client, ClientError, ClientName, ClientResult, ClientStatus};
pub use constants::*; pub use constants::*;
pub use fifo::new_client as new_fifo_client; pub use fifo::{new_default_fifo_client, new_fifo_client};
pub use fifo::new_default_client as new_default_fifo_client;
pub use types::StatusLine; pub use types::StatusLine;
pub use types::*; pub use types::*;

@ -21,26 +21,6 @@ macro_rules! invalid_input {
}; };
} }
macro_rules! send_lines {
($input:expr, $output:expr, $lines:expr) => {
crate::protocol::send_lines($output, $lines)
.and_then(|()| crate::protocol::receive_answer($input, None))
};
($input:expr, $output:expr, $lines:expr, $out:expr) => {
crate::protocol::send_lines($output, $lines)
.and_then(|()| crate::protocol::receive_answer($input, Some($out)))
};
}
macro_rules! send_line {
($input:expr, $output:expr, $line:expr) => {
send_lines!($input, $output, &[$line])
};
($input:expr, $output:expr, $fmt:expr, $($arg:tt)*) => {
send_line!($input, $output, format!($fmt, $($arg)*).as_str())
};
}
pub(crate) fn write_lines(output: &mut dyn Write, lines: &[&str]) -> ClientResult<()> { pub(crate) fn write_lines(output: &mut dyn Write, lines: &[&str]) -> ClientResult<()> {
for line in lines.iter() { for line in lines.iter() {
output.write_all(line.as_bytes())?; output.write_all(line.as_bytes())?;

@ -361,6 +361,12 @@ impl fmt::Display for StatusLine {
} }
} }
#[cfg(not(feature = "metal-io"))]
pub use std::fmt::Debug as Source; // Trick to have common implementation for sync and async.
#[cfg(feature = "metal-io")]
pub use mio::event::Source;
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {

@ -7,10 +7,17 @@
// modified, or distributed except according to those terms. // modified, or distributed except according to those terms.
use std::io::{self, BufRead, BufReader, BufWriter, Write}; use std::io::{self, BufRead, BufReader, BufWriter, Write};
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::thread; use std::thread;
use std::os::unix::net::UnixListener;
#[cfg(not(feature = "metal-io"))]
use std::os::unix::net::UnixStream;
#[cfg(feature = "metal-io")]
use mio::net::UnixStream;
use ssip_client::*; use ssip_client::*;
struct Server { struct Server {
@ -75,6 +82,17 @@ impl Server {
} }
} }
#[cfg(not(feature = "metal-io"))]
pub fn new_fifo_client<P>(socket_path: P) -> ClientResult<Client<UnixStream>>
where
P: AsRef<Path>,
{
ssip_client::new_fifo_client(&socket_path, None)
}
#[cfg(feature = "metal-io")]
use ssip_client::new_fifo_client;
/// Create a server and run the client /// Create a server and run the client
/// ///
/// The communication is an array of (["question", ...], "response") /// The communication is an array of (["question", ...], "response")
@ -91,9 +109,12 @@ where
let mut process_wrapper = std::panic::AssertUnwindSafe(process); let mut process_wrapper = std::panic::AssertUnwindSafe(process);
let result = std::panic::catch_unwind(move || { let result = std::panic::catch_unwind(move || {
let handle = Server::run(&server_path, communication); let handle = Server::run(&server_path, communication);
let mut client = let mut client = new_fifo_client(&server_path).unwrap();
ssip_client::new_fifo_client(&server_path, &ClientName::new("test", "test"), None) client
.unwrap(); .open(ClientName::new("test", "test"))
.unwrap()
.check_status(OK_CLIENT_NAME_SET)
.unwrap();
process_wrapper(&mut client).unwrap(); process_wrapper(&mut client).unwrap();
handle.join().unwrap() handle.join().unwrap()
}); });
@ -115,7 +136,7 @@ fn connect_and_quit() -> io::Result<()> {
(&["QUIT\r\n"], "231 HAPPY HACKING\r\n"), (&["QUIT\r\n"], "231 HAPPY HACKING\r\n"),
], ],
|client| { |client| {
assert_eq!(OK_BYE, client.quit().unwrap().code); client.quit().unwrap().check_status(OK_BYE).unwrap();
Ok(()) Ok(())
}, },
) )
@ -133,7 +154,18 @@ fn say_one_line() -> io::Result<()> {
), ),
], ],
|client| { |client| {
assert_eq!("21", client.say_line("Hello, world").unwrap(),); assert_eq!(
"21",
client
.speak()
.unwrap()
.check_status(OK_RECEIVING_DATA)
.unwrap()
.send_line("Hello, world")
.unwrap()
.receive_message_id()
.unwrap()
);
Ok(()) Ok(())
}, },
) )
@ -146,8 +178,7 @@ macro_rules! test_setter {
test_client( test_client(
&[SET_CLIENT_COMMUNICATION, (&[$question], $answer)], &[SET_CLIENT_COMMUNICATION, (&[$question], $answer)],
|client| { |client| {
let status = client.$setter($($arg)*).unwrap(); client.$setter($($arg)*).unwrap().check_status($code).unwrap();
assert_eq!($code, status.code);
Ok(()) Ok(())
}, },
) )
@ -156,29 +187,32 @@ macro_rules! test_setter {
} }
macro_rules! test_getter { macro_rules! test_getter {
($getter:ident, $question:expr, $answer:expr, $value:expr) => { ($getter:ident, $receive:ident, $question:expr, $answer:expr, $value:expr) => {
#[test] #[test]
fn $getter() -> io::Result<()> { fn $getter() -> io::Result<()> {
test_client( test_client(
&[SET_CLIENT_COMMUNICATION, (&[$question], $answer)], &[SET_CLIENT_COMMUNICATION, (&[$question], $answer)],
|client| { |client| {
let value = client.$getter().unwrap(); let value = client.$getter().unwrap().$receive(251).unwrap();
assert_eq!($value, value); assert_eq!($value, value);
Ok(()) Ok(())
}, },
) )
} }
}; };
($getter:ident, $question:expr, $answer:expr, $value:expr) => {
test_getter!($getter, receive_string, $question, $answer, $value);
};
} }
macro_rules! test_list { macro_rules! test_list {
($getter:ident, $question:expr, $answer:expr, $values:expr) => { ($getter:ident, $question:expr, $answer:expr, $code:expr, $values:expr) => {
#[test] #[test]
fn $getter() -> io::Result<()> { fn $getter() -> io::Result<()> {
test_client( test_client(
&[SET_CLIENT_COMMUNICATION, (&[$question], $answer)], &[SET_CLIENT_COMMUNICATION, (&[$question], $answer)],
|client| { |client| {
let values = client.$getter().unwrap(); let values = client.$getter().unwrap().receive_lines($code).unwrap();
assert_eq!($values, values.as_slice()); assert_eq!($values, values.as_slice());
Ok(()) Ok(())
}, },
@ -206,7 +240,11 @@ fn set_debug() -> io::Result<()> {
), ),
], ],
|client| { |client| {
let output = client.set_debug(true).unwrap(); let output = client
.set_debug(true)
.unwrap()
.receive_string(OK_DEBUG_SET)
.unwrap();
assert_eq!("/run/user/100/speech-dispatcher/log/debug", output); assert_eq!("/run/user/100/speech-dispatcher/log/debug", output);
Ok(()) Ok(())
}, },
@ -233,6 +271,7 @@ test_list!(
list_output_modules, list_output_modules,
"LIST OUTPUT_MODULES\r\n", "LIST OUTPUT_MODULES\r\n",
"250-espeak-ng\r\n250-festival\r\n250 OK MODULE LIST SENT\r\n", "250-espeak-ng\r\n250-festival\r\n250 OK MODULE LIST SENT\r\n",
250,
&["espeak-ng", "festival"] &["espeak-ng", "festival"]
); );
@ -263,6 +302,7 @@ test_setter!(
test_getter!( test_getter!(
get_rate, get_rate,
receive_u8,
"GET RATE\r\n", "GET RATE\r\n",
"251-0\r\n251 OK GET RETURNED\r\n", "251-0\r\n251 OK GET RETURNED\r\n",
0 0
@ -279,6 +319,7 @@ test_setter!(
test_getter!( test_getter!(
get_volume, get_volume,
receive_u8,
"GET VOLUME\r\n", "GET VOLUME\r\n",
"251-100\r\n251 OK GET RETURNED\r\n", "251-100\r\n251 OK GET RETURNED\r\n",
100 100
@ -286,6 +327,7 @@ test_getter!(
test_getter!( test_getter!(
get_pitch, get_pitch,
receive_u8,
"GET PITCH\r\n", "GET PITCH\r\n",
"251-0\r\n251 OK GET RETURNED\r\n", "251-0\r\n251 OK GET RETURNED\r\n",
0 0
@ -355,6 +397,7 @@ test_list!(
list_voice_types, list_voice_types,
"LIST VOICES\r\n", "LIST VOICES\r\n",
"249-MALE1\r\n249-MALE2\r\n249-FEMALE1\r\n249-FEMALE2\r\n249-CHILD_MALE\r\n249-CHILD_FEMALE\r\n249 OK VOICE LIST SENT\r\n", "249-MALE1\r\n249-MALE2\r\n249-FEMALE1\r\n249-FEMALE2\r\n249-CHILD_MALE\r\n249-CHILD_FEMALE\r\n249 OK VOICE LIST SENT\r\n",
249,
&[ "MALE1", "MALE2", "FEMALE1", "FEMALE2", "CHILD_MALE", "CHILD_FEMALE" ] &[ "MALE1", "MALE2", "FEMALE1", "FEMALE2", "CHILD_MALE", "CHILD_FEMALE" ]
); );
@ -369,7 +412,7 @@ fn list_synthesis_voices() -> io::Result<()> {
), ),
], ],
|client| { |client| {
let voices = client.list_synthesis_voices().unwrap(); let voices = client.list_synthesis_voices().unwrap().receive_synthesis_voices().unwrap();
let expected_voices: [SynthesisVoice; 3] = [ SynthesisVoice::new("Amharic", Some("am"), None), let expected_voices: [SynthesisVoice; 3] = [ SynthesisVoice::new("Amharic", Some("am"), None),
SynthesisVoice::new("Greek+Auntie", Some("el"), Some("Auntie")), SynthesisVoice::new("Greek+Auntie", Some("el"), Some("Auntie")),
SynthesisVoice::new("Vietnamese (Southern)+shelby", Some("vi-VN-X-SOUTH"), Some("shelby")), SynthesisVoice::new("Vietnamese (Southern)+shelby", Some("vi-VN-X-SOUTH"), Some("shelby")),
@ -395,7 +438,18 @@ fn receive_notification() -> io::Result<()> {
), ),
], ],
|client| { |client| {
assert_eq!("21", client.say_line("Hello, world").unwrap(),); assert_eq!(
"21",
client
.speak()
.unwrap()
.check_status(OK_RECEIVING_DATA)
.unwrap()
.send_line("Hello, world")
.unwrap()
.receive_message_id()
.unwrap()
);
match client.receive_event() { match client.receive_event() {
Ok(Event { Ok(Event {
ntype: EventType::Begin, ntype: EventType::Begin,

Loading…
Cancel
Save