Skip to content

Commit

Permalink
heapless 0.8 changes
Browse files Browse the repository at this point in the history
  • Loading branch information
jordens committed Nov 13, 2023
1 parent 6b09939 commit a52e7d1
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 33 deletions.
50 changes: 22 additions & 28 deletions src/net/data_stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@
//! of livestreamed data.
use core::mem::MaybeUninit;
use heapless::{
pool::{Box, Init, Pool, Uninit},
box_pool,
pool::boxed::{Box, BoxBlock},
spsc::{Consumer, Producer, Queue},
};
use num_enum::IntoPrimitive;
Expand Down Expand Up @@ -53,13 +54,14 @@ const FRAME_SIZE: usize = 1500 - 40 - 8;
// allocated frame buffer should fit in the queue.
const FRAME_QUEUE_SIZE: usize = FRAME_COUNT * 2;

// Static storage used for a heapless::Pool of frame buffers.
static mut FRAME_DATA: [u8; core::mem::size_of::<u8>()
* FRAME_SIZE
* FRAME_COUNT] = [0; core::mem::size_of::<u8>() * FRAME_SIZE * FRAME_COUNT];

type Frame = [MaybeUninit<u8>; FRAME_SIZE];

box_pool!(FRAME_POOL: Frame);

Check warning on line 59 in src/net/data_stream.rs

View workflow job for this annotation

GitHub Actions / clippy

type `FRAME_POOL` should have an upper camel case name

warning: type `FRAME_POOL` should have an upper camel case name --> src/net/data_stream.rs:59:11 | 59 | box_pool!(FRAME_POOL: Frame); | ^^^^^^^^^^ help: convert the identifier to upper camel case: `FramePool` | = note: `#[warn(non_camel_case_types)]` on by default

// Static storage used for a heapless::Pool of frame buffers.
const BLOCK: BoxBlock<Frame> = BoxBlock::new();

Check warning on line 62 in src/net/data_stream.rs

View workflow job for this annotation

GitHub Actions / clippy

a `const` item should never be interior mutable

warning: a `const` item should never be interior mutable --> src/net/data_stream.rs:62:1 | 62 | const BLOCK: BoxBlock<Frame> = BoxBlock::new(); | -----^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | | | make this a static item (maybe with lazy_static) | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#declare_interior_mutable_const = note: `#[warn(clippy::declare_interior_mutable_const)]` on by default
static mut FRAME_DATA: [BoxBlock<Frame>; FRAME_COUNT] = [BLOCK; FRAME_COUNT];

/// Represents the destination for the UDP stream to send data to.
///
/// # Miniconf
Expand Down Expand Up @@ -129,34 +131,32 @@ pub fn setup_streaming(
.unwrap();
let (producer, consumer) = queue.split();

let frame_pool = cortex_m::singleton!(: Pool<Frame> = Pool::new()).unwrap();

// Note(unsafe): We guarantee that FRAME_DATA is only accessed once in this function.
let memory = unsafe { &mut FRAME_DATA };
frame_pool.grow(memory);
let blocks = unsafe { &mut FRAME_DATA };
for block in blocks {
FRAME_POOL.manage(block);
}

let generator = FrameGenerator::new(producer, frame_pool);
let generator = FrameGenerator::new(producer);

let stream = DataStream::new(stack, consumer, frame_pool);
let stream = DataStream::new(stack, consumer);

(generator, stream)
}

#[derive(Debug)]
struct StreamFrame {
buffer: Box<Frame, Init>,
buffer: Box<FRAME_POOL>,
offset: usize,
batches: u8,
}

impl StreamFrame {
pub fn new(
buffer: Box<Frame, Uninit>,
mut buffer: Box<FRAME_POOL>,
format_id: u8,
sequence_number: u32,
) -> Self {
let mut buffer = buffer.init([MaybeUninit::uninit(); FRAME_SIZE]);

for (byte, buf) in MAGIC
.to_le_bytes()
.iter()
Expand Down Expand Up @@ -197,20 +197,15 @@ impl StreamFrame {
/// The data generator for a stream.
pub struct FrameGenerator {
queue: Producer<'static, StreamFrame, FRAME_QUEUE_SIZE>,
pool: &'static Pool<Frame>,
current_frame: Option<StreamFrame>,
sequence_number: u32,
format: u8,
}

impl FrameGenerator {
fn new(
queue: Producer<'static, StreamFrame, FRAME_QUEUE_SIZE>,
pool: &'static Pool<Frame>,
) -> Self {
fn new(queue: Producer<'static, StreamFrame, FRAME_QUEUE_SIZE>) -> Self {
Self {
queue,
pool,
format: StreamFormat::Unknown.into(),
current_frame: None,
sequence_number: 0,
Expand Down Expand Up @@ -242,7 +237,9 @@ impl FrameGenerator {
self.sequence_number = self.sequence_number.wrapping_add(1);

if self.current_frame.is_none() {
if let Some(buffer) = self.pool.alloc() {
if let Ok(buffer) =
FRAME_POOL.alloc([MaybeUninit::uninit(); FRAME_SIZE])
{
self.current_frame.replace(StreamFrame::new(
buffer,
self.format,
Expand Down Expand Up @@ -276,7 +273,6 @@ pub struct DataStream {
stack: NetworkReference,
socket: Option<<NetworkReference as UdpClientStack>::UdpSocket>,
queue: Consumer<'static, StreamFrame, FRAME_QUEUE_SIZE>,
frame_pool: &'static Pool<Frame>,
remote: SocketAddr,
}

Expand All @@ -290,14 +286,12 @@ impl DataStream {
fn new(
stack: NetworkReference,
consumer: Consumer<'static, StreamFrame, FRAME_QUEUE_SIZE>,
frame_pool: &'static Pool<Frame>,
) -> Self {
Self {
stack,
socket: None,
remote: StreamTarget::default().into(),
queue: consumer,
frame_pool,
}
}

Expand Down Expand Up @@ -350,7 +344,7 @@ impl DataStream {
if self.open().is_ok() {
// If we just successfully opened the socket, flush old data from queue.
while let Some(frame) = self.queue.dequeue() {
self.frame_pool.free(frame.buffer);
drop(frame.buffer);
}
}
}
Expand All @@ -365,7 +359,7 @@ impl DataStream {
)
};
self.stack.send(handle, data).ok();
self.frame_pool.free(frame.buffer)
drop(frame.buffer);
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/net/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -205,9 +205,9 @@ where
// `settings_path` has to be at least as large as `miniconf::mqtt_client::MAX_TOPIC_LENGTH`.
let mut settings_path: String<128> = String::new();
match self.miniconf.handled_update(|path, old, new| {
settings_path = path.into();
settings_path = path.try_into().or(Err("path too long"))?;
*old = new.clone();
Result::<(), &'static str>::Ok(())
Result::<_, &'static str>::Ok(())
}) {
Ok(true) => NetworkState::SettingsChanged(settings_path),
_ => poll_result,
Expand Down
7 changes: 4 additions & 3 deletions src/net/telemetry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
//! sampling frequency. Instead, the raw codes are stored and the telemetry is generated as
//! required immediately before transmission. This ensures that any slower computation required
//! for unit conversion can be off-loaded to lower priority tasks.
use heapless::{String, Vec};
use heapless::String;
use serde::Serialize;

use super::NetworkReference;
Expand Down Expand Up @@ -115,7 +115,8 @@ impl<T: Serialize> TelemetryClient<T> {
>,
prefix: &str,
) -> Self {
let mut telemetry_topic: String<128> = String::from(prefix);
let mut telemetry_topic: String<128> =
String::try_from(prefix).unwrap();
telemetry_topic.push_str("/telemetry").unwrap();

Self {
Expand All @@ -134,7 +135,7 @@ impl<T: Serialize> TelemetryClient<T> {
/// # Args
/// * `telemetry` - The telemetry to report
pub fn publish(&mut self, telemetry: &T) {
let telemetry: Vec<u8, 512> =
let telemetry: serde_json_core::heapless::Vec<u8, 512> =
serde_json_core::to_vec(telemetry).unwrap();
self.mqtt
.client()
Expand Down

0 comments on commit a52e7d1

Please sign in to comment.