1use core::ops::Not;
2
3pub use crate::cfg::channel::Channel;
4pub use crate::cfg::gain::Gain;
5pub use crate::cfg::mode::Mode;
6pub use crate::cfg::resolution::Resolution;
7use crate::Configuration;
8
9mod gain;
10mod channel;
11mod mode;
12mod resolution;
13
14#[derive(Copy, Clone)]
15#[cfg_attr(any(feature = "fmt", test), derive(Debug))]
16#[cfg_attr(feature = "defmt", derive(defmt::Format))]
17pub struct Cfg {
18 pub ready: bool,
19 pub channel: Channel,
20 pub mode: Mode,
21 pub resolution: Resolution,
22 pub gain: Gain,
23}
24
25impl Cfg {
26
27 pub fn set_values_from_configuration(&mut self, other: &Configuration) {
28 self.channel = other.channel;
29 self.gain = other.gain;
30 self.resolution = other.resolution;
31 }
32
33 pub fn as_byte(&self) -> u8 {
34 let mut result = 0_u8;
35 result |= self.ready.not() as u8;
36 result <<= 2;
37 result |= self.channel.mask();
38 result <<= 1;
39 result |= self.mode.mask();
40 result <<= 2;
41 result |= self.resolution.mask();
42 result <<= 2;
43 result |= self.gain.mask();
44 result
45 }
46}
47
48impl From<u8> for Cfg {
49
50 fn from(value: u8) -> Self {
51 let ready = {
52 value >> 7 == 0
53 };
54 let channel = {
55 match (value >> 5) & 0b11 {
56 0b00 => Channel::Channel1,
57 0b01 => Channel::Channel2,
58 0b10 => Channel::Channel3,
59 0b11 => Channel::Channel4,
60 _ => unreachable!()
61 }
62 };
63 let mode = {
64 if (value >> 4) & 1 == 1 {
65 Mode::Continuous
66 }
67 else {
68 Mode::OneShot
69 }
70 };
71 let resolution = {
72 match (value >> 2) & 0b11 {
73 0b00 => Resolution::TwelveBits,
74 0b01 => Resolution::FourteenBits,
75 0b10 => Resolution::SixteenBits,
76 0b11 => Resolution::EighteenBits,
77 _ => unreachable!()
78 }
79 };
80 let gain = {
81 match value & 0b11 {
82 0b00 => Gain::X1,
83 0b01 => Gain::X2,
84 0b10 => Gain::X4,
85 0b11 => Gain::X8,
86 _ => unreachable!()
87 }
88 };
89 Self {
90 ready,
91 channel,
92 mode,
93 resolution,
94 gain
95 }
96 }
97}
98
99impl Default for Cfg {
100 fn default() -> Self {
101 Self {
102 ready: true,
103 channel: Channel::default(),
104 mode: Mode::default(),
105 resolution: Resolution::default(),
106 gain: Gain::default(),
107 }
108 }
109}