use {
crate::{
error::{Error, Result},
port::{Port, PortEnumerator, PortInfo, SerialConfig},
},
std::{
io::{Read, Write},
time::Duration,
},
};
pub struct WebSerialPort {
name: String,
baud_rate: u32,
timeout: Duration,
}
impl WebSerialPort {
pub fn new(_config: &SerialConfig) -> Result<Self> {
Err(Error::Unsupported(
"Web Serial API support is not yet implemented. Please use the native version of \
hisiflash."
.to_string(),
))
}
#[cfg(all(feature = "wasm", target_arch = "wasm32"))]
pub fn from_js_port(
_js_port: js_sys::Object, name: String,
baud_rate: u32,
) -> Result<Self> {
let _ = (_js_port, &name, baud_rate);
Err(Error::Unsupported(
"Web Serial API support is not yet implemented.".to_string(),
))
}
}
impl Port for WebSerialPort {
fn set_timeout(&mut self, timeout: Duration) -> Result<()> {
self.timeout = timeout;
Ok(())
}
fn timeout(&self) -> Duration {
self.timeout
}
fn set_baud_rate(&mut self, baud_rate: u32) -> Result<()> {
self.baud_rate = baud_rate;
Err(Error::Unsupported(
"Changing baud rate on Web Serial requires reopening the port.".to_string(),
))
}
fn baud_rate(&self) -> u32 {
self.baud_rate
}
fn clear_buffers(&mut self) -> Result<()> {
Ok(())
}
fn name(&self) -> &str {
&self.name
}
fn set_dtr(&mut self, _level: bool) -> Result<()> {
Err(Error::Unsupported(
"DTR control not yet implemented for Web Serial.".to_string(),
))
}
fn set_rts(&mut self, _level: bool) -> Result<()> {
Err(Error::Unsupported(
"RTS control not yet implemented for Web Serial.".to_string(),
))
}
fn read_cts(&mut self) -> Result<bool> {
Err(Error::Unsupported(
"CTS reading not yet implemented for Web Serial.".to_string(),
))
}
fn read_dsr(&mut self) -> Result<bool> {
Err(Error::Unsupported(
"DSR reading not yet implemented for Web Serial.".to_string(),
))
}
fn close(&mut self) -> Result<()> {
Ok(())
}
}
impl Read for WebSerialPort {
fn read(&mut self, _buf: &mut [u8]) -> std::io::Result<usize> {
Err(std::io::Error::new(
std::io::ErrorKind::Unsupported,
"Web Serial read not yet implemented",
))
}
}
impl Write for WebSerialPort {
fn write(&mut self, _buf: &[u8]) -> std::io::Result<usize> {
Err(std::io::Error::new(
std::io::ErrorKind::Unsupported,
"Web Serial write not yet implemented",
))
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
pub struct WebSerialPortEnumerator;
impl PortEnumerator for WebSerialPortEnumerator {
fn list_ports() -> Result<Vec<PortInfo>> {
Err(Error::Unsupported(
"Web Serial cannot enumerate ports without user interaction. Use \
navigator.serial.requestPort() from JavaScript instead."
.to_string(),
))
}
}
#[cfg(feature = "wasm")]
#[allow(async_fn_in_trait)]
pub trait AsyncPort {
async fn read_async(&mut self, buf: &mut [u8]) -> Result<usize>;
async fn write_async(&mut self, buf: &[u8]) -> Result<usize>;
async fn write_all_async(&mut self, buf: &[u8]) -> Result<()>;
async fn flush_async(&mut self) -> Result<()>;
}