add all commands except notification and history, and no tests

main
Laurent Pelecq 3 years ago
parent c6527cb793
commit 5a656d5d27

@ -11,6 +11,8 @@ license = "MIT OR Apache-2.0"
[dependencies]
dirs = "3"
thiserror = "1"
strum = "0.20"
strum_macros = "0.20"
[dev-dependencies]
libc = "0"

@ -2,7 +2,7 @@ use ssip_client::ClientResult;
fn main() -> ClientResult<()> {
let mut client = ssip_client::new_unix_client("joe", "hello", "main")?;
let msg_id = client.speak1("hello")?;
let msg_id = client.say_line("hello")?;
println!("message: {}", msg_id);
client.quit()?;
Ok(())

@ -9,9 +9,13 @@
use std::fmt;
use std::io::{self, Read, Write};
use std::str::FromStr;
use thiserror::Error as ThisError;
use crate::constants::{ReturnCode, OK_RECEIVING_DATA};
use crate::constants::{
CapitalLettersRecognitionMode, ClientTarget, KeyName, MessageId, MessageTarget, Priority,
PunctuationMode, ReturnCode, SynthesisVoice, OK_RECEIVING_DATA,
};
/// Command status line
///
@ -39,6 +43,12 @@ pub enum ClientError {
Io(io::Error),
#[error("SSIP: {0}")]
Ssip(StatusLine),
#[error("No line in result")]
NoLine,
#[error("Too many lines")]
TooManyLines,
#[error("Invalid type")]
InvalidType,
}
impl From<io::Error> for ClientError {
@ -53,10 +63,41 @@ pub type ClientResult<T> = Result<T, ClientError>;
/// Client result consisting in a single status line
pub type ClientStatus = ClientResult<StatusLine>;
/// Message identifier
pub type MessageId = String;
macro_rules! client_method {
macro_rules! client_setter {
($name:ident, $doc:expr, $target_name:ident, $value_name:ident as $value_type:ty, $fmt:expr, $value:expr) => {
#[doc=$doc]
pub fn $name(
&mut self,
$target_name: ClientTarget,
$value_name: $value_type,
) -> ClientStatus {
let line = match $target_name {
ClientTarget::Current => format!($fmt, "self", $value),
ClientTarget::All => format!($fmt, "all", $value),
ClientTarget::Message(id) => format!($fmt, id, $value),
};
send_lines!(&mut self.input, &mut self.output, &[line.as_str()])
}
};
($name:ident, $doc:expr, $target_name:ident, $value_name:ident as $value_type:ty, $fmt:expr) => {
client_setter!(
$name,
$doc,
$target_name,
$value_name as $value_type,
$fmt,
$value_name
);
};
($name:ident, $doc:expr, $value_name:ident as $value_type:ty, $fmt:expr, $value:expr) => {
#[doc=$doc]
pub fn $name(&mut self, $value_name: $value_type) -> ClientStatus {
send_line!(&mut self.input, &mut self.output, $fmt, $value)
}
};
($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);
};
($name:ident, $doc:expr, $line:expr) => {
#[doc=$doc]
pub fn $name(&mut self) -> ClientStatus {
@ -65,6 +106,74 @@ macro_rules! client_method {
};
}
macro_rules! client_boolean_setter {
($name:ident, $doc:expr, $target_name:ident, $value_name:ident, $fmt:expr) => {
client_setter!(
$name,
$doc,
$target_name,
$value_name as bool,
$fmt,
if $value_name { "ON" } else { "OFF" }
);
};
($name:ident, $doc:expr, $value_name:ident, $fmt:expr) => {
client_setter!(
$name,
$doc,
$value_name as bool,
$fmt,
if $value_name { "ON" } else { "OFF" }
);
};
}
macro_rules! client_range_setter {
($name:ident, $doc:expr, $target_name:ident, $value_name:ident, $fmt:expr) => {
client_setter!(
$name,
$doc,
$target_name,
$value_name as i8,
$fmt,
std::cmp::max(-100, std::cmp::min(100, $value_name))
);
};
}
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
pub struct Client<S: Read + Write> {
input: io::BufReader<S>,
@ -91,25 +200,242 @@ impl<S: Read + Write> Client<S> {
Ok(Self { input, output })
}
fn parse_single_value(lines: &[String]) -> ClientResult<String> {
match lines.len() {
0 => Err(ClientError::NoLine),
1 => Ok(lines[0].to_string()),
_ => Err(ClientError::TooManyLines),
}
}
/// Send text to server
pub fn speak(&mut self, lines: &[&str]) -> ClientResult<MessageId> {
pub fn say_text(&mut self, lines: &[&str]) -> ClientResult<MessageId> {
let status = send_line!(&mut self.input, &mut self.output, "SPEAK")?;
if status.code == OK_RECEIVING_DATA {
const END_OF_DATA: [&str; 1] = ["."];
crate::protocol::write_lines(&mut self.output, lines)?;
let mut answer = Vec::new();
send_lines!(&mut self.input, &mut self.output, &END_OF_DATA, &mut answer)
.map(|_| answer[0].to_string())
send_lines!(&mut self.input, &mut self.output, &END_OF_DATA, &mut answer)?;
Client::<S>::parse_single_value(&answer)
} else {
Err(ClientError::Ssip(status))
}
}
/// Send a single line to the server
pub fn speak1(&mut self, line: &str) -> ClientResult<MessageId> {
pub fn say_line(&mut self, line: &str) -> ClientResult<MessageId> {
let lines: [&str; 1] = [line];
self.speak(&lines)
self.say_text(&lines)
}
/// Send a char to the server
pub fn say_char(&mut self, ch: char) -> ClientResult<MessageId> {
let line = format!("CHAR {}", ch);
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
pub fn say_key_name(&mut self, keyname: KeyName) -> ClientResult<MessageId> {
let line = format!("KEY {}", keyname);
let mut answer = Vec::new();
send_lines!(&mut self.input, &mut self.output, &[&line], &mut answer)?;
Client::<S>::parse_single_value(&answer)
}
client_method!(quit, "Close the connection", "QUIT");
/// Action on a message or a group of messages
fn send_message_command(&mut self, command: &str, target: MessageTarget) -> ClientStatus {
let line = match target {
MessageTarget::Last => format!("{} self", command),
MessageTarget::All => format!("{} all", command),
MessageTarget::Message(id) => format!("{} {}", command, id),
};
send_lines!(&mut self.input, &mut self.output, &[line.as_str()])
}
/// Stop current message
pub fn stop(&mut self, target: MessageTarget) -> ClientStatus {
self.send_message_command("STOP", target)
}
/// Cancel current message
pub fn cancel(&mut self, target: MessageTarget) -> ClientStatus {
self.send_message_command("CANCEL", target)
}
/// Pause current message
pub fn pause(&mut self, target: MessageTarget) -> ClientStatus {
self.send_message_command("PAUSE", target)
}
/// Resume current message
pub fn resume(&mut self, target: MessageTarget) -> ClientStatus {
self.send_message_command("RESUME", target)
}
client_setter!(
set_priority,
"Set message priority",
priority as Priority,
"SET self PRIORITY {}"
);
client_boolean_setter!(set_debug, "Set debug mode", value, "SET all DEBUG {}");
client_setter!(
set_output_module,
"Set output module",
target,
value as &str,
"SET {} OUTPUT_MODULE {}"
);
client_single_getter!(
get_output_module,
"Get the current output module",
"GET OUTPUT_MODULE"
);
client_getter!(
list_output_module,
"List the available output modules",
"LIST OUTPUT_MODULES"
);
client_setter!(
set_language,
"Set language code",
target,
value as &str,
"SET {} LANGUAGE {}"
);
client_boolean_setter!(
set_ssml_mode,
"Set SSML mode (Speech Synthesis Markup Language)",
value,
"SET self SSML_MODE {}"
);
client_setter!(
set_punctuation_mode,
"Set punctuation mode",
target,
value as PunctuationMode,
"SET {} PUNCTUATION {}"
);
client_boolean_setter!(
set_spelling,
"Set spelling on or off",
target,
value,
"SET {} SPELLING {}"
);
client_setter!(
set_capital_letter_recogn,
"Set capital letters recognition mode",
target,
value as CapitalLettersRecognitionMode,
"SET {} CAP_LET_RECOGN {}"
);
client_setter!(
set_voice_type,
"Set the voice type (MALE1, FEMALE1, …)",
target,
value as &str,
"SET {} VOICE_TYPE {}"
);
client_getter!(
get_voice_type,
"Get the current pre-defined voice",
"GET VOICE_TYPE"
);
client_getter!(
list_voices,
"List the available symbolic voice names",
"LIST VOICES"
);
client_setter!(
set_synthesis_voice,
"Set the voice",
target,
value as &str,
"SET {} SYNTHESIS_VOICE {}"
);
/// Lists the available voices for the current synthesizer.
pub fn list_synthesis_voice(&mut self) -> ClientResult<Vec<SynthesisVoice>> {
let mut result = Vec::new();
send_lines!(
&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!(
set_rate,
"Set the rate of speech. n is an integer value within the range from -100 to 100, lower values meaning slower speech.",
target,
value,
"SET {} RATE {}"
);
client_single_getter!(get_rate, "Get the current rate of speech.", u8, "GET RATE");
client_range_setter!(
set_pitch,
"Set the pitch of speech. n is an integer value within the range from -100 to 100.",
target,
value,
"SET {} PITCH {}"
);
client_single_getter!(get_pitch, "Get the current pitch value.", u8, "GET PITCH");
client_range_setter!(
set_volume,
"Set the volume of speech. n is an integer value within the range from -100 to 100.",
target,
value,
"SET {} VOLUME {}"
);
client_setter!(
set_pause_context,
"Set the number of (more or less) sentences that should be repeated after a previously paused text is resumed.",
target,
value as u8,
"SET {} PAUSE_CONTEXT {}"
);
client_boolean_setter!(
set_history,
"Enable or disable history of received messages.",
target,
value,
"SET {} HISTORY {}"
);
client_single_getter!(get_volume, "Get the current volume.", u8, "GET VOLUME");
client_setter!(block_begin, "Open a block", "BLOCK BEGIN");
client_setter!(block_end, "End a block", "BLOCK END");
client_setter!(quit, "Close the connection", "QUIT");
}

@ -7,6 +7,9 @@
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.
use std::str::FromStr;
use strum_macros::Display as StrumDisplay;
/// Return code of SSIP commands
pub type ReturnCode = u16;
@ -288,3 +291,250 @@ pub const ERR_PARAMETER_NOT_ON_OFF: ReturnCode = 513;
/// Client error: ERR PARAMETER INVALID
pub const ERR_PARAMETER_INVALID: ReturnCode = 514;
/// Message identifier
pub type MessageId = String;
/// Client identifier
pub type ClientId = String;
/// Message identifiers
#[derive(Debug)]
pub enum MessageTarget {
/// Last message from current client
Last,
/// Messages from all clients
All,
/// Specific message
Message(MessageId),
}
/// Client identifiers
#[derive(Debug)]
pub enum ClientTarget {
/// Current client
Current,
/// All clients
All,
/// Specific message
Message(MessageId),
}
/// Priority
#[derive(StrumDisplay, Debug)]
pub enum Priority {
#[strum(serialize = "progress")]
Progress,
#[strum(serialize = "notification")]
Notification,
#[strum(serialize = "message")]
Message,
#[strum(serialize = "text")]
Text,
#[strum(serialize = "important")]
Important,
}
/// Punctuation mode.
#[derive(StrumDisplay, Debug)]
pub enum PunctuationMode {
#[strum(serialize = "none")]
None,
#[strum(serialize = "some")]
Some,
#[strum(serialize = "most")]
Most,
#[strum(serialize = "all")]
All,
}
/// Capital letters recognition mode.
#[derive(StrumDisplay, Debug)]
pub enum CapitalLettersRecognitionMode {
#[strum(serialize = "none")]
None,
#[strum(serialize = "spell")]
Spell,
#[strum(serialize = "icon")]
Icon,
}
/// Symbolic key names
#[derive(StrumDisplay, Debug)]
pub enum KeyName {
#[strum(serialize = "space")]
Space,
#[strum(serialize = "underscore")]
Underscore,
#[strum(serialize = "double-quote")]
DoubleQuote,
#[strum(serialize = "alt")]
Alt,
#[strum(serialize = "control")]
Control,
#[strum(serialize = "hyper")]
Hyper,
#[strum(serialize = "meta")]
Meta,
#[strum(serialize = "shift")]
Shift,
#[strum(serialize = "super")]
Super,
#[strum(serialize = "backspace")]
Backspace,
#[strum(serialize = "break")]
Break,
#[strum(serialize = "delete")]
Delete,
#[strum(serialize = "down")]
Down,
#[strum(serialize = "end")]
End,
#[strum(serialize = "enter")]
Enter,
#[strum(serialize = "escape")]
Escape,
#[strum(serialize = "f1")]
F1,
#[strum(serialize = "f2")]
F2,
#[strum(serialize = "f3")]
F3,
#[strum(serialize = "f4")]
F4,
#[strum(serialize = "f5")]
F5,
#[strum(serialize = "f6")]
F6,
#[strum(serialize = "f7")]
F7,
#[strum(serialize = "f8")]
F8,
#[strum(serialize = "f9")]
F9,
#[strum(serialize = "f10")]
F10,
#[strum(serialize = "f11")]
F11,
#[strum(serialize = "f12")]
F12,
#[strum(serialize = "f13")]
F13,
#[strum(serialize = "f14")]
F14,
#[strum(serialize = "f15")]
F15,
#[strum(serialize = "f16")]
F16,
#[strum(serialize = "f17")]
F17,
#[strum(serialize = "f18")]
F18,
#[strum(serialize = "f19")]
F19,
#[strum(serialize = "f20")]
F20,
#[strum(serialize = "f21")]
F21,
#[strum(serialize = "f22")]
F22,
#[strum(serialize = "f23")]
F23,
#[strum(serialize = "f24")]
F24,
#[strum(serialize = "home")]
Home,
#[strum(serialize = "insert")]
Insert,
#[strum(serialize = "kp-*")]
KpMultiply,
#[strum(serialize = "kp-+")]
KpPlus,
#[strum(serialize = "kp--")]
KpMinus,
#[strum(serialize = "kp-.")]
KpDot,
#[strum(serialize = "kp-/")]
KpDivide,
#[strum(serialize = "kp-0")]
Kp0,
#[strum(serialize = "kp-1")]
Kp1,
#[strum(serialize = "kp-2")]
Kp2,
#[strum(serialize = "kp-3")]
Kp3,
#[strum(serialize = "kp-4")]
Kp4,
#[strum(serialize = "kp-5")]
Kp5,
#[strum(serialize = "kp-6")]
Kp6,
#[strum(serialize = "kp-7")]
Kp7,
#[strum(serialize = "kp-8")]
Kp8,
#[strum(serialize = "kp-9")]
Kp9,
#[strum(serialize = "kp-enter")]
KpEnter,
#[strum(serialize = "left")]
Left,
#[strum(serialize = "menu")]
Menu,
#[strum(serialize = "next")]
Next,
#[strum(serialize = "num-lock")]
NumLock,
#[strum(serialize = "pause")]
Pause,
#[strum(serialize = "print")]
Print,
#[strum(serialize = "prior")]
Prior,
#[strum(serialize = "return")]
Return,
#[strum(serialize = "right")]
Right,
#[strum(serialize = "scroll-lock")]
ScrollLock,
#[strum(serialize = "tab")]
Tab,
#[strum(serialize = "up")]
Up,
#[strum(serialize = "window")]
Window,
}
/// Synthesis voice
pub struct SynthesisVoice {
pub name: String,
pub language: Option<String>,
pub dialect: Option<String>,
}
impl SynthesisVoice {
/// Parse Option::None or string "none" into Option::None
fn parse_none(token: Option<&str>) -> Option<String> {
match token {
Some(s) => match s {
"none" => None,
s => Some(s.to_string()),
},
None => None,
}
}
}
impl FromStr for SynthesisVoice {
type Err = std::io::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut iter = s.split_whitespace();
Ok(SynthesisVoice {
name: String::from(iter.next().unwrap()),
language: SynthesisVoice::parse_none(iter.next()),
dialect: SynthesisVoice::parse_none(iter.next()),
})
}
}

@ -17,7 +17,7 @@
//! Example
//! ```no_run
//! let mut client = ssip_client::new_unix_client("joe", "hello", "main")?;
//! let msg_id = client.speak1("hello")?;
//! let msg_id = client.say_line("hello")?;
//! client.quit()?;
//! # Ok::<(), ssip_client::ClientError>(())
//! ```

@ -173,7 +173,7 @@ mod tests {
}
#[test]
fn speak_one_line() -> io::Result<()> {
fn say_one_line() -> io::Result<()> {
test_client(
&[
SET_CLIENT_COMMUNICATION,
@ -184,7 +184,7 @@ mod tests {
),
],
|client| {
assert_eq!("21", client.speak1("Hello, world").unwrap(),);
assert_eq!("21", client.say_line("Hello, world").unwrap(),);
Ok(())
},
)

Loading…
Cancel
Save