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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
#![no_std]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#[macro_use]
extern crate bitfield;
mod map;
pub mod settings;
pub mod structs;
use embedded_hal::blocking::i2c;
pub use map::*;
pub use structs::Entries;
pub trait Entry: Sized {
const INDEX: Index;
type Array: AsMut<[u8]> + AsRef<[u8]> + Default;
fn into_array(self) -> Self::Array;
fn from_array(arr: Self::Array) -> Self;
fn index(&self) -> Index {
Self::INDEX
}
}
const INDEX_LEN: usize = 2;
const DATA_LEN: usize = 200;
pub const MAX_SLICE_LEN: usize = DATA_LEN - INDEX_LEN;
pub const SLAVE_ADDR: u8 = 0x52 >> 1;
pub fn write_slice<I>(i2c: &mut I, index: Index, slice: &[u8]) -> Result<(), I::Error>
where
I: i2c::Write,
{
assert!(slice.len() < MAX_SLICE_LEN);
let mut data = [0u8; DATA_LEN];
let data_len = INDEX_LEN + slice.len();
let data = &mut data[..data_len];
let [ix_a, ix_b]: [u8; 2] = index.into();
data[0] = ix_a;
data[1] = ix_b;
for (d, s) in data[INDEX_LEN..].iter_mut().zip(slice) {
*d = *s;
}
i2c.write(SLAVE_ADDR, &data)
}
pub fn read_slice<I>(i2c: &mut I, index: Index, slice: &mut [u8]) -> Result<(), I::Error>
where
I: i2c::WriteRead,
{
let arr: [u8; 2] = index.into();
i2c.write_read(SLAVE_ADDR, &arr, slice)
}
pub fn write_byte<I>(i2c: &mut I, index: Index, byte: u8) -> Result<(), I::Error>
where
I: i2c::Write,
{
write_slice(i2c, index, &[byte])
}
pub fn read_byte<I>(i2c: &mut I, index: Index) -> Result<u8, I::Error>
where
I: i2c::WriteRead,
{
let mut b = [0u8];
read_slice(i2c, index, &mut b)?;
let [b] = b;
Ok(b)
}
pub fn write_word<I>(i2c: &mut I, index: Index, word: u16) -> Result<(), I::Error>
where
I: i2c::Write,
{
let [a, b] = word.to_be_bytes();
write_slice(i2c, index, &[a, b])
}
pub fn read_word<I>(i2c: &mut I, index: Index) -> Result<u16, I::Error>
where
I: i2c::WriteRead,
{
let mut bs = [0u8; 2];
read_slice(i2c, index, &mut bs)?;
Ok(u16::from_be_bytes(bs))
}
pub fn write_entry<I, E>(i2c: &mut I, entry: E) -> Result<(), I::Error>
where
I: i2c::Write,
E: Entry,
{
let arr = entry.into_array();
write_slice(i2c, E::INDEX, arr.as_ref())
}
pub fn read_entry<I, E>(i2c: &mut I) -> Result<E, I::Error>
where
I: i2c::WriteRead,
E: Entry,
{
let mut arr: E::Array = Default::default();
read_slice(i2c, E::INDEX, arr.as_mut())?;
Ok(E::from_array(arr))
}