components/
proximity.rs

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
// Licensed under the Apache License, Version 2.0 or the MIT License.
// SPDX-License-Identifier: Apache-2.0 OR MIT
// Copyright Tock Contributors 2022.

//! Component for any proximity sensor.
//!
//! Usage
//! -----
//! ```rust
//! let proximity = ProximityComponent::new(apds9960, board_kernel, capsules_extra::proximity::DRIVER_NUM)
//!     .finalize(components::proximity_component_static!());
//! ```

use capsules_extra::proximity::ProximitySensor;
use core::mem::MaybeUninit;
use kernel::capabilities;
use kernel::component::Component;
use kernel::create_capability;
use kernel::hil;

#[macro_export]
macro_rules! proximity_component_static {
    () => {{
        kernel::static_buf!(capsules_extra::proximity::ProximitySensor<'static>)
    };};
}

pub struct ProximityComponent<P: hil::sensors::ProximityDriver<'static> + 'static> {
    sensor: &'static P,
    board_kernel: &'static kernel::Kernel,
    driver_num: usize,
}

impl<P: hil::sensors::ProximityDriver<'static>> ProximityComponent<P> {
    pub fn new(
        sensor: &'static P,
        board_kernel: &'static kernel::Kernel,
        driver_num: usize,
    ) -> ProximityComponent<P> {
        ProximityComponent {
            sensor,
            board_kernel,
            driver_num,
        }
    }
}

impl<P: hil::sensors::ProximityDriver<'static>> Component for ProximityComponent<P> {
    type StaticInput = &'static mut MaybeUninit<ProximitySensor<'static>>;
    type Output = &'static ProximitySensor<'static>;

    fn finalize(self, s: Self::StaticInput) -> Self::Output {
        let grant_cap = create_capability!(capabilities::MemoryAllocationCapability);
        let grant = self.board_kernel.create_grant(self.driver_num, &grant_cap);

        let proximity = s.write(ProximitySensor::new(self.sensor, grant));

        hil::sensors::ProximityDriver::set_client(self.sensor, proximity);
        proximity
    }
}