1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
use embedded_hal as hal;
use hal::blocking::i2c;
use std::error::Error as StdError;
use std::result;
use std::str;
use std::str::Utf8Error;
use std::thread;
use std::time::Duration;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum EzoBoardError<E: StdError + 'static> {
#[error(transparent)]
I2c(#[from] E),
#[error(transparent)]
Utf8Error(Utf8Error),
#[error("Read buffer is not ready")]
NotReady,
#[error("No Data To Send")]
NoDataToSend,
#[error("Syntax Error")]
SyntaxError,
#[error("unknown EzoReadError")]
Unknown,
}
pub struct EzoBoard<I2C> {
i2c: I2C,
address: u8,
}
impl<I2C, E> EzoBoard<I2C>
where
I2C: i2c::Read<Error = E> + i2c::Write<Error = E>,
E: std::error::Error,
{
pub fn new(i2c: I2C, address: u8) -> Self {
EzoBoard { i2c, address }
}
pub fn send_command(
&mut self,
command: &[u8],
delay: Duration,
) -> result::Result<(), EzoBoardError<E>> {
self.i2c.write(self.address, command)?;
if delay != Duration::new(0, 0) {
thread::sleep(delay);
}
Ok(())
}
pub fn read_response(&mut self) -> result::Result<String, EzoBoardError<E>> {
let mut buff: [u8; 40] = [0; 40];
self.i2c.read(self.address, &mut buff[..])?;
match &buff[0] {
1 => Ok(str::from_utf8(&buff[1..])
.map_err(EzoBoardError::Utf8Error)?
.to_string()),
2 => Err(EzoBoardError::SyntaxError),
254 => Err(EzoBoardError::NotReady),
255 => Err(EzoBoardError::NoDataToSend),
_ => Err(EzoBoardError::Unknown),
}
}
}