1#![no_std]
2
3mod response;
4pub mod direction;
5mod errors;
6
7pub use errors::Error;
8
9pub struct Driver {
14 address: u8,
15 bytes: [u8; 8], }
17
18type Result<T> = core::result::Result<T, crate::Error>;
19
20impl Default for Driver {
21 fn default() -> Self {
22 Driver {
23 address: 0xe0,
24 bytes: Default::default(),
25 }
26 }
27}
28
29impl Driver {
30 pub fn with_id(address: u8) -> Self {
32 Driver {
33 address,
34 .. Default::default()
35 }
36 }
37
38 pub fn rotate<'a>(&'a mut self, direction: direction::Direction, speed: u8) -> Result<&'a [u8]> {
48 if speed > 0x80 {
49 return Err(Error::InvalidValue);
50 }
51
52 Ok(self.set_bytes(&[self.address, 0xf6, speed | direction as u8]))
53 }
54
55 pub fn stop<'a>(&'a mut self) -> Result<&'a [u8]> {
57 Ok(self.set_bytes(&mut [self.address, 0xf7]))
58 }
59
60 pub fn rotate_to<'a>(&'a mut self, direction: direction::Direction, speed: u8, value: u32) -> Result<&'a [u8]> {
61 if speed > 0x80 {
62 return Err(Error::InvalidValue);
63 }
64
65 Ok(self.set_bytes(&[self.address, 0xfd, speed | direction as u8,
67 ((value & 0xff000000) >> 24) as u8,
68 ((value & 0x00ff0000) >> 16) as u8,
69 ((value & 0x0000ff00) >> 8) as u8,
70 ((value & 0x000000ff) >> 0) as u8]))
71
72 }
73
74 pub fn zero<'a>(&'a mut self) -> Result<&'a [u8]> {
75 Ok(self.set_bytes(&[self.address, 0x94, 0x00]))
76 }
77
78 pub fn set_zero_speed<'a>(&'a mut self, speed: u8) -> Result<&'a [u8]> {
80 Ok(self.set_bytes(&[self.address, 0x92, speed]))
81 }
82
83 fn set_bytes(&mut self, cmd: &[u8]) -> &[u8] {
86 let len = cmd.len();
87 self.bytes[..len].clone_from_slice(&cmd);
88 self.bytes[len] = checksum(&cmd);
89 &self.bytes[..len+1]
90 }
91}
92
93fn checksum(bytes: &[u8]) -> u8 {
94 let mut total: u64 = 0;
95 for b in bytes {
96 total += *b as u64;
97 }
98 return (total & 0xff) as u8;
99}
100
101
102#[cfg(test)]
103mod tests {
104 use super::*;
105
106 #[test]
107 fn checksums() {
108 assert_eq!(0xd7, checksum(&[0xe0, 0xf6, 0x01]));
109 }
110}