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
//
// Copyright 2024, Colias Group, LLC
//
// SPDX-License-Identifier: BSD-2-Clause
//

use core::time::Duration;

use sel4_driver_interfaces::timer::{Clock, ErrorType, NumTimers, Timers};
use sel4_microkit::{Channel, MessageInfo};
use sel4_microkit_message::MessageInfoExt;

use super::message_types::*;

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Client {
    channel: Channel,
}

impl Client {
    pub fn new(channel: Channel) -> Self {
        Client { channel }
    }

    fn request(&self, req: Request) -> Result<SuccessResponse, Error> {
        self.channel
            .pp_call(MessageInfo::send_using_postcard(req).unwrap())
            .recv_using_postcard::<Response>()
            .map_err(|_| Error::InvalidResponse)?
            .map_err(Error::ErrorResponse)
    }
}

impl ErrorType for Client {
    type Error = Error;
}

impl Clock for Client {
    fn get_time(&mut self) -> Result<Duration, Self::Error> {
        match self.request(Request::GetTime)? {
            SuccessResponse::GetTime(v) => Ok(v),
            _ => Err(Error::UnexpectedResponse),
        }
    }
}

impl Timers for Client {
    type TimerLayout = NumTimers;

    type Timer = usize;

    fn timer_layout(&mut self) -> Result<Self::TimerLayout, Self::Error> {
        match self.request(Request::NumTimers)? {
            SuccessResponse::NumTimers(v) => Ok(NumTimers(v)),
            _ => Err(Error::UnexpectedResponse),
        }
    }

    fn set_timeout_on(
        &mut self,
        timer: Self::Timer,
        relative: Duration,
    ) -> Result<(), Self::Error> {
        match self.request(Request::SetTimeout { timer, relative })? {
            SuccessResponse::SetTimeout => Ok(()),
            _ => Err(Error::UnexpectedResponse),
        }
    }

    fn clear_timeout_on(&mut self, timer: Self::Timer) -> Result<(), Self::Error> {
        match self.request(Request::ClearTimeout { timer })? {
            SuccessResponse::ClearTimeout => Ok(()),
            _ => Err(Error::UnexpectedResponse),
        }
    }
}

#[derive(Debug, Copy, Clone)]
pub enum Error {
    ErrorResponse(ErrorResponse),
    InvalidResponse,
    UnexpectedResponse,
}