#![allow(dead_code)]
use std::io::ErrorKind;
use serde_json::Value;
use crate::{io_err, Device, Error, HostErr, Reply};
pub const COMMANDS: &[(&str, &[&str])] = &[
("sys.claim", &[]),
("sys.release", &[]),
("sys.challenge", &[]),
("sys.unlock", &["tier", "nonce", "dna", "sig"]),
("sys.hello", &[]),
("id.boards", &["seg"]),
("power.status", &[]),
("power.up", &[]),
("adio.mode", &["slot", "ch1", "ch2"]),
("adio.fb", &["slot", "on"]),
("adio.dout", &["slot", "mask"]),
("adio.adc", &["slot", "ch", "n"]),
];
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
#[non_exhaustive]
pub enum SegBoards {
Main,
Slot0,
Slot1,
Slot2,
Slot3,
Slot4,
Slot5,
Slot6,
Slot7,
}
impl SegBoards {
pub const fn token(self) -> &'static str {
match self {
SegBoards::Main => "main",
SegBoards::Slot0 => "slot0",
SegBoards::Slot1 => "slot1",
SegBoards::Slot2 => "slot2",
SegBoards::Slot3 => "slot3",
SegBoards::Slot4 => "slot4",
SegBoards::Slot5 => "slot5",
SegBoards::Slot6 => "slot6",
SegBoards::Slot7 => "slot7",
}
}
pub fn from_token(s: &str) -> Option<Self> {
Some(match s {
"main" => SegBoards::Main,
"slot0" => SegBoards::Slot0,
"slot1" => SegBoards::Slot1,
"slot2" => SegBoards::Slot2,
"slot3" => SegBoards::Slot3,
"slot4" => SegBoards::Slot4,
"slot5" => SegBoards::Slot5,
"slot6" => SegBoards::Slot6,
"slot7" => SegBoards::Slot7,
_ => return None,
})
}
}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
#[non_exhaustive]
pub enum ChMode {
Off,
In,
Out,
Adc,
Dac,
}
impl ChMode {
pub const fn token(self) -> &'static str {
match self {
ChMode::Off => "off",
ChMode::In => "in",
ChMode::Out => "out",
ChMode::Adc => "adc",
ChMode::Dac => "dac",
}
}
pub fn from_token(s: &str) -> Option<Self> {
Some(match s {
"off" => ChMode::Off,
"in" => ChMode::In,
"out" => ChMode::Out,
"adc" => ChMode::Adc,
"dac" => ChMode::Dac,
_ => return None,
})
}
}
#[derive(Clone, Debug)]
pub struct SysHello {
pub proto: u8,
pub cmdset: String,
pub kdi: String,
pub board_id: u32,
pub fw: String,
pub gw: String,
pub tiers: String,
}
impl SysHello {
fn parse(r: &Reply) -> Result<Self, Error> {
Ok(Self {
proto: uint(r, "proto")?,
cmdset: text(r, "cmdset")?,
kdi: text(r, "kdi")?,
board_id: uint(r, "board_id")?,
fw: text(r, "fw")?,
gw: text(r, "gw")?,
tiers: text(r, "tiers")?,
})
}
}
#[derive(Clone, Debug)]
pub struct IdBoardsEntry {
pub addr: u8,
pub serial: String,
}
impl IdBoardsEntry {
fn parse(v: &Value) -> Result<Self, Error> {
Ok(Self {
addr: uint(v, "addr")?,
serial: text(v, "serial")?,
})
}
}
#[derive(Clone, Debug)]
pub struct IdBoards {
pub boards: Vec<IdBoardsEntry>,
}
impl IdBoards {
fn parse(r: &Reply) -> Result<Self, Error> {
Ok(Self {
boards: objects(r, "boards", IdBoardsEntry::parse)?,
})
}
}
#[derive(Clone, Debug)]
pub struct PowerStatus {
pub present: u8,
pub reverify: bool,
}
impl PowerStatus {
fn parse(r: &Reply) -> Result<Self, Error> {
Ok(Self {
present: uint(r, "present")?,
reverify: flag(r, "reverify")?,
})
}
}
#[derive(Clone, Debug)]
pub struct PowerUp {
pub ok: bool,
pub present: u8,
}
impl PowerUp {
fn parse(r: &Reply) -> Result<Self, Error> {
Ok(Self {
ok: flag(r, "ok")?,
present: uint(r, "present")?,
})
}
}
#[derive(Clone, Debug)]
pub struct AdioMode {
pub slot: u8,
pub ch_mode: u16,
}
impl AdioMode {
fn parse(r: &Reply) -> Result<Self, Error> {
Ok(Self {
slot: uint(r, "slot")?,
ch_mode: uint(r, "ch_mode")?,
})
}
}
#[derive(Clone, Debug)]
pub struct AdioFb {
pub slot: u8,
pub fb: u8,
}
impl AdioFb {
fn parse(r: &Reply) -> Result<Self, Error> {
Ok(Self {
slot: uint(r, "slot")?,
fb: uint(r, "fb")?,
})
}
}
#[derive(Clone, Debug)]
pub struct AdioDout {
pub slot: u8,
pub dout: u8,
pub din: u8,
}
impl AdioDout {
fn parse(r: &Reply) -> Result<Self, Error> {
Ok(Self {
slot: uint(r, "slot")?,
dout: uint(r, "dout")?,
din: uint(r, "din")?,
})
}
}
#[derive(Clone, Debug)]
pub struct AdioAdc {
pub slot: u8,
pub ch: u8,
pub codes: Vec<u16>,
pub valid: Vec<bool>,
}
impl AdioAdc {
fn parse(r: &Reply) -> Result<Self, Error> {
Ok(Self {
slot: uint(r, "slot")?,
ch: uint(r, "ch")?,
codes: uints(r, "codes")?,
valid: flags(r, "valid")?,
})
}
}
pub trait Commands {
fn sys_hello(&mut self) -> Result<SysHello, Error>;
fn id_boards(&mut self, seg: SegBoards) -> Result<IdBoards, Error>;
fn power_status(&mut self) -> Result<PowerStatus, Error>;
fn power_up(&mut self) -> Result<PowerUp, Error>;
fn adio_mode(&mut self, slot: u8, ch1: ChMode, ch2: ChMode) -> Result<AdioMode, Error>;
fn adio_fb(&mut self, slot: u8, on: u8) -> Result<AdioFb, Error>;
fn adio_dout(&mut self, slot: u8, mask: u8) -> Result<AdioDout, Error>;
fn adio_adc(&mut self, slot: u8, ch: u8, n: Option<u8>) -> Result<AdioAdc, Error>;
}
impl Commands for Device {
fn sys_hello(&mut self) -> Result<SysHello, Error> {
let reply = checked(self.raw_cmd("sys.hello", &[])?)?;
SysHello::parse(&reply)
}
fn id_boards(&mut self, seg: SegBoards) -> Result<IdBoards, Error> {
let args: Vec<String> = vec![seg.token().to_string()];
let args: Vec<&str> = args.iter().map(String::as_str).collect();
let reply = checked(self.raw_cmd("id.boards", &args)?)?;
IdBoards::parse(&reply)
}
fn power_status(&mut self) -> Result<PowerStatus, Error> {
let reply = checked(self.raw_cmd("power.status", &[])?)?;
PowerStatus::parse(&reply)
}
fn power_up(&mut self) -> Result<PowerUp, Error> {
let reply = checked(self.raw_cmd("power.up", &[])?)?;
PowerUp::parse(&reply)
}
fn adio_mode(&mut self, slot: u8, ch1: ChMode, ch2: ChMode) -> Result<AdioMode, Error> {
if slot > 7 {
return Err(Error::Host(HostErr::HostUnsafeArg));
}
let args: Vec<String> = vec![
slot.to_string(),
ch1.token().to_string(),
ch2.token().to_string(),
];
let args: Vec<&str> = args.iter().map(String::as_str).collect();
let reply = checked(self.raw_cmd("adio.mode", &args)?)?;
AdioMode::parse(&reply)
}
fn adio_fb(&mut self, slot: u8, on: u8) -> Result<AdioFb, Error> {
if slot > 7 {
return Err(Error::Host(HostErr::HostUnsafeArg));
}
if on > 1 {
return Err(Error::Host(HostErr::HostUnsafeArg));
}
let args: Vec<String> = vec![slot.to_string(), on.to_string()];
let args: Vec<&str> = args.iter().map(String::as_str).collect();
let reply = checked(self.raw_cmd("adio.fb", &args)?)?;
AdioFb::parse(&reply)
}
fn adio_dout(&mut self, slot: u8, mask: u8) -> Result<AdioDout, Error> {
if slot > 7 {
return Err(Error::Host(HostErr::HostUnsafeArg));
}
if mask > 3 {
return Err(Error::Host(HostErr::HostUnsafeArg));
}
let args: Vec<String> = vec![slot.to_string(), mask.to_string()];
let args: Vec<&str> = args.iter().map(String::as_str).collect();
let reply = checked(self.raw_cmd("adio.dout", &args)?)?;
AdioDout::parse(&reply)
}
fn adio_adc(&mut self, slot: u8, ch: u8, n: Option<u8>) -> Result<AdioAdc, Error> {
if slot > 7 {
return Err(Error::Host(HostErr::HostUnsafeArg));
}
if ch > 1 {
return Err(Error::Host(HostErr::HostUnsafeArg));
}
if let Some(n) = n {
if !(1..=16).contains(&n) {
return Err(Error::Host(HostErr::HostUnsafeArg));
}
}
let mut args: Vec<String> = vec![slot.to_string(), ch.to_string()];
if let Some(n) = n {
args.push(n.to_string());
}
let args: Vec<&str> = args.iter().map(String::as_str).collect();
let reply = checked(self.raw_cmd("adio.adc", &args)?)?;
AdioAdc::parse(&reply)
}
}
fn bad(key: &str, want: &str) -> Error {
io_err(
ErrorKind::InvalidData,
format!("reply key `{key}` is not {want}"),
)
}
trait Fields {
fn field(&self, key: &str) -> Option<&Value>;
}
impl Fields for Reply {
fn field(&self, key: &str) -> Option<&Value> {
self.get(key)
}
}
impl Fields for Value {
fn field(&self, key: &str) -> Option<&Value> {
self.get(key)
}
}
fn at<'a>(r: &'a impl Fields, key: &str) -> Result<&'a Value, Error> {
r.field(key).ok_or_else(|| bad(key, "present in the reply"))
}
fn uint<T: TryFrom<u64>>(r: &impl Fields, key: &str) -> Result<T, Error> {
let v = at(r, key)?
.as_u64()
.ok_or_else(|| bad(key, "an unsigned integer"))?;
T::try_from(v).map_err(|_| bad(key, "in range for its declared width"))
}
fn flag(r: &impl Fields, key: &str) -> Result<bool, Error> {
at(r, key)?.as_bool().ok_or_else(|| bad(key, "a bool"))
}
fn text(r: &impl Fields, key: &str) -> Result<String, Error> {
Ok(at(r, key)?
.as_str()
.ok_or_else(|| bad(key, "a string"))?
.to_string())
}
fn uints<T: TryFrom<u64>>(r: &impl Fields, key: &str) -> Result<Vec<T>, Error> {
at(r, key)?
.as_array()
.ok_or_else(|| bad(key, "an array"))?
.iter()
.map(|v| {
let n = v
.as_u64()
.ok_or_else(|| bad(key, "an array of unsigned integers"))?;
T::try_from(n).map_err(|_| bad(key, "in range for its declared width"))
})
.collect()
}
fn flags(r: &impl Fields, key: &str) -> Result<Vec<bool>, Error> {
at(r, key)?
.as_array()
.ok_or_else(|| bad(key, "an array"))?
.iter()
.map(|v| v.as_bool().ok_or_else(|| bad(key, "an array of bools")))
.collect()
}
fn object(r: &impl Fields, key: &str) -> Result<Value, Error> {
Ok(at(r, key)?.clone())
}
fn objects<T>(
r: &impl Fields,
key: &str,
parse: fn(&Value) -> Result<T, Error>,
) -> Result<Vec<T>, Error> {
at(r, key)?
.as_array()
.ok_or_else(|| bad(key, "an array"))?
.iter()
.map(|v| {
if !v.is_object() {
return Err(bad(key, "an array of objects"));
}
parse(v)
})
.collect()
}
fn checked(r: Reply) -> Result<Reply, Error> {
if r.ok() {
Ok(r)
} else {
Err(Error::Device(r))
}
}