Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/logging #86

Merged
merged 6 commits into from
Oct 8, 2020
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
119 changes: 119 additions & 0 deletions src/logger.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
//! Booster NGFW logging utilities
//!
//! # Copyright
//! Copyright (C) 2020 QUARTIQ GmbH - All Rights Reserved
//! Unauthorized usage, editing, or copying is strictly prohibited.
//! Proprietary and confidential.
use heapless::{consts, String};

use super::SerialTerminal;
use core::fmt::Write;

/// A logging buffer for storing serialized logs pending transmission.
///
/// # Notes
/// The LoBufferedLog contains a character buffer of the log data waiting to be written. It is
/// intended to be consumed asynchronously. In the case of booster, this log data is consumed in the
/// USB task.
pub struct BufferedLog {
buffer: core::cell::UnsafeCell<LogBuffer>,
}

// Critical sections are used to manage the buffer access. This type is safe to share across contexts.
unsafe impl Sync for BufferedLog {}

impl BufferedLog {
/// Construct a new buffered log object.
pub const fn new() -> Self {
Self {
buffer: core::cell::UnsafeCell::new(LogBuffer::new()),
}
}

/// Process all of the available log data.
///
/// # Args
/// * `terminal` - The serial terminal to write log data into.
pub fn process(&self, terminal: &mut SerialTerminal) {
cortex_m::interrupt::free(|_cs| {
let buffer = unsafe { &mut *self.buffer.get() };
terminal.write(buffer.data());
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Doesn't this take quite a while?
It's in a critical section.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This boils down into a copy into the USB serial output port buffer, so the actual blocking time should just be the amount of time to copy the data - the output isn't actually transmitted over USB here.

buffer.clear();
});
}
}

impl log::Log for BufferedLog {
fn enabled(&self, _metadata: &log::Metadata) -> bool {
true
}

fn log(&self, record: &log::Record) {
let source_file = record.file().unwrap_or("Unknown");
let source_line = record.line().unwrap_or(u32::MAX);

// Print the record into the buffer.
let mut string: String<consts::U128> = String::new();
match write!(
&mut string,
"[{}] {}:{} - {}\n",
record.level(),
source_file,
source_line,
record.args()
) {
Err(_) => warn!("Log buffer overflow"),
ryan-summers marked this conversation as resolved.
Show resolved Hide resolved
_ => {}
};

cortex_m::interrupt::free(|_cs| {
let buffer = unsafe { &mut *self.buffer.get() };
buffer.append(&string.into_bytes());
});
}

// The log is not capable of being flushed as it does not own the data consumer.
fn flush(&self) {}
}

/// An internal buffer for storing serialized log data. This is essentially a vector of u8.
struct LogBuffer {
data: [u8; 1024],
index: usize,
}

impl LogBuffer {
/// Construct the buffer.
pub const fn new() -> Self {
Self {
data: [0u8; 1024],
index: 0,
}
}

/// Append data into the buffer.
///
/// # Args
/// * `data` - The data to append. If space isn't available, as much data will be appended as
/// possible.
pub fn append(&mut self, data: &[u8]) {
let tail = &mut self.data[self.index..];
self.index += if data.len() > tail.len() {
tail.copy_from_slice(&data[..tail.len()]);
tail.len()
} else {
tail[..data.len()].copy_from_slice(data);
data.len()
}
}

/// Get the data in the buffer.
pub fn data(&self) -> &[u8] {
&self.data[..self.index]
}

/// Clear contents of the buffer.
pub fn clear(&mut self) {
self.index = 0;
}
}
13 changes: 13 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ mod chassis_fans;
mod delay;
mod error;
mod linear_transformation;
mod logger;
mod mqtt_control;
mod mutex;
mod platform;
Expand All @@ -37,6 +38,7 @@ use booster_channels::{BoosterChannels, Channel};
use chassis_fans::ChassisFans;
use delay::AsmDelay;
use error::Error;
use logger::BufferedLog;
use rf_channel::{AdcPin, AnalogPins as AdcPins, ChannelPins as RfChannelPins, ChannelState};
use serial_terminal::SerialTerminal;
use settings::BoosterSettings;
Expand Down Expand Up @@ -138,6 +140,8 @@ macro_rules! channel_pins {
// USB end-point memory.
static mut USB_EP_MEMORY: [u32; 1024] = [0; 1024];

static LOGGER: BufferedLog = BufferedLog::new();

/// Container method for all devices on the main I2C bus.
pub struct MainBus {
pub channels: BoosterChannels,
Expand All @@ -162,6 +166,11 @@ const APP: () = {
static mut USB_BUS: Option<usb_device::bus::UsbBusAllocator<UsbBus>> = None;
static mut USB_SERIAL: Option<String<heapless::consts::U64>> = None;

// Install the logger
log::set_logger(&LOGGER)
.map(|()| log::set_max_level(log::LevelFilter::Info))
.unwrap();

c.core.DWT.enable_cycle_counter();
c.core.DCB.enable_trace();

Expand Down Expand Up @@ -678,6 +687,10 @@ const APP: () = {
.watchdog
.lock(|watchdog| watchdog.check_in(WatchdogClient::UsbTask));

// Process any log output.
LOGGER.process(&mut c.resources.usb_terminal);

// Handle the USB serial terminal.
c.resources.usb_terminal.process();

// TODO: Replace hard-coded CPU cycles here.
Expand Down