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
use core::cell::Cell;
use kernel::ReturnCode;
use kernel::common::take_cell::TakeCell;
use kernel::hil::i2c::{Error, I2CClient, I2CDevice};
use kernel::hil::sensors::{AmbientLight, AmbientLightClient};
use kernel::hil::time::{self, Frequency};
pub static mut BUF: [u8; 3] = [0; 3];
#[derive(Copy, Clone, PartialEq)]
enum State {
Disabled,
Enabling,
Integrating,
ReadingLI,
Disabling(usize),
}
pub struct Isl29035<'a, A: time::Alarm + 'a> {
i2c: &'a I2CDevice,
alarm: &'a A,
state: Cell<State>,
buffer: TakeCell<'static, [u8]>,
client: Cell<Option<&'a AmbientLightClient>>,
}
impl<'a, A: time::Alarm + 'a> Isl29035<'a, A> {
pub fn new(i2c: &'a I2CDevice, alarm: &'a A, buffer: &'static mut [u8]) -> Isl29035<'a, A> {
Isl29035 {
i2c: i2c,
alarm: alarm,
state: Cell::new(State::Disabled),
buffer: TakeCell::new(buffer),
client: Cell::new(None),
}
}
pub fn start_read_lux(&self) {
if self.state.get() == State::Disabled {
self.buffer.take().map(|buf| {
self.i2c.enable();
buf[0] = 0;
buf[1] = 0b10100000;
buf[2] = 0b00001001;
self.i2c.write(buf, 3);
self.state.set(State::Enabling);
});
}
}
}
impl<'a, A: time::Alarm + 'a> AmbientLight for Isl29035<'a, A> {
fn set_client(&self, client: &'static AmbientLightClient) {
self.client.set(Some(client));
}
fn read_light_intensity(&self) -> ReturnCode {
self.start_read_lux();
ReturnCode::SUCCESS
}
}
impl<'a, A: time::Alarm + 'a> time::Client for Isl29035<'a, A> {
fn fired(&self) {
self.buffer.take().map(|buffer| {
self.i2c.enable();
buffer[0] = 0x02 as u8;
self.i2c.write_read(buffer, 1, 2);
self.state.set(State::ReadingLI);
});
}
}
impl<'a, A: time::Alarm + 'a> I2CClient for Isl29035<'a, A> {
fn command_complete(&self, buffer: &'static mut [u8], _error: Error) {
match self.state.get() {
State::Enabling => {
let interval = (410 as u32) * <A::Frequency>::frequency() / 1000000;
let tics = self.alarm.now().wrapping_add(interval);
self.alarm.set_alarm(tics);
self.buffer.replace(buffer);
self.i2c.disable();
self.state.set(State::Integrating);
}
State::ReadingLI => {
let data = buffer[0] as usize;
let lux = (data * 4000) >> 8;
buffer[0] = 0;
self.i2c.write(buffer, 2);
self.state.set(State::Disabling(lux));
}
State::Disabling(lux) => {
self.i2c.disable();
self.state.set(State::Disabled);
self.buffer.replace(buffer);
self.client.get().map(|client| client.callback(lux));
}
_ => {}
}
}
}