flipperzero_sys/
furi.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
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
//! Furi helpers.

use core::ffi::c_char;
use core::fmt::Display;

use crate::FuriStatus;

/// The error type for Furi kernel operations.
#[derive(Clone, Copy, Debug, ufmt::derive::uDebug, Eq, PartialEq)]
pub enum Error {
    Unspecified,
    TimedOut,
    ResourceBusy,
    InvalidParameter,
    OutOfMemory,
    ForbiddenInISR,
    Other(i32),
}

impl Error {
    /// Describe the kind of error.
    pub fn description(&self) -> &str {
        match self {
            Self::Unspecified => "Unspecified RTOS error",
            Self::TimedOut => "Operation not completed within the timeout period",
            Self::ResourceBusy => "Resource not available",
            Self::InvalidParameter => "Parameter error",
            Self::OutOfMemory => "System is out of memory",
            Self::ForbiddenInISR => "Not allowed in ISR context",
            _ => "Unknown",
        }
    }
}

/// Create [`Error`] from [`FuriStatus`].
impl TryFrom<FuriStatus> for Error {
    type Error = i32;

    fn try_from(status: crate::FuriStatus) -> core::result::Result<Self, Self::Error> {
        match status {
            crate::FuriStatus_FuriStatusError => Ok(Self::Unspecified),
            crate::FuriStatus_FuriStatusErrorTimeout => Ok(Self::TimedOut),
            crate::FuriStatus_FuriStatusErrorResource => Ok(Self::ResourceBusy),
            crate::FuriStatus_FuriStatusErrorParameter => Ok(Self::InvalidParameter),
            crate::FuriStatus_FuriStatusErrorNoMemory => Ok(Self::OutOfMemory),
            crate::FuriStatus_FuriStatusErrorISR => Ok(Self::ForbiddenInISR),
            x => {
                if x < 0 {
                    Ok(Self::Other(x))
                } else {
                    Err(x)
                }
            }
        }
    }
}

/// Create [`FuriStatus`] from [`Error`].
impl From<Error> for FuriStatus {
    fn from(error: Error) -> Self {
        match error {
            Error::Unspecified => crate::FuriStatus_FuriStatusError,
            Error::TimedOut => crate::FuriStatus_FuriStatusErrorTimeout,
            Error::ResourceBusy => crate::FuriStatus_FuriStatusErrorResource,
            Error::InvalidParameter => crate::FuriStatus_FuriStatusErrorParameter,
            Error::OutOfMemory => crate::FuriStatus_FuriStatusErrorNoMemory,
            Error::ForbiddenInISR => crate::FuriStatus_FuriStatusErrorISR,
            Error::Other(x) => x as crate::FuriStatus,
        }
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{} ({})", self.description(), FuriStatus::from(*self))
    }
}

impl ufmt::uDisplay for Error {
    fn fmt<W>(&self, f: &mut ufmt::Formatter<'_, W>) -> Result<(), W::Error>
    where
        W: ufmt::uWrite + ?Sized,
    {
        ufmt::uwrite!(f, "{} ({})", self.description(), FuriStatus::from(*self))
    }
}

/// Operation status.
/// The Furi API switches between using `enum FuriStatus`, `int32_t` and `uint32_t`.
/// Since these all use the same bit representation, we can just "cast" the returns to this type.
#[repr(transparent)]
#[derive(Clone, Copy, Debug, ufmt::derive::uDebug, Eq, PartialEq)]
pub struct Status(pub i32);

impl Status {
    /// Operation completed successfully.
    pub const OK: Status = Status(0);
    /// Unspecified RTOS error: run-time error but no other error message fits.
    pub const ERR: Status = Status(-1);
    /// Operation not completed within the timeout period.
    pub const ERR_TIMEOUT: Status = Status(-2);
    /// Resource not available.
    pub const ERR_RESOURCE: Status = Status(-3);
    /// Parameter error.
    pub const ERR_PARAMETER: Status = Status(-4);
    /// System is out of memory: it was impossible to allocate or reserve memory for the operation.
    pub const ERR_NO_MEMORY: Status = Status(-5);
    /// Not allowed in ISR context: the function cannot be called from interrupt service routines.
    pub const ERR_ISR: Status = Status(-6);

    /// Describes the status result of the operation.
    pub fn description(self) -> &'static str {
        match self {
            Self::OK => "Operation completed successfully",
            Self::ERR => "Unspecified RTOS error",
            Self::ERR_TIMEOUT => "Operation not completed within the timeout period",
            Self::ERR_RESOURCE => "Resource not available",
            Self::ERR_PARAMETER => "Parameter error",
            Self::ERR_NO_MEMORY => "System is out of memory",
            Self::ERR_ISR => "Not allowed in ISR context",
            _ => "Unknown",
        }
    }

    /// Check if this is an error status.
    pub fn is_err(self) -> bool {
        self != Self::OK
    }

    /// Convert into [`Result`] type.
    pub fn into_result(self) -> Result<i32, Error> {
        match Error::try_from(self.0) {
            Err(x) => Ok(x),
            Ok(err) => Err(err),
        }
    }
}

impl Display for Status {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{:?}: {}", self, self.description())
    }
}

impl ufmt::uDisplay for Status {
    fn fmt<W>(&self, f: &mut ufmt::Formatter<'_, W>) -> Result<(), W::Error>
    where
        W: ufmt::uWrite + ?Sized,
    {
        ufmt::uwrite!(f, "{:?}: {}", self, self.description())
    }
}

impl From<crate::FuriStatus> for Status {
    fn from(code: FuriStatus) -> Self {
        Status(code)
    }
}

impl From<Status> for Result<i32, Error> {
    fn from(status: Status) -> Self {
        status.into_result()
    }
}

/// Low-level wrapper of a record handle.
pub struct UnsafeRecord<T> {
    name: *const c_char,
    data: *mut T,
}

impl<T> UnsafeRecord<T> {
    /// Opens a record.
    ///
    /// Safety: The caller must ensure that `record_name` lives for the
    /// duration of the object lifetime.
    ///
    /// # Safety
    ///
    /// The caller must provide a valid C-string `name`.
    pub unsafe fn open(name: *const c_char) -> Self {
        Self {
            name,
            data: crate::furi_record_open(name) as *mut T,
        }
    }

    /// Returns the record data as a raw pointer.
    pub fn as_ptr(&self) -> *mut T {
        self.data
    }
}

impl<T> Drop for UnsafeRecord<T> {
    fn drop(&mut self) {
        unsafe {
            // decrement the holders count
            crate::furi_record_close(self.name);
        }
    }
}