use super::{AvailableDevice, Model};
use crate::protos::MessageType;
use std::fmt;
pub mod error;
pub mod protocol;
pub mod udp;
pub mod webusb;
#[derive(Debug)]
pub enum AvailableDeviceTransport {
WebUsb(webusb::AvailableWebUsbTransport),
Udp(udp::AvailableUdpTransport),
}
impl fmt::Display for AvailableDeviceTransport {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
AvailableDeviceTransport::WebUsb(ref t) => write!(f, "{}", t),
AvailableDeviceTransport::Udp(ref t) => write!(f, "{}", t),
}
}
}
pub struct ProtoMessage(pub MessageType, pub Vec<u8>);
impl ProtoMessage {
pub fn new(mt: MessageType, payload: Vec<u8>) -> ProtoMessage {
ProtoMessage(mt, payload)
}
pub fn message_type(&self) -> MessageType {
self.0
}
pub fn payload(&self) -> &[u8] {
&self.1
}
pub fn into_payload(self) -> Vec<u8> {
self.1
}
pub fn into_message<M: protobuf::Message>(self) -> Result<M, protobuf::Error> {
protobuf::Message::parse_from_bytes(&self.into_payload())
}
}
pub trait Transport: Sync + Send {
fn session_begin(&mut self) -> Result<(), error::Error>;
fn session_end(&mut self) -> Result<(), error::Error>;
fn write_message(&mut self, message: ProtoMessage) -> Result<(), error::Error>;
fn read_message(&mut self) -> Result<ProtoMessage, error::Error>;
}
pub fn connect(available_device: &AvailableDevice) -> Result<Box<dyn Transport>, error::Error> {
match available_device.transport {
AvailableDeviceTransport::WebUsb(_) => webusb::WebUsbTransport::connect(available_device),
AvailableDeviceTransport::Udp(_) => udp::UdpTransport::connect(available_device),
}
}
mod constants {
pub(crate) const DEV_TREZOR_LEGACY: (u16, u16) = (0x534C, 0x0001);
pub(crate) const DEV_TREZOR: (u16, u16) = (0x1209, 0x53C1);
pub(crate) const DEV_TREZOR_BOOTLOADER: (u16, u16) = (0x1209, 0x53C0);
}
pub(crate) fn derive_model(dev_id: (u16, u16)) -> Option<Model> {
match dev_id {
constants::DEV_TREZOR_LEGACY => Some(Model::TrezorLegacy),
constants::DEV_TREZOR => Some(Model::Trezor),
constants::DEV_TREZOR_BOOTLOADER => Some(Model::TrezorBootloader),
_ => None,
}
}