Skip to main content

sensor_db/
logger.rs

1//! Convenience wrapper that injects timestamps from a user-provided clock.
2//!
3//! [`SensorLogger`] wraps anything that can take a sample — a
4//! [`SensorDb`](crate::SensorDb), a [`TieredDb`](crate::TieredDb), or any other
5//! [`LogSink`] — together with a clock function, eliminating the need to pass a
6//! timestamp on every append call.
7//!
8//! # Example
9//!
10//! ```ignore
11//! use sensor_db::{SensorDb, SensorLogger};
12//!
13//! let db: SensorDb<_, 256, 32> = SensorDb::new(flash, 0, 32, 2)?;
14//! let mut logger = SensorLogger::new(db, || get_timestamp_us());
15//!
16//! logger.log(&Temperature { celsius: 25.5 })?;
17//! logger.sync()?;
18//! ```
19//!
20//! The same wrapper over a tier, so a card can come and go beneath it:
21//!
22//! ```ignore
23//! let mut logger = SensorLogger::new(tiered, || get_timestamp_us());
24//! logger.log(&Temperature { celsius: 25.5 })?;
25//! ```
26
27use crate::error::Error;
28use crate::port::{LogSink, LogSinkAsync, LogSinkAsyncExt, LogSinkExt};
29use crate::typed::SensorData;
30use zerocopy::{Immutable, IntoBytes};
31
32/// A convenience wrapper around a [`LogSink`] that automatically timestamps entries.
33///
34/// The `Clock` parameter is any `Fn() -> u64` that returns the current timestamp
35/// (typically microseconds since epoch). This avoids threading a timestamp through
36/// every call site.
37///
38/// For query and read access, use [`sink()`](SensorLogger::sink) or
39/// [`sink_mut()`](SensorLogger::sink_mut) to reach the wrapped log — the logger
40/// deliberately exposes no reads of its own, so nothing here has to be
41/// duplicated when the log underneath changes.
42pub struct SensorLogger<L, Clock>
43where
44    Clock: Fn() -> u64,
45{
46    sink: L,
47    clock: Clock,
48}
49
50impl<L, Clock> SensorLogger<L, Clock>
51where
52    L: LogSink,
53    Clock: Fn() -> u64,
54{
55    /// Create a new `SensorLogger` wrapping an existing log.
56    ///
57    /// # Arguments
58    /// - `sink`: A mounted (or freshly formatted) log
59    /// - `clock`: Function returning the current timestamp as `u64`
60    pub fn new(sink: L, clock: Clock) -> Self {
61        Self { sink, clock }
62    }
63
64    /// Log a typed sensor reading with an auto-generated timestamp.
65    ///
66    /// The sensor ID is derived from `T::SENSOR_ID`.
67    pub fn log<T: SensorData>(&mut self, data: &T) -> Result<(), Error> {
68        let ts = (self.clock)();
69        self.sink.append_sensor(ts, data)
70    }
71
72    /// Log a raw payload with an auto-generated timestamp.
73    ///
74    /// # Arguments
75    /// - `sensor_id`: Sensor identifier
76    /// - `payload`: Raw sensor data bytes
77    pub fn log_raw(&mut self, sensor_id: u16, payload: &[u8]) -> Result<(), Error> {
78        let ts = (self.clock)();
79        self.sink.append(sensor_id, ts, payload)
80    }
81
82    /// Log a typed value with an explicit sensor ID and auto-generated timestamp.
83    ///
84    /// This is the Layer 1 equivalent — you provide the sensor ID, the clock
85    /// provides the timestamp.
86    pub fn log_value<T: IntoBytes + Immutable>(
87        &mut self,
88        sensor_id: u16,
89        data: &T,
90    ) -> Result<(), Error> {
91        let ts = (self.clock)();
92        self.sink.append_value(sensor_id, ts, data)
93    }
94
95    /// Flush the page buffer to flash.
96    ///
97    /// Delegates to [`LogSink::sync`].
98    pub fn sync(&mut self) -> Result<(), Error> {
99        self.sink.sync()
100    }
101
102    /// Immutable access to the wrapped log.
103    ///
104    /// Enough for the accessors that touch no flash —
105    /// [`stats`](crate::SensorDb::stats), `is_mounted`, `spool_stats` and the
106    /// rest. Reads and writes both go through
107    /// [`sink_mut()`](Self::sink_mut), because reading flash is a `&mut`
108    /// operation.
109    pub fn sink(&self) -> &L {
110        &self.sink
111    }
112
113    /// Mutable access to the wrapped log, for writes and queries.
114    pub fn sink_mut(&mut self) -> &mut L {
115        &mut self.sink
116    }
117
118    /// Consume the logger and return the wrapped log and clock.
119    pub fn into_inner(self) -> (L, Clock) {
120        (self.sink, self.clock)
121    }
122}
123
124// ---------------------------------------------------------------------------
125// Async logger
126// ---------------------------------------------------------------------------
127
128/// Async version of [`SensorLogger`], wrapping any [`LogSinkAsync`].
129///
130/// All logging methods are `async fn` and take `&mut self`. For query access,
131/// use [`sink_mut()`](SensorLoggerAsync::sink_mut) to reach the wrapped log.
132///
133/// # Example
134///
135/// ```ignore
136/// use sensor_db::{SensorDbAsync, SensorLoggerAsync};
137///
138/// let db: SensorDbAsync<_, 256, 32> = SensorDbAsync::new(flash, 0, 32, 2)?;
139/// let mut logger = SensorLoggerAsync::new(db, || get_timestamp_us());
140///
141/// logger.log(&Temperature { celsius: 25.5 }).await?;
142/// logger.sync().await?;
143/// ```
144pub struct SensorLoggerAsync<L, Clock>
145where
146    Clock: Fn() -> u64,
147{
148    sink: L,
149    clock: Clock,
150}
151
152impl<L, Clock> SensorLoggerAsync<L, Clock>
153where
154    L: LogSinkAsync,
155    Clock: Fn() -> u64,
156{
157    /// Create a new `SensorLoggerAsync` wrapping an existing log.
158    ///
159    /// # Arguments
160    /// - `sink`: A mounted (or freshly formatted) async log
161    /// - `clock`: Function returning the current timestamp as `u64`
162    pub fn new(sink: L, clock: Clock) -> Self {
163        Self { sink, clock }
164    }
165
166    /// Log a typed sensor reading with an auto-generated timestamp.
167    ///
168    /// The sensor ID is derived from `T::SENSOR_ID`.
169    pub async fn log<T: SensorData>(&mut self, data: &T) -> Result<(), Error> {
170        let ts = (self.clock)();
171        self.sink.append_sensor(ts, data).await
172    }
173
174    /// Log a raw payload with an auto-generated timestamp.
175    ///
176    /// # Arguments
177    /// - `sensor_id`: Sensor identifier
178    /// - `payload`: Raw sensor data bytes
179    pub async fn log_raw(&mut self, sensor_id: u16, payload: &[u8]) -> Result<(), Error> {
180        let ts = (self.clock)();
181        self.sink.append(sensor_id, ts, payload).await
182    }
183
184    /// Log a typed value with an explicit sensor ID and auto-generated timestamp.
185    ///
186    /// This is the Layer 1 equivalent — you provide the sensor ID, the clock
187    /// provides the timestamp.
188    pub async fn log_value<T: IntoBytes + Immutable>(
189        &mut self,
190        sensor_id: u16,
191        data: &T,
192    ) -> Result<(), Error> {
193        let ts = (self.clock)();
194        self.sink.append_value(sensor_id, ts, data).await
195    }
196
197    /// Flush the page buffer to flash.
198    ///
199    /// Delegates to [`LogSinkAsync::sync`].
200    pub async fn sync(&mut self) -> Result<(), Error> {
201        self.sink.sync().await
202    }
203
204    /// Mutable access to the wrapped log.
205    ///
206    /// Every async read takes `&mut self`, so this is the accessor to reach for
207    /// — unlike the blocking logger, where [`sink()`](Self::sink) covers reads.
208    pub fn sink_mut(&mut self) -> &mut L {
209        &mut self.sink
210    }
211
212    /// Immutable access to the wrapped log.
213    ///
214    /// Only useful for non-flash methods like `stats()`, `is_mounted()`,
215    /// and `max_payload_size()`.
216    pub fn sink(&self) -> &L {
217        &self.sink
218    }
219
220    /// Consume the logger and return the wrapped log and clock.
221    pub fn into_inner(self) -> (L, Clock) {
222        (self.sink, self.clock)
223    }
224}
225
226// ---------------------------------------------------------------------------
227// Tests
228// ---------------------------------------------------------------------------
229
230#[cfg(all(test, feature = "std"))]
231mod tests {
232    extern crate alloc;
233
234    use super::*;
235    use crate::db::SensorDb;
236    use crate::mock::MockFlash;
237    use core::cell::Cell;
238    use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};
239
240    const PAGE: usize = 256;
241    const SECTOR: usize = 4096;
242    const SECTORS: usize = 8;
243
244    type Db = SensorDb<MockFlash<PAGE, SECTOR>, PAGE, SECTORS>;
245
246    #[derive(Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable)]
247    #[repr(C)]
248    struct Temperature {
249        celsius: f32,
250    }
251
252    impl SensorData for Temperature {
253        const SENSOR_ID: u16 = 0x01;
254    }
255
256    fn make_logger(start: u64) -> SensorLogger<Db, impl Fn() -> u64> {
257        let flash = MockFlash::<PAGE, SECTOR>::new(SECTORS * SECTOR);
258        let mut db = SensorDb::new(flash, 0, SECTORS as u16, 1).unwrap();
259        db.format().unwrap();
260
261        let counter = Cell::new(start);
262        SensorLogger::new(db, move || {
263            let ts = counter.get();
264            counter.set(ts + 1000);
265            ts
266        })
267    }
268
269    #[test]
270    fn log_and_retrieve() {
271        let mut logger = make_logger(1000);
272
273        logger.log(&Temperature { celsius: 25.5 }).unwrap();
274        logger.sync().unwrap();
275
276        let (hdr, temp) = logger
277            .sink_mut()
278            .latest_sensor::<Temperature>()
279            .unwrap()
280            .unwrap();
281        assert_eq!(hdr.timestamp, 1000);
282        assert_eq!(temp.celsius, 25.5);
283    }
284
285    #[test]
286    fn log_raw_and_retrieve() {
287        let mut logger = make_logger(5000);
288
289        logger.log_raw(0x42, &[0xDE, 0xAD]).unwrap();
290        logger.sync().unwrap();
291
292        let mut buf = [0u8; 16];
293        let (hdr, n) = logger.sink_mut().latest(0x42, &mut buf).unwrap().unwrap();
294        assert_eq!(hdr.timestamp, 5000);
295        assert_eq!(&buf[..n], &[0xDE, 0xAD]);
296    }
297
298    #[test]
299    fn multiple_logs_increment_timestamp() {
300        let mut logger = make_logger(0);
301
302        for i in 0..5 {
303            logger
304                .log(&Temperature {
305                    celsius: i as f32 * 10.0,
306                })
307                .unwrap();
308        }
309        logger.sync().unwrap();
310
311        // Latest should have timestamp = 4000 (0, 1000, 2000, 3000, 4000)
312        let (hdr, temp) = logger
313            .sink_mut()
314            .latest_sensor::<Temperature>()
315            .unwrap()
316            .unwrap();
317        assert_eq!(hdr.timestamp, 4000);
318        assert_eq!(temp.celsius, 40.0);
319
320        assert_eq!(
321            logger
322                .sink_mut()
323                .count(Some(Temperature::SENSOR_ID))
324                .unwrap(),
325            5
326        );
327    }
328
329    #[test]
330    fn db_access_for_queries() {
331        let mut logger = make_logger(100);
332
333        logger.log(&Temperature { celsius: 20.0 }).unwrap();
334        logger.log(&Temperature { celsius: 21.0 }).unwrap();
335        logger.log(&Temperature { celsius: 22.0 }).unwrap();
336        logger.sync().unwrap();
337
338        // Use db() for non-mutating checks and reads
339        assert!(logger.sink().is_mounted());
340        assert_eq!(logger.sink().stats().total_entries, 3);
341
342        // Use db_mut() for callback-based queries
343        let mut readings = alloc::vec::Vec::new();
344        logger
345            .sink_mut()
346            .query_all_sensor::<Temperature, _>(|hdr, temp| {
347                readings.push((hdr.timestamp, temp.celsius));
348                true
349            })
350            .unwrap();
351
352        assert_eq!(readings.len(), 3);
353        assert_eq!(readings[0], (100, 20.0));
354        assert_eq!(readings[1], (1100, 21.0));
355        assert_eq!(readings[2], (2100, 22.0));
356    }
357
358    #[test]
359    fn into_inner_returns_db_and_clock() {
360        let logger = make_logger(0);
361        let (db, clock) = logger.into_inner();
362        assert!(db.is_mounted());
363        // Clock still works
364        assert_eq!(clock(), 0);
365    }
366
367    #[test]
368    fn logger_db_immutable_reads() {
369        let mut logger = make_logger(1000);
370
371        logger.log(&Temperature { celsius: 20.0 }).unwrap();
372        logger.log(&Temperature { celsius: 25.0 }).unwrap();
373        logger.log(&Temperature { celsius: 30.0 }).unwrap();
374        logger.sync().unwrap();
375
376        // All read methods work through db() (immutable reference)
377        let (hdr, temp) = logger
378            .sink_mut()
379            .latest_sensor::<Temperature>()
380            .unwrap()
381            .unwrap();
382        assert_eq!(hdr.timestamp, 3000);
383        assert_eq!(temp.celsius, 30.0);
384
385        let (hdr, temp) = logger
386            .sink_mut()
387            .oldest_sensor::<Temperature>()
388            .unwrap()
389            .unwrap();
390        assert_eq!(hdr.timestamp, 1000);
391        assert_eq!(temp.celsius, 20.0);
392
393        assert_eq!(logger.sink_mut().count_sensor::<Temperature>().unwrap(), 3);
394        assert_eq!(logger.sink_mut().count(None).unwrap(), 3);
395    }
396}
397
398#[cfg(all(test, feature = "std", feature = "async"))]
399mod async_tests {
400    extern crate alloc;
401
402    use super::*;
403    use crate::async_db::SensorDbAsync;
404    use crate::mock::MockFlash;
405    use core::cell::Cell;
406    use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};
407
408    const PAGE: usize = 256;
409    const SECTOR: usize = 4096;
410    const SECTORS: usize = 8;
411
412    #[derive(Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable)]
413    #[repr(C)]
414    struct Temperature {
415        celsius: f32,
416    }
417
418    impl SensorData for Temperature {
419        const SENSOR_ID: u16 = 0x01;
420    }
421
422    // -- MockFlashAsync adapter (same pattern as async_db tests) -----------
423
424    struct MockFlashAsync<const P: usize, const S: usize> {
425        inner: MockFlash<P, S>,
426    }
427
428    impl<const P: usize, const S: usize> MockFlashAsync<P, S> {
429        fn new(size: usize) -> Self {
430            Self {
431                inner: MockFlash::<P, S>::new(size),
432            }
433        }
434    }
435
436    impl<const P: usize, const S: usize> embedded_storage_async::nor_flash::ErrorType
437        for MockFlashAsync<P, S>
438    {
439        type Error = crate::mock::MockFlashError;
440    }
441
442    impl<const P: usize, const S: usize> embedded_storage_async::nor_flash::ReadNorFlash
443        for MockFlashAsync<P, S>
444    {
445        const READ_SIZE: usize = 1;
446        async fn read(&mut self, offset: u32, buf: &mut [u8]) -> Result<(), Self::Error> {
447            use embedded_storage::nor_flash::ReadNorFlash;
448            self.inner.read(offset, buf)
449        }
450        fn capacity(&self) -> usize {
451            use embedded_storage::nor_flash::ReadNorFlash;
452            self.inner.capacity()
453        }
454    }
455
456    impl<const P: usize, const S: usize> embedded_storage_async::nor_flash::NorFlash
457        for MockFlashAsync<P, S>
458    {
459        const WRITE_SIZE: usize = P;
460        const ERASE_SIZE: usize = S;
461        async fn erase(&mut self, from: u32, to: u32) -> Result<(), Self::Error> {
462            use embedded_storage::nor_flash::NorFlash;
463            self.inner.erase(from, to)
464        }
465        async fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> {
466            use embedded_storage::nor_flash::NorFlash;
467            self.inner.write(offset, bytes)
468        }
469    }
470
471    // -- Minimal block_on --------------------------------------------------
472
473    #[allow(unsafe_code, clippy::never_loop)]
474    fn block_on<T>(fut: impl core::future::Future<Output = T>) -> T {
475        use core::pin::pin;
476        use core::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
477
478        fn dummy_raw_waker() -> RawWaker {
479            fn no_op(_: *const ()) {}
480            fn clone(data: *const ()) -> RawWaker {
481                RawWaker::new(data, &VTABLE)
482            }
483            const VTABLE: RawWakerVTable = RawWakerVTable::new(clone, no_op, no_op, no_op);
484            RawWaker::new(core::ptr::null(), &VTABLE)
485        }
486
487        let waker = unsafe { Waker::from_raw(dummy_raw_waker()) };
488        let mut cx = Context::from_waker(&waker);
489        let mut fut = pin!(fut);
490
491        loop {
492            match fut.as_mut().poll(&mut cx) {
493                Poll::Ready(val) => return val,
494                Poll::Pending => panic!("async operation returned Pending in sync mock"),
495            }
496        }
497    }
498
499    // -- Helpers -----------------------------------------------------------
500
501    fn make_async_logger(
502        start: u64,
503    ) -> SensorLoggerAsync<
504        SensorDbAsync<MockFlashAsync<PAGE, SECTOR>, PAGE, SECTORS>,
505        impl Fn() -> u64,
506    > {
507        let flash = MockFlashAsync::<PAGE, SECTOR>::new(SECTORS * SECTOR);
508        let mut db = SensorDbAsync::new(flash, 0, SECTORS as u16, 1).unwrap();
509        block_on(db.format()).unwrap();
510
511        let counter = Cell::new(start);
512        SensorLoggerAsync::new(db, move || {
513            let ts = counter.get();
514            counter.set(ts + 1000);
515            ts
516        })
517    }
518
519    #[test]
520    fn async_log_and_retrieve() {
521        let mut logger = make_async_logger(1000);
522
523        block_on(logger.log(&Temperature { celsius: 25.5 })).unwrap();
524        block_on(logger.sync()).unwrap();
525
526        let (hdr, temp) = block_on(logger.sink_mut().latest_sensor::<Temperature>())
527            .unwrap()
528            .unwrap();
529        assert_eq!(hdr.timestamp, 1000);
530        assert_eq!(temp.celsius, 25.5);
531    }
532
533    #[test]
534    fn async_log_raw_and_retrieve() {
535        let mut logger = make_async_logger(5000);
536
537        block_on(logger.log_raw(0x42, &[0xDE, 0xAD])).unwrap();
538        block_on(logger.sync()).unwrap();
539
540        let mut buf = [0u8; 16];
541        let (hdr, n) = block_on(logger.sink_mut().latest(0x42, &mut buf))
542            .unwrap()
543            .unwrap();
544        assert_eq!(hdr.timestamp, 5000);
545        assert_eq!(&buf[..n], &[0xDE, 0xAD]);
546    }
547
548    #[test]
549    fn async_multiple_logs_increment_timestamp() {
550        let mut logger = make_async_logger(0);
551
552        for i in 0..5 {
553            block_on(logger.log(&Temperature {
554                celsius: i as f32 * 10.0,
555            }))
556            .unwrap();
557        }
558        block_on(logger.sync()).unwrap();
559
560        let (hdr, temp) = block_on(logger.sink_mut().latest_sensor::<Temperature>())
561            .unwrap()
562            .unwrap();
563        assert_eq!(hdr.timestamp, 4000);
564        assert_eq!(temp.celsius, 40.0);
565
566        assert_eq!(
567            block_on(logger.sink_mut().count(Some(Temperature::SENSOR_ID))).unwrap(),
568            5
569        );
570    }
571
572    #[test]
573    fn async_db_access() {
574        let mut logger = make_async_logger(100);
575
576        block_on(logger.log(&Temperature { celsius: 20.0 })).unwrap();
577        block_on(logger.log(&Temperature { celsius: 21.0 })).unwrap();
578        block_on(logger.log(&Temperature { celsius: 22.0 })).unwrap();
579        block_on(logger.sync()).unwrap();
580
581        // db() for non-flash reads
582        assert!(logger.sink().is_mounted());
583        assert_eq!(logger.sink().stats().total_entries, 3);
584
585        // db_mut() for async queries
586        let mut readings = alloc::vec::Vec::new();
587        block_on(
588            logger
589                .sink_mut()
590                .query_all_sensor::<Temperature, _>(|hdr, temp| {
591                    readings.push((hdr.timestamp, temp.celsius));
592                    true
593                }),
594        )
595        .unwrap();
596
597        assert_eq!(readings.len(), 3);
598        assert_eq!(readings[0], (100, 20.0));
599        assert_eq!(readings[1], (1100, 21.0));
600        assert_eq!(readings[2], (2100, 22.0));
601    }
602
603    #[test]
604    fn async_into_inner_returns_db_and_clock() {
605        let logger = make_async_logger(0);
606        let (db, clock) = logger.into_inner();
607        assert!(db.is_mounted());
608        assert_eq!(clock(), 0);
609    }
610}