Skip to main content

psdk_fruit_emapi/
device_connection.rs

1use std::time::Duration;
2
3use psdk_father::device::{ConnectedDevice, ReadOptions};
4
5use crate::{
6  connection::EmapiConnection,
7  error::{EmapiError, Result},
8};
9
10pub struct ConnectedDeviceEmapiConnection<D> {
11  device: D,
12}
13
14impl<D> ConnectedDeviceEmapiConnection<D>
15where
16  D: ConnectedDevice,
17{
18  pub fn new(device: D) -> Self {
19    Self { device }
20  }
21
22  pub fn write(&mut self, data: &[u8]) -> Result<()> {
23    EmapiConnection::write(self, data)
24  }
25
26  pub fn read(&mut self, timeout: Duration) -> Result<Vec<u8>> {
27    EmapiConnection::read(self, timeout)
28  }
29
30  pub fn into_inner(self) -> D {
31    self.device
32  }
33}
34
35impl<D> EmapiConnection for ConnectedDeviceEmapiConnection<D>
36where
37  D: ConnectedDevice,
38{
39  fn write(&mut self, data: &[u8]) -> Result<()> {
40    self
41      .device
42      .write(data)
43      .map_err(|error| EmapiError::Connection {
44        message: error.to_string(),
45      })
46  }
47
48  fn read(&mut self, timeout: Duration) -> Result<Vec<u8>> {
49    let data = self
50      .device
51      .read(Some(ReadOptions {
52        timeout: timeout.as_millis().min(u128::from(u32::MAX)) as u32,
53      }))
54      .map_err(|error| EmapiError::Connection {
55        message: error.to_string(),
56      })?;
57    if data.is_empty() {
58      return Err(EmapiError::Timeout {
59        message: "device read returned no data".to_string(),
60      });
61    }
62    Ok(data)
63  }
64}