Skip to main content

capsules_extra/
ninedof.rs

1// Licensed under the Apache License, Version 2.0 or the MIT License.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3// Copyright Tock Contributors 2022.
4
5//! Provides userspace with virtualized access to 9DOF sensors.
6//!
7//! Usage
8//! -----
9//!
10//! You need a device that provides the `hil::sensors::NineDof` trait.
11//!
12//! ```rust,ignore
13//! # use kernel::{hil, static_init};
14//!
15//! let grant_cap = create_capability!(capabilities::MemoryAllocationCapability);
16//! let grant_ninedof = board_kernel.create_grant(&grant_cap);
17//!
18//! let ninedof = static_init!(
19//!     capsules::ninedof::NineDof<'static>,
20//!     capsules::ninedof::NineDof::new(grant_ninedof));
21//! ninedof.add_driver(fxos8700);
22//! hil::sensors::NineDof::set_client(fxos8700, ninedof);
23//! ```
24
25use kernel::grant::{AllowRoCount, AllowRwCount, Grant, UpcallCount};
26use kernel::hil;
27use kernel::syscall::{CommandReturn, SyscallDriver};
28use kernel::utilities::cells::OptionalCell;
29use kernel::{ErrorCode, ProcessId};
30
31/// Syscall driver number.
32use capsules_core::driver;
33pub const DRIVER_NUM: usize = driver::NUM::NINEDOF as usize;
34
35#[derive(Clone, Copy, PartialEq)]
36pub enum NineDofCommand {
37    Exists,
38    ReadAccelerometer,
39    ReadMagnetometer,
40    ReadGyroscope,
41}
42
43pub struct App {
44    pending_command: bool,
45    command: NineDofCommand,
46    arg1: usize,
47}
48
49impl Default for App {
50    fn default() -> App {
51        App {
52            pending_command: false,
53            command: NineDofCommand::Exists,
54            arg1: 0,
55        }
56    }
57}
58
59pub struct NineDof<'a> {
60    drivers: &'a [&'a dyn hil::sensors::NineDof<'a>],
61    apps: Grant<App, UpcallCount<1>, AllowRoCount<0>, AllowRwCount<0>>,
62    current_app: OptionalCell<ProcessId>,
63}
64
65impl<'a> NineDof<'a> {
66    pub fn new(
67        drivers: &'a [&'a dyn hil::sensors::NineDof<'a>],
68        grant: Grant<App, UpcallCount<1>, AllowRoCount<0>, AllowRwCount<0>>,
69    ) -> NineDof<'a> {
70        NineDof {
71            drivers,
72            apps: grant,
73            current_app: OptionalCell::empty(),
74        }
75    }
76
77    // Check so see if we are doing something. If not,
78    // go ahead and do this command. If so, this is queued
79    // and will be run when the pending command completes.
80    fn enqueue_command(
81        &self,
82        command: NineDofCommand,
83        arg1: usize,
84        processid: ProcessId,
85    ) -> CommandReturn {
86        self.apps
87            .enter(processid, |app, _| {
88                if self.current_app.is_none() {
89                    self.current_app.set(processid);
90                    app.command = command;
91                    app.arg1 = arg1;
92                    let value = self.call_driver(command, arg1);
93                    if value != Ok(()) {
94                        self.current_app.clear();
95                    }
96                    CommandReturn::from(value)
97                } else {
98                    if app.pending_command {
99                        CommandReturn::failure(ErrorCode::BUSY)
100                    } else {
101                        app.pending_command = true;
102                        app.command = command;
103                        app.arg1 = arg1;
104                        CommandReturn::success()
105                    }
106                }
107            })
108            .unwrap_or_else(|err| {
109                let rcode: Result<(), ErrorCode> = err.into();
110                CommandReturn::from(rcode)
111            })
112    }
113
114    fn call_driver(&self, command: NineDofCommand, _: usize) -> Result<(), ErrorCode> {
115        match command {
116            NineDofCommand::ReadAccelerometer => {
117                let mut data = Err(ErrorCode::NODEVICE);
118                for driver in self.drivers.iter() {
119                    data = driver.read_accelerometer();
120                    if data == Ok(()) {
121                        break;
122                    }
123                }
124                data
125            }
126            NineDofCommand::ReadMagnetometer => {
127                let mut data = Err(ErrorCode::NODEVICE);
128                for driver in self.drivers.iter() {
129                    data = driver.read_magnetometer();
130                    if data == Ok(()) {
131                        break;
132                    }
133                }
134                data
135            }
136            NineDofCommand::ReadGyroscope => {
137                let mut data = Err(ErrorCode::NODEVICE);
138                for driver in self.drivers.iter() {
139                    data = driver.read_gyroscope();
140                    if data == Ok(()) {
141                        break;
142                    }
143                }
144                data
145            }
146            _ => Err(ErrorCode::NOSUPPORT),
147        }
148    }
149}
150
151impl hil::sensors::NineDofClient for NineDof<'_> {
152    fn callback(&self, arg1: usize, arg2: usize, arg3: usize) {
153        // Notify the current application that the command finished.
154        // Also keep track of what just finished to see if we can re-use
155        // the result.
156        let mut finished_command = NineDofCommand::Exists;
157        let mut finished_command_arg = 0;
158        self.current_app.take().map(|processid| {
159            let _ = self.apps.enter(processid, |app, upcalls| {
160                app.pending_command = false;
161                finished_command = app.command;
162                finished_command_arg = app.arg1;
163                let _ = upcalls.schedule_upcall(0, (arg1, arg2, arg3));
164            });
165        });
166
167        // Check if there are any pending events.
168        for cntr in self.apps.iter() {
169            let processid = cntr.processid();
170            let started_command = cntr.enter(|app, upcalls| {
171                if app.pending_command
172                    && app.command == finished_command
173                    && app.arg1 == finished_command_arg
174                {
175                    // Don't bother re-issuing this command, just use
176                    // the existing result.
177                    app.pending_command = false;
178                    let _ = upcalls.schedule_upcall(0, (arg1, arg2, arg3));
179                    false
180                } else if app.pending_command {
181                    app.pending_command = false;
182                    let result = self.call_driver(app.command, app.arg1);
183                    if result == Ok(()) {
184                        self.current_app.set(processid);
185                        true
186                    } else {
187                        false
188                    }
189                } else {
190                    false
191                }
192            });
193            if started_command {
194                break;
195            }
196        }
197    }
198}
199
200impl SyscallDriver for NineDof<'_> {
201    fn command(
202        &self,
203        command_num: usize,
204        arg1: usize,
205        _: usize,
206        processid: ProcessId,
207    ) -> CommandReturn {
208        match command_num {
209            0 => CommandReturn::success(),
210            // Single acceleration reading.
211            1 => self.enqueue_command(NineDofCommand::ReadAccelerometer, arg1, processid),
212
213            // Single magnetometer reading.
214            100 => self.enqueue_command(NineDofCommand::ReadMagnetometer, arg1, processid),
215
216            // Single gyroscope reading.
217            200 => self.enqueue_command(NineDofCommand::ReadGyroscope, arg1, processid),
218
219            _ => CommandReturn::failure(ErrorCode::NOSUPPORT),
220        }
221    }
222
223    fn allocate_grant(&self, processid: ProcessId) -> Result<(), kernel::process::Error> {
224        self.apps.enter(processid, |_, _| {})
225    }
226}