wasefire_board_api/
uart.rs

1// Copyright 2023 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! UART interface.
16
17use derive_where::derive_where;
18
19use crate::{Error, Id, Support};
20
21/// UART event.
22#[cfg_attr(feature = "defmt", derive(defmt::Format))]
23#[derive_where(Debug, PartialEq, Eq)]
24pub struct Event<B: crate::Api + ?Sized> {
25    /// The UART that triggered the event.
26    pub uart: Id<crate::Uart<B>>,
27
28    /// Whether the UART may be ready for read or write.
29    pub direction: Direction,
30}
31
32/// Whether it might be possible to read or write.
33#[cfg_attr(feature = "defmt", derive(defmt::Format))]
34#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
35pub enum Direction {
36    /// There might be data to read.
37    ///
38    /// This is only guaranteed to be triggered after a short read.
39    Read,
40
41    /// It might be possible to write data.
42    ///
43    /// This is only guaranteed to be triggered after a short write.
44    Write,
45}
46
47impl<B: crate::Api> From<Event<B>> for crate::Event<B> {
48    fn from(event: Event<B>) -> Self {
49        crate::Event::Uart(event)
50    }
51}
52
53/// UART interface.
54pub trait Api: Support<usize> + Send {
55    /// Sets the baudrate of a stopped UART.
56    fn set_baudrate(uart: Id<Self>, baudrate: usize) -> Result<(), Error>;
57
58    /// Starts a UART.
59    fn start(uart: Id<Self>) -> Result<(), Error>;
60
61    /// Stops a UART.
62    fn stop(uart: Id<Self>) -> Result<(), Error>;
63
64    /// Reads from a UART into a buffer.
65    ///
66    /// Returns the number of bytes read. It could be zero if there's nothing to read.
67    fn read(uart: Id<Self>, output: &mut [u8]) -> Result<usize, Error>;
68
69    /// Writes from a buffer to a UART.
70    ///
71    /// Returns the number of bytes written. It could be zero if the other side is not ready.
72    fn write(uart: Id<Self>, input: &[u8]) -> Result<usize, Error>;
73
74    /// Enables a given event to be triggered.
75    fn enable(uart: Id<Self>, direction: Direction) -> Result<(), Error>;
76
77    /// Disables a given event from being triggered.
78    fn disable(uart: Id<Self>, direction: Direction) -> Result<(), Error>;
79}