Skip to main content

SensorDbAsync

Struct SensorDbAsync 

Source
pub struct SensorDbAsync<F, const PAGE_SIZE: usize, const MAX_SECTORS: usize> { /* private fields */ }
Available on crate feature async only.
Expand description

Async append-only sensor database for NOR flash.

This is the async counterpart of SensorDb, using embedded-storage-async traits for all flash operations. It is designed for use with Embassy on targets that benefit from DMA-based flash access.

§Key differences from SensorDb

  • All flash-touching methods are async fn
  • All methods take &mut self (no RefCell / interior mutability)
  • Reuses the same wire format, sector layout, and SensorDbState value

Generic parameters:

  • F: Flash storage implementing async NorFlash and ReadNorFlash
  • PAGE_SIZE: the unit this database writes in. Must be a multiple of F::WRITE_SIZE, checked at compile time, and must not exceed the part’s physical program page — which the trait does not express, so it cannot be checked. See SensorDb for the full contract.
  • MAX_SECTORS: Maximum number of sectors this instance can manage

Implementations§

Source§

impl<F, const PAGE_SIZE: usize, const MAX_SECTORS: usize> SensorDbAsync<F, PAGE_SIZE, MAX_SECTORS>

Source

pub fn new( flash: F, base_offset: u32, sector_count: u16, reserved_sectors: u16, ) -> Result<Self, Error>

Create a new async SensorDb instance.

§Arguments
  • flash: Async flash storage
  • base_offset: Starting offset in flash for the database region
  • sector_count: Number of sectors to use
  • reserved_sectors: Number of sectors to keep free for compaction headroom
§Errors
  • TooManySectors if sector_count > MAX_SECTORS
  • InvalidConfig if reserved_sectors >= sector_count
Source

pub fn with_config(flash: F, config: DbConfig) -> Result<Self, Error>

Create a SensorDbAsync from a validated DbConfig.

Use this instead of new when the database needs a LogId — for example when its storage is removable and could be carried to, or confused with, another device.

§Errors
  • TooManySectors if config.sector_count() > MAX_SECTORS
  • Overflow if the region does not fit in u32 address space
§Panics

Fails to compile, not to run, if PAGE_SIZE is not a multiple of F::WRITE_SIZE.

Source

pub async fn format(&mut self) -> Result<(), Error>

Format the database region, erasing all sectors and initializing the first as active.

After format, the database is automatically mounted.

Source

pub async fn mount(&mut self) -> Result<MountStats, Error>

Mount an existing database by scanning all sectors and rebuilding the index.

Equivalent to mount_with(MountMode::Full).

§Errors
  • AlreadyMounted if already mounted
  • ForeignVolume if the medium belongs to a different log
  • UnsupportedVersion if the medium uses a newer format
Source

pub async fn mount_with(&mut self, mode: MountMode) -> Result<MountStats, Error>

Mount an existing database, choosing how much of the index to rebuild.

See SensorDb::mount_with for the foreign-media and epoch semantics; they are identical here.

§Errors
  • AlreadyMounted if already mounted
  • ForeignVolume if the medium belongs to a different log
  • UnsupportedVersion if the medium uses a newer format
Source

pub async fn append( &mut self, sensor_id: u16, timestamp: u64, payload: &[u8], ) -> Result<(), Error>

Append a sensor reading to the database.

§Errors
  • NotMounted if not mounted
  • PayloadTooLarge if payload exceeds max size
  • NoSpace if no sectors available
Source

pub async fn append_run(&mut self, run: &Run<'_>) -> Result<(), Error>

Append a run: many evenly spaced samples under one header.

Async mirror of SensorDb::append_run, including its invisibility to every read.

Source

pub async fn append_framed( &mut self, header: &EntryHeader, payload: &[u8], ) -> Result<(), Error>

Append an entry exactly as another log stored it.

Async mirror of SensorDb::append_framed.

Source

pub async fn sync(&mut self) -> Result<(), Error>

Flush the page buffer to flash, committing buffered entries.

Source

pub async fn latest( &mut self, sensor_id: u16, buf: &mut [u8], ) -> Result<Option<(EntryHeader, usize)>, Error>

Find the most recent entry for a given sensor.

§Arguments
  • sensor_id: Sensor to query
  • buf: Buffer to receive payload
§Returns

Some((header, payload_len)) if found, None if no entries for this sensor.

Source

pub async fn query_range<C>( &mut self, sensor_id: Option<u16>, t_start: u64, t_end: u64, callback: C, ) -> Result<u32, Error>
where C: FnMut(&EntryHeader, &[u8]) -> bool,

Query entries within a time range.

§Arguments
  • sensor_id: Optional sensor filter (None for all sensors)
  • t_start: Start timestamp (inclusive)
  • t_end: End timestamp (inclusive)
  • callback: Called for each matching entry. Return false to stop early.
§Returns

Number of entries that matched.

Source

pub async fn query_all<C>( &mut self, sensor_id: Option<u16>, callback: C, ) -> Result<u32, Error>
where C: FnMut(&EntryHeader, &[u8]) -> bool,

Query all entries for a sensor (or all sensors) without time constraints.

Source

pub async fn oldest( &mut self, sensor_id: u16, buf: &mut [u8], ) -> Result<Option<(EntryHeader, usize)>, Error>

Find the oldest (earliest) entry for a given sensor.

Source

pub async fn count(&mut self, sensor_id: Option<u16>) -> Result<u32, Error>

Count entries for a specific sensor (or all sensors).

Exact, and priced, exactly as SensorDb::count — the count matches what query_range would yield, at the cost of a payload read per entry in each sector the bloom filter does not reject.

Source

pub async fn compact( &mut self, count: u16, scope: CompactScope, ) -> Result<u16, Error>

Compact the database by erasing the oldest sealed sectors.

See SensorDb::compact for the meaning of scope.

Source

pub fn sectors_erased(&self) -> u32

Sectors this instance has erased, since it was created.

See SensorDb::sectors_erased.

Source

pub fn stats(&self) -> DbStats

Get database statistics.

Source

pub fn is_mounted(&self) -> bool

Check if the database is mounted.

Source

pub fn max_payload_size(&self) -> usize

Maximum payload size that can fit in a single entry.

Source

pub async fn append_value<T: IntoBytes + Immutable>( &mut self, sensor_id: u16, timestamp: u64, data: &T, ) -> Result<(), Error>

Append a typed value with an explicit sensor ID, untagged.

Entries written this way carry no schema version and are not readable through the *_sensor methods.

Source

pub async fn latest_value<T: FromBytes + KnownLayout>( &mut self, sensor_id: u16, ) -> Result<Option<(EntryHeader, T)>, Error>

Find the most recent entry for a sensor and interpret as a typed value.

Source

pub async fn append_sensor<T: SensorData>( &mut self, timestamp: u64, data: &T, ) -> Result<(), Error>

Append a sensor reading using the type-driven API.

The payload is the type’s SCHEMA_VERSION followed by the value’s bytes; see SensorData::SCHEMA_VERSION.

Source

pub async fn latest_sensor<T: SensorData>( &mut self, ) -> Result<Option<(EntryHeader, T)>, Error>

Find the most recent entry for a sensor type.

§Errors
  • SizeMismatch if the stored payload is not size_of::<T>() + 1 bytes
  • SchemaMismatch if it was written under another SCHEMA_VERSION
Source

pub async fn query_sensor<T: SensorData, C>( &mut self, t_start: u64, t_end: u64, callback: C, ) -> Result<u32, Error>
where C: FnMut(&EntryHeader, &T) -> bool,

Query sensor entries within a time range using the type-driven API.

Source

pub async fn query_all_sensor<T: SensorData, C>( &mut self, callback: C, ) -> Result<u32, Error>
where C: FnMut(&EntryHeader, &T) -> bool,

Query all entries for a sensor type without time constraints.

Source

pub async fn oldest_sensor<T: SensorData>( &mut self, ) -> Result<Option<(EntryHeader, T)>, Error>

Find the oldest (earliest) entry for a sensor type.

Source

pub async fn count_sensor<T: SensorData>(&mut self) -> Result<u32, Error>

Count entries for a sensor type.

Source

pub async fn read_from<C>( &mut self, from: LogPosition, max_entries: u32, callback: C, ) -> Result<ReadCursor, Error>

Deliver committed entries in log order, starting at from (inclusive).

Async mirror of SensorDb::read_from; see there for the durability boundary, ordering, and gap semantics.

§Errors
  • NotMounted if the database is not mounted
  • whatever the callback returns
Source

pub fn drain_unflushed<C>(&mut self, callback: C) -> Result<u32, Error>
where C: FnMut(&EntryHeader, &[u8]) -> Result<(), Error>,

Hand out entries buffered in RAM but not yet durable, then discard them.

Async mirror of SensorDb::drain_unflushed. Touches no flash, so it works when the device has physically gone away.

Source

pub fn peek_unflushed<C>(&self, callback: C) -> Result<u32, Error>
where C: FnMut(&EntryHeader, &[u8]) -> Result<(), Error>,

Show the RAM-buffered entries without removing them.

Async mirror of SensorDb::peek_unflushed. Not async: it touches no flash.

Source

pub async fn sector_epoch_at( &mut self, position: LogPosition, ) -> Result<Option<u32>, Error>

The epoch of the sector containing position.

Async mirror of SensorDb::sector_epoch_at.

Source

pub fn mark_as_replica(&mut self)

Declare this log a replica of another, suppressing the per-run epoch roll.

See SensorDb::mark_as_replica.

Source

pub fn head_position(&self) -> LogPosition

Position immediately after the newest entry, buffered entries included.

Source

pub fn tail_position(&self) -> LogPosition

Position of the oldest entry the log still retains.

Source

pub fn note_spooled(&mut self, upto: LogPosition, moved: Replicated)

Advance the replication watermark. See SensorDb::note_spooled.

Source

pub async fn restore_spool_watermark( &mut self, upto: LogPosition, ) -> Result<(), Error>

Restore the replication watermark from an external source of truth. See SensorDb::restore_spool_watermark, including why an Err leaves the log fully usable.

async because exact accounting costs one scan of the sector the watermark falls inside.

Source

pub fn spool_stats(&self) -> SpoolStats

Replication accounting for this log.

Source

pub fn log_id(&self) -> Option<LogId>

This log’s declared identity, if any.

Source

pub fn epoch(&self) -> u32

The current epoch — one higher than any epoch seen on the medium at mount.

Source

pub fn mount_mode(&self) -> MountMode

How much of the index the current mount rebuilt.

Source

pub fn region( &mut self, base: u32, len: u32, ) -> Result<Partition<&mut F>, Error>

Flash access bounded to [base, base + len).

The async counterpart of SensorDb::with_region, and it returns the Partition rather than taking a closure: a closure cannot express an awaited operation, because the future it returned would borrow from its own argument and the signature has nowhere to tie that lifetime to.

The same check applies — a region intersecting the database’s sectors is rejected with Error::RegionOverlap — and it applies at the point the partition is handed out, which is the only place it can be applied.

§Errors
  • RegionOverlap if the region intersects the database’s sectors
  • InvalidConfig if base or len is misaligned, len is zero, or the region runs past the device’s capacity
  • Overflow if base + len does not fit in u32
Source

pub fn driver_mut(&mut self) -> &mut F

Borrow the underlying flash driver.

See SensorDb::driver_mut: driver capabilities only — presence detection, wear counters, chip identification, power modes. To address flash, use region, which is checked.

Source

pub fn into_inner(self) -> F

Consume the database and return the underlying flash storage.

Trait Implementations§

Source§

impl<F, const PAGE_SIZE: usize, const MAX_SECTORS: usize> Debug for SensorDbAsync<F, PAGE_SIZE, MAX_SECTORS>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<F, const PAGE_SIZE: usize, const MAX_SECTORS: usize> LogSinkAsync for SensorDbAsync<F, PAGE_SIZE, MAX_SECTORS>

Source§

fn append( &mut self, sensor_id: u16, timestamp: u64, payload: &[u8], ) -> impl Future<Output = Result<(), Error>>

Append a sample.
Source§

fn append_run( &mut self, run: &Run<'_>, ) -> impl Future<Output = Result<(), Error>>

Append a run: many evenly spaced samples under one header.
Source§

fn sync(&mut self) -> impl Future<Output = Result<(), Error>>

Make everything appended so far durable.
Source§

impl<F, const PAGE_SIZE: usize, const MAX_SECTORS: usize> LogSourceAsync for SensorDbAsync<F, PAGE_SIZE, MAX_SECTORS>

Source§

fn latest( &mut self, sensor_id: u16, buf: &mut [u8], ) -> impl Future<Output = Result<Option<(EntryHeader, usize)>, Error>>

The most recent entry for a sensor, or None if it has none.
Source§

fn oldest( &mut self, sensor_id: u16, buf: &mut [u8], ) -> impl Future<Output = Result<Option<(EntryHeader, usize)>, Error>>

The oldest retained entry for a sensor, or None if it has none.
Source§

fn count( &mut self, sensor_id: Option<u16>, ) -> impl Future<Output = Result<u32, Error>>

Entries retained for a sensor, or for every sensor if None.
Source§

fn query_range( &mut self, sensor_id: Option<u16>, t_start: u64, t_end: u64, callback: &mut dyn FnMut(&EntryHeader, &[u8]) -> bool, ) -> impl Future<Output = Result<u32, Error>>

Entries whose timestamp lies in [t_start, t_end], in log order. Read more

Auto Trait Implementations§

§

impl<F, const PAGE_SIZE: usize, const MAX_SECTORS: usize> Freeze for SensorDbAsync<F, PAGE_SIZE, MAX_SECTORS>
where F: Freeze, SensorDbState<PAGE_SIZE, MAX_SECTORS>: Freeze,

§

impl<F, const PAGE_SIZE: usize, const MAX_SECTORS: usize> RefUnwindSafe for SensorDbAsync<F, PAGE_SIZE, MAX_SECTORS>
where F: RefUnwindSafe, SensorDbState<PAGE_SIZE, MAX_SECTORS>: RefUnwindSafe,

§

impl<F, const PAGE_SIZE: usize, const MAX_SECTORS: usize> Send for SensorDbAsync<F, PAGE_SIZE, MAX_SECTORS>
where F: Send, SensorDbState<PAGE_SIZE, MAX_SECTORS>: Send,

§

impl<F, const PAGE_SIZE: usize, const MAX_SECTORS: usize> Sync for SensorDbAsync<F, PAGE_SIZE, MAX_SECTORS>
where F: Sync, SensorDbState<PAGE_SIZE, MAX_SECTORS>: Sync,

§

impl<F, const PAGE_SIZE: usize, const MAX_SECTORS: usize> Unpin for SensorDbAsync<F, PAGE_SIZE, MAX_SECTORS>
where F: Unpin, SensorDbState<PAGE_SIZE, MAX_SECTORS>: Unpin,

§

impl<F, const PAGE_SIZE: usize, const MAX_SECTORS: usize> UnsafeUnpin for SensorDbAsync<F, PAGE_SIZE, MAX_SECTORS>
where F: UnsafeUnpin, SensorDbState<PAGE_SIZE, MAX_SECTORS>: UnsafeUnpin,

§

impl<F, const PAGE_SIZE: usize, const MAX_SECTORS: usize> UnwindSafe for SensorDbAsync<F, PAGE_SIZE, MAX_SECTORS>
where F: UnwindSafe, SensorDbState<PAGE_SIZE, MAX_SECTORS>: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<L> LogSinkAsyncExt for L
where L: LogSinkAsync + ?Sized,

Source§

fn append_value<T: IntoBytes + Immutable>( &mut self, sensor_id: u16, timestamp: u64, data: &T, ) -> impl Future<Output = Result<(), Error>>

Append a value’s bytes under an explicit sensor ID, untagged.
Source§

fn append_sensor<T: SensorData>( &mut self, timestamp: u64, data: &T, ) -> impl Future<Output = Result<(), Error>>

Append a value under the sensor ID its type declares, schema-tagged.
Source§

impl<L> LogSourceAsyncExt for L
where L: LogSourceAsync + ?Sized,

Source§

fn latest_sensor<T: SensorData>( &mut self, ) -> impl Future<Output = Result<Option<(EntryHeader, T)>, Error>>

The most recent value for a sensor type.
Source§

fn oldest_sensor<T: SensorData>( &mut self, ) -> impl Future<Output = Result<Option<(EntryHeader, T)>, Error>>

The oldest retained value for a sensor type.
Source§

fn count_sensor<T: SensorData>( &mut self, ) -> impl Future<Output = Result<u32, Error>>

Entries retained for a sensor type.
Source§

fn query_sensor<T: SensorData, C>( &mut self, t_start: u64, t_end: u64, callback: C, ) -> impl Future<Output = Result<u32, Error>>
where C: FnMut(&EntryHeader, &T) -> bool,

Values for a sensor type whose timestamp lies in [t_start, t_end].
Source§

fn query_all_sensor<T: SensorData, C>( &mut self, callback: C, ) -> impl Future<Output = Result<u32, Error>>
where C: FnMut(&EntryHeader, &T) -> bool,

Every retained value for a sensor type, in log order.
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.