extern crate alloc;
use crate::InterruptType;
mod interface;
pub struct Uart1 {
initialized: bool,
}
impl Uart1 {
pub const fn new() -> Self {
Uart1 { initialized: false }
}
pub fn initialize(&mut self, clock_rate: u32, baud_rate: u32) -> Result<(), &'static str> {
interface::uart1_init(clock_rate, baud_rate).map(|_| {
self.initialized = true;
})
}
pub fn send_char(&self, c: char) {
if self.initialized {
interface::uart1_send_char(c);
}
}
pub fn send_string(&self, s: &str) {
if self.initialized {
interface::uart1_send_string(s);
}
}
pub fn send_data(&self, d: &[u8]) {
if self.initialized {
interface::uart1_send_data(d);
}
}
pub fn send_hex(&self, value: u64) {
if value == 0 {
self.send_string("0x0");
return;
}
const HEXCHAR: &[u8] = b"0123456789ABCDEF";
let mut tmp = value;
let mut hex: [u8; 16] = [0; 16];
let mut idx = 0;
while tmp != 0 {
hex[idx] = HEXCHAR[(tmp & 0xF) as usize];
tmp >>= 4;
idx += 1;
}
self.send_string("0x");
for i in 0..16 {
if hex[15 - i] != 0 {
self.send_char(hex[15 - i] as char);
}
}
}
pub fn try_receive_data(&self, buffer: &mut [u8]) -> Result<usize, &'static str> {
if self.initialized {
if buffer.is_empty() {
Err("buffer size expected to be at least 1")
} else {
for c in 0..buffer.len() {
buffer[c] = interface::uart1_receive_data(1000)?;
}
Ok(buffer.len())
}
} else {
Err("Uart not initialized")
}
}
pub fn receive_data(&self, buffer: &mut [u8]) -> Result<usize, &'static str> {
if self.initialized {
if buffer.is_empty() {
Err("buffer size expected to be at least 1")
} else {
for c in 0..buffer.len() {
buffer[c] = interface::uart1_receive_data(0)?;
}
Ok(buffer.len())
}
} else {
Err("Uart not initialized")
}
}
pub fn enable_interrupts(&self, i_type: InterruptType) {
if self.initialized {
interface::uart1_enable_interrupts(i_type);
}
}
pub fn disable_interrupts(&self, i_type: InterruptType) {
if self.initialized {
interface::uart1_disable_interrupts(i_type);
}
}
pub fn get_interrupt_status(&self) -> u32 {
if self.initialized {
interface::uart1_get_interrupt_status()
} else {
0
}
}
}
impl Drop for Uart1 {
fn drop(&mut self) {
interface::uart1_release();
}
}
impl core::fmt::Write for Uart1 {
fn write_str(&mut self, s: &str) -> core::fmt::Result {
self.send_string(s);
Ok(())
}
}