ionpak-thermostat/firmware/src/command_parser.rs

122 lines
2.9 KiB
Rust
Raw Normal View History

use logos::Logos;
2019-09-11 05:37:51 +08:00
use super::session::ReportMode;
#[derive(Logos, Debug, PartialEq)]
enum Token {
#[end]
End,
#[error]
Error,
#[token = "Quit"]
Quit,
#[token = "show"]
Show,
#[token = "channel"]
Channel,
#[token = "report"]
Report,
#[token = "mode"]
Mode,
#[token = "off"]
Off,
#[token = "once"]
Once,
#[token = "continuous"]
Continuous,
2019-09-12 22:12:03 +08:00
#[token = "enable"]
Enable,
#[token = "disable"]
Disable,
2019-09-11 05:37:51 +08:00
#[regex = "[0-9]+"]
Number,
}
#[derive(Debug)]
pub enum Error {
Parser,
UnexpectedEnd,
UnexpectedToken(Token),
2019-09-12 22:12:03 +08:00
NoSuchChannel,
2019-09-11 05:37:51 +08:00
}
#[derive(Debug)]
pub enum ShowCommand {
2019-09-11 05:37:51 +08:00
ReportMode,
}
2019-09-12 22:12:03 +08:00
#[derive(Debug)]
pub enum ChannelCommand {
Enable,
Disable,
}
2019-09-11 05:37:51 +08:00
#[derive(Debug)]
pub enum Command {
Quit,
Show(ShowCommand),
2019-09-11 05:37:51 +08:00
Report(ReportMode),
2019-09-12 22:12:03 +08:00
Channel(u8, ChannelCommand),
2019-09-11 05:37:51 +08:00
}
2019-09-12 22:12:03 +08:00
const CHANNEL_IDS: &'static [&'static str] = &[
"0", "1", "2", "3",
];
2019-09-11 05:37:51 +08:00
impl Command {
pub fn parse(input: &str) -> Result<Self, Error> {
let mut lexer = Token::lexer(input);
macro_rules! choice {
[$($token: tt => $block: stmt,)*] => {
match lexer.token {
$(
Token::$token => {
lexer.advance();
$block
}
)*
Token::End => Err(Error::UnexpectedEnd),
_ => Err(Error::UnexpectedToken(lexer.token))
}
}
}
choice![
Quit => Ok(Command::Quit),
Report => choice![
Mode => choice![
End => Ok(Command::Show(ShowCommand::ReportMode)),
2019-09-11 05:37:51 +08:00
Off => Ok(Command::Report(ReportMode::Off)),
Once => Ok(Command::Report(ReportMode::Once)),
Continuous => Ok(Command::Report(ReportMode::Continuous)),
],
End => Ok(Command::Report(ReportMode::Once)),
],
2019-09-12 22:12:03 +08:00
Channel => choice![
Number => {
let channel = CHANNEL_IDS.iter()
.position(|id| *id == lexer.slice());
match channel {
Some(channel) => {
choice![
Enable => Ok(Command::Channel(
channel as u8,
ChannelCommand::Enable
)),
Disable => Ok(Command::Channel(
channel as u8,
ChannelCommand::Enable
)),
]
}
None => Err(Error::NoSuchChannel)
}
},
],
2019-09-11 05:37:51 +08:00
]
}
}