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
use base::*;
use units::*;
use shim::*;

/// A counting or binary semaphore
pub struct Semaphore {
    semaphore: FreeRtosSemaphoreHandle,
}

unsafe impl Send for Semaphore {}
unsafe impl Sync for Semaphore {}

impl Semaphore {
    /// Create a new binary semaphore
    pub fn new_binary() -> Result<Semaphore, FreeRtosError> {
        unsafe {
            let s = freertos_rs_create_binary_semaphore();
            if s == 0 as *const _ {
                return Err(FreeRtosError::OutOfMemory);
            }
            Ok(Semaphore { semaphore: s })
        }
    }

    /// Create a new counting semaphore
    pub fn new_counting(max: u32, initial: u32) -> Result<Semaphore, FreeRtosError> {
        unsafe {
            let s = freertos_rs_create_counting_semaphore(max, initial);
            if s == 0 as *const _ {
                return Err(FreeRtosError::OutOfMemory);
            }
            Ok(Semaphore { semaphore: s })
        }
    }

    // pub fn get_count(&self) -> u32 {
    // unsafe {
    // freertos_rs_get_semaphore_count(self.semaphore)
    // }
    // }
    //

    /// Lock this semaphore in a RAII fashion
    pub fn lock<D: DurationTicks>(&self, max_wait: D) -> Result<SemaphoreGuard, FreeRtosError> {
        unsafe {
            let res = freertos_rs_take_mutex(self.semaphore, max_wait.to_ticks());

            if res != 0 {
                return Err(FreeRtosError::Timeout);
            }

            Ok(SemaphoreGuard { __semaphore: self.semaphore })
        }
    }
}

impl Drop for Semaphore {
    fn drop(&mut self) {
        unsafe {
            freertos_rs_delete_semaphore(self.semaphore);
        }
    }
}

/// Holds the lock to the semaphore until we are dropped
pub struct SemaphoreGuard {
    __semaphore: FreeRtosSemaphoreHandle,
}

impl Drop for SemaphoreGuard {
    fn drop(&mut self) {
        unsafe {
            freertos_rs_give_mutex(self.__semaphore);
        }
    }
}