sensor-db 0.1.0

Append-only sensor database for NOR flash on embedded devices
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
//! Convenience wrapper that injects timestamps from a user-provided clock.
//!
//! [`SensorLogger`] wraps anything that can take a sample — a
//! [`SensorDb`](crate::SensorDb), a [`TieredDb`](crate::TieredDb), or any other
//! [`LogSink`] — together with a clock function, eliminating the need to pass a
//! timestamp on every append call.
//!
//! # Example
//!
//! ```ignore
//! use sensor_db::{SensorDb, SensorLogger};
//!
//! let db: SensorDb<_, 256, 32> = SensorDb::new(flash, 0, 32, 2)?;
//! let mut logger = SensorLogger::new(db, || get_timestamp_us());
//!
//! logger.log(&Temperature { celsius: 25.5 })?;
//! logger.sync()?;
//! ```
//!
//! The same wrapper over a tier, so a card can come and go beneath it:
//!
//! ```ignore
//! let mut logger = SensorLogger::new(tiered, || get_timestamp_us());
//! logger.log(&Temperature { celsius: 25.5 })?;
//! ```

use crate::error::Error;
use crate::port::{LogSink, LogSinkAsync, LogSinkAsyncExt, LogSinkExt};
use crate::typed::SensorData;
use zerocopy::{Immutable, IntoBytes};

/// A convenience wrapper around a [`LogSink`] that automatically timestamps entries.
///
/// The `Clock` parameter is any `Fn() -> u64` that returns the current timestamp
/// (typically microseconds since epoch). This avoids threading a timestamp through
/// every call site.
///
/// For query and read access, use [`sink()`](SensorLogger::sink) or
/// [`sink_mut()`](SensorLogger::sink_mut) to reach the wrapped log — the logger
/// deliberately exposes no reads of its own, so nothing here has to be
/// duplicated when the log underneath changes.
pub struct SensorLogger<L, Clock>
where
    Clock: Fn() -> u64,
{
    sink: L,
    clock: Clock,
}

impl<L, Clock> SensorLogger<L, Clock>
where
    L: LogSink,
    Clock: Fn() -> u64,
{
    /// Create a new `SensorLogger` wrapping an existing log.
    ///
    /// # Arguments
    /// - `sink`: A mounted (or freshly formatted) log
    /// - `clock`: Function returning the current timestamp as `u64`
    pub fn new(sink: L, clock: Clock) -> Self {
        Self { sink, clock }
    }

    /// Log a typed sensor reading with an auto-generated timestamp.
    ///
    /// The sensor ID is derived from `T::SENSOR_ID`.
    pub fn log<T: SensorData>(&mut self, data: &T) -> Result<(), Error> {
        let ts = (self.clock)();
        self.sink.append_sensor(ts, data)
    }

    /// Log a raw payload with an auto-generated timestamp.
    ///
    /// # Arguments
    /// - `sensor_id`: Sensor identifier
    /// - `payload`: Raw sensor data bytes
    pub fn log_raw(&mut self, sensor_id: u16, payload: &[u8]) -> Result<(), Error> {
        let ts = (self.clock)();
        self.sink.append(sensor_id, ts, payload)
    }

    /// Log a typed value with an explicit sensor ID and auto-generated timestamp.
    ///
    /// This is the Layer 1 equivalent — you provide the sensor ID, the clock
    /// provides the timestamp.
    pub fn log_value<T: IntoBytes + Immutable>(
        &mut self,
        sensor_id: u16,
        data: &T,
    ) -> Result<(), Error> {
        let ts = (self.clock)();
        self.sink.append_value(sensor_id, ts, data)
    }

    /// Flush the page buffer to flash.
    ///
    /// Delegates to [`LogSink::sync`].
    pub fn sync(&mut self) -> Result<(), Error> {
        self.sink.sync()
    }

    /// Immutable access to the wrapped log.
    ///
    /// Enough for the accessors that touch no flash —
    /// [`stats`](crate::SensorDb::stats), `is_mounted`, `spool_stats` and the
    /// rest. Reads and writes both go through
    /// [`sink_mut()`](Self::sink_mut), because reading flash is a `&mut`
    /// operation.
    pub fn sink(&self) -> &L {
        &self.sink
    }

    /// Mutable access to the wrapped log, for writes and queries.
    pub fn sink_mut(&mut self) -> &mut L {
        &mut self.sink
    }

    /// Consume the logger and return the wrapped log and clock.
    pub fn into_inner(self) -> (L, Clock) {
        (self.sink, self.clock)
    }
}

// ---------------------------------------------------------------------------
// Async logger
// ---------------------------------------------------------------------------

/// Async version of [`SensorLogger`], wrapping any [`LogSinkAsync`].
///
/// All logging methods are `async fn` and take `&mut self`. For query access,
/// use [`sink_mut()`](SensorLoggerAsync::sink_mut) to reach the wrapped log.
///
/// # Example
///
/// ```ignore
/// use sensor_db::{SensorDbAsync, SensorLoggerAsync};
///
/// let db: SensorDbAsync<_, 256, 32> = SensorDbAsync::new(flash, 0, 32, 2)?;
/// let mut logger = SensorLoggerAsync::new(db, || get_timestamp_us());
///
/// logger.log(&Temperature { celsius: 25.5 }).await?;
/// logger.sync().await?;
/// ```
pub struct SensorLoggerAsync<L, Clock>
where
    Clock: Fn() -> u64,
{
    sink: L,
    clock: Clock,
}

impl<L, Clock> SensorLoggerAsync<L, Clock>
where
    L: LogSinkAsync,
    Clock: Fn() -> u64,
{
    /// Create a new `SensorLoggerAsync` wrapping an existing log.
    ///
    /// # Arguments
    /// - `sink`: A mounted (or freshly formatted) async log
    /// - `clock`: Function returning the current timestamp as `u64`
    pub fn new(sink: L, clock: Clock) -> Self {
        Self { sink, clock }
    }

    /// Log a typed sensor reading with an auto-generated timestamp.
    ///
    /// The sensor ID is derived from `T::SENSOR_ID`.
    pub async fn log<T: SensorData>(&mut self, data: &T) -> Result<(), Error> {
        let ts = (self.clock)();
        self.sink.append_sensor(ts, data).await
    }

    /// Log a raw payload with an auto-generated timestamp.
    ///
    /// # Arguments
    /// - `sensor_id`: Sensor identifier
    /// - `payload`: Raw sensor data bytes
    pub async fn log_raw(&mut self, sensor_id: u16, payload: &[u8]) -> Result<(), Error> {
        let ts = (self.clock)();
        self.sink.append(sensor_id, ts, payload).await
    }

    /// Log a typed value with an explicit sensor ID and auto-generated timestamp.
    ///
    /// This is the Layer 1 equivalent — you provide the sensor ID, the clock
    /// provides the timestamp.
    pub async fn log_value<T: IntoBytes + Immutable>(
        &mut self,
        sensor_id: u16,
        data: &T,
    ) -> Result<(), Error> {
        let ts = (self.clock)();
        self.sink.append_value(sensor_id, ts, data).await
    }

    /// Flush the page buffer to flash.
    ///
    /// Delegates to [`LogSinkAsync::sync`].
    pub async fn sync(&mut self) -> Result<(), Error> {
        self.sink.sync().await
    }

    /// Mutable access to the wrapped log.
    ///
    /// Every async read takes `&mut self`, so this is the accessor to reach for
    /// — unlike the blocking logger, where [`sink()`](Self::sink) covers reads.
    pub fn sink_mut(&mut self) -> &mut L {
        &mut self.sink
    }

    /// Immutable access to the wrapped log.
    ///
    /// Only useful for non-flash methods like `stats()`, `is_mounted()`,
    /// and `max_payload_size()`.
    pub fn sink(&self) -> &L {
        &self.sink
    }

    /// Consume the logger and return the wrapped log and clock.
    pub fn into_inner(self) -> (L, Clock) {
        (self.sink, self.clock)
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(all(test, feature = "std"))]
mod tests {
    extern crate alloc;

    use super::*;
    use crate::db::SensorDb;
    use crate::mock::MockFlash;
    use core::cell::Cell;
    use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};

    const PAGE: usize = 256;
    const SECTOR: usize = 4096;
    const SECTORS: usize = 8;

    type Db = SensorDb<MockFlash<PAGE, SECTOR>, PAGE, SECTORS>;

    #[derive(Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable)]
    #[repr(C)]
    struct Temperature {
        celsius: f32,
    }

    impl SensorData for Temperature {
        const SENSOR_ID: u16 = 0x01;
    }

    fn make_logger(start: u64) -> SensorLogger<Db, impl Fn() -> u64> {
        let flash = MockFlash::<PAGE, SECTOR>::new(SECTORS * SECTOR);
        let mut db = SensorDb::new(flash, 0, SECTORS as u16, 1).unwrap();
        db.format().unwrap();

        let counter = Cell::new(start);
        SensorLogger::new(db, move || {
            let ts = counter.get();
            counter.set(ts + 1000);
            ts
        })
    }

    #[test]
    fn log_and_retrieve() {
        let mut logger = make_logger(1000);

        logger.log(&Temperature { celsius: 25.5 }).unwrap();
        logger.sync().unwrap();

        let (hdr, temp) = logger
            .sink_mut()
            .latest_sensor::<Temperature>()
            .unwrap()
            .unwrap();
        assert_eq!(hdr.timestamp, 1000);
        assert_eq!(temp.celsius, 25.5);
    }

    #[test]
    fn log_raw_and_retrieve() {
        let mut logger = make_logger(5000);

        logger.log_raw(0x42, &[0xDE, 0xAD]).unwrap();
        logger.sync().unwrap();

        let mut buf = [0u8; 16];
        let (hdr, n) = logger.sink_mut().latest(0x42, &mut buf).unwrap().unwrap();
        assert_eq!(hdr.timestamp, 5000);
        assert_eq!(&buf[..n], &[0xDE, 0xAD]);
    }

    #[test]
    fn multiple_logs_increment_timestamp() {
        let mut logger = make_logger(0);

        for i in 0..5 {
            logger
                .log(&Temperature {
                    celsius: i as f32 * 10.0,
                })
                .unwrap();
        }
        logger.sync().unwrap();

        // Latest should have timestamp = 4000 (0, 1000, 2000, 3000, 4000)
        let (hdr, temp) = logger
            .sink_mut()
            .latest_sensor::<Temperature>()
            .unwrap()
            .unwrap();
        assert_eq!(hdr.timestamp, 4000);
        assert_eq!(temp.celsius, 40.0);

        assert_eq!(
            logger
                .sink_mut()
                .count(Some(Temperature::SENSOR_ID))
                .unwrap(),
            5
        );
    }

    #[test]
    fn db_access_for_queries() {
        let mut logger = make_logger(100);

        logger.log(&Temperature { celsius: 20.0 }).unwrap();
        logger.log(&Temperature { celsius: 21.0 }).unwrap();
        logger.log(&Temperature { celsius: 22.0 }).unwrap();
        logger.sync().unwrap();

        // Use db() for non-mutating checks and reads
        assert!(logger.sink().is_mounted());
        assert_eq!(logger.sink().stats().total_entries, 3);

        // Use db_mut() for callback-based queries
        let mut readings = alloc::vec::Vec::new();
        logger
            .sink_mut()
            .query_all_sensor::<Temperature, _>(|hdr, temp| {
                readings.push((hdr.timestamp, temp.celsius));
                true
            })
            .unwrap();

        assert_eq!(readings.len(), 3);
        assert_eq!(readings[0], (100, 20.0));
        assert_eq!(readings[1], (1100, 21.0));
        assert_eq!(readings[2], (2100, 22.0));
    }

    #[test]
    fn into_inner_returns_db_and_clock() {
        let logger = make_logger(0);
        let (db, clock) = logger.into_inner();
        assert!(db.is_mounted());
        // Clock still works
        assert_eq!(clock(), 0);
    }

    #[test]
    fn logger_db_immutable_reads() {
        let mut logger = make_logger(1000);

        logger.log(&Temperature { celsius: 20.0 }).unwrap();
        logger.log(&Temperature { celsius: 25.0 }).unwrap();
        logger.log(&Temperature { celsius: 30.0 }).unwrap();
        logger.sync().unwrap();

        // All read methods work through db() (immutable reference)
        let (hdr, temp) = logger
            .sink_mut()
            .latest_sensor::<Temperature>()
            .unwrap()
            .unwrap();
        assert_eq!(hdr.timestamp, 3000);
        assert_eq!(temp.celsius, 30.0);

        let (hdr, temp) = logger
            .sink_mut()
            .oldest_sensor::<Temperature>()
            .unwrap()
            .unwrap();
        assert_eq!(hdr.timestamp, 1000);
        assert_eq!(temp.celsius, 20.0);

        assert_eq!(logger.sink_mut().count_sensor::<Temperature>().unwrap(), 3);
        assert_eq!(logger.sink_mut().count(None).unwrap(), 3);
    }
}

#[cfg(all(test, feature = "std", feature = "async"))]
mod async_tests {
    extern crate alloc;

    use super::*;
    use crate::async_db::SensorDbAsync;
    use crate::mock::MockFlash;
    use core::cell::Cell;
    use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};

    const PAGE: usize = 256;
    const SECTOR: usize = 4096;
    const SECTORS: usize = 8;

    #[derive(Debug, Clone, Copy, PartialEq, FromBytes, IntoBytes, KnownLayout, Immutable)]
    #[repr(C)]
    struct Temperature {
        celsius: f32,
    }

    impl SensorData for Temperature {
        const SENSOR_ID: u16 = 0x01;
    }

    // -- MockFlashAsync adapter (same pattern as async_db tests) -----------

    struct MockFlashAsync<const P: usize, const S: usize> {
        inner: MockFlash<P, S>,
    }

    impl<const P: usize, const S: usize> MockFlashAsync<P, S> {
        fn new(size: usize) -> Self {
            Self {
                inner: MockFlash::<P, S>::new(size),
            }
        }
    }

    impl<const P: usize, const S: usize> embedded_storage_async::nor_flash::ErrorType
        for MockFlashAsync<P, S>
    {
        type Error = crate::mock::MockFlashError;
    }

    impl<const P: usize, const S: usize> embedded_storage_async::nor_flash::ReadNorFlash
        for MockFlashAsync<P, S>
    {
        const READ_SIZE: usize = 1;
        async fn read(&mut self, offset: u32, buf: &mut [u8]) -> Result<(), Self::Error> {
            use embedded_storage::nor_flash::ReadNorFlash;
            self.inner.read(offset, buf)
        }
        fn capacity(&self) -> usize {
            use embedded_storage::nor_flash::ReadNorFlash;
            self.inner.capacity()
        }
    }

    impl<const P: usize, const S: usize> embedded_storage_async::nor_flash::NorFlash
        for MockFlashAsync<P, S>
    {
        const WRITE_SIZE: usize = P;
        const ERASE_SIZE: usize = S;
        async fn erase(&mut self, from: u32, to: u32) -> Result<(), Self::Error> {
            use embedded_storage::nor_flash::NorFlash;
            self.inner.erase(from, to)
        }
        async fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> {
            use embedded_storage::nor_flash::NorFlash;
            self.inner.write(offset, bytes)
        }
    }

    // -- Minimal block_on --------------------------------------------------

    #[allow(unsafe_code, clippy::never_loop)]
    fn block_on<T>(fut: impl core::future::Future<Output = T>) -> T {
        use core::pin::pin;
        use core::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};

        fn dummy_raw_waker() -> RawWaker {
            fn no_op(_: *const ()) {}
            fn clone(data: *const ()) -> RawWaker {
                RawWaker::new(data, &VTABLE)
            }
            const VTABLE: RawWakerVTable = RawWakerVTable::new(clone, no_op, no_op, no_op);
            RawWaker::new(core::ptr::null(), &VTABLE)
        }

        let waker = unsafe { Waker::from_raw(dummy_raw_waker()) };
        let mut cx = Context::from_waker(&waker);
        let mut fut = pin!(fut);

        loop {
            match fut.as_mut().poll(&mut cx) {
                Poll::Ready(val) => return val,
                Poll::Pending => panic!("async operation returned Pending in sync mock"),
            }
        }
    }

    // -- Helpers -----------------------------------------------------------

    fn make_async_logger(
        start: u64,
    ) -> SensorLoggerAsync<
        SensorDbAsync<MockFlashAsync<PAGE, SECTOR>, PAGE, SECTORS>,
        impl Fn() -> u64,
    > {
        let flash = MockFlashAsync::<PAGE, SECTOR>::new(SECTORS * SECTOR);
        let mut db = SensorDbAsync::new(flash, 0, SECTORS as u16, 1).unwrap();
        block_on(db.format()).unwrap();

        let counter = Cell::new(start);
        SensorLoggerAsync::new(db, move || {
            let ts = counter.get();
            counter.set(ts + 1000);
            ts
        })
    }

    #[test]
    fn async_log_and_retrieve() {
        let mut logger = make_async_logger(1000);

        block_on(logger.log(&Temperature { celsius: 25.5 })).unwrap();
        block_on(logger.sync()).unwrap();

        let (hdr, temp) = block_on(logger.sink_mut().latest_sensor::<Temperature>())
            .unwrap()
            .unwrap();
        assert_eq!(hdr.timestamp, 1000);
        assert_eq!(temp.celsius, 25.5);
    }

    #[test]
    fn async_log_raw_and_retrieve() {
        let mut logger = make_async_logger(5000);

        block_on(logger.log_raw(0x42, &[0xDE, 0xAD])).unwrap();
        block_on(logger.sync()).unwrap();

        let mut buf = [0u8; 16];
        let (hdr, n) = block_on(logger.sink_mut().latest(0x42, &mut buf))
            .unwrap()
            .unwrap();
        assert_eq!(hdr.timestamp, 5000);
        assert_eq!(&buf[..n], &[0xDE, 0xAD]);
    }

    #[test]
    fn async_multiple_logs_increment_timestamp() {
        let mut logger = make_async_logger(0);

        for i in 0..5 {
            block_on(logger.log(&Temperature {
                celsius: i as f32 * 10.0,
            }))
            .unwrap();
        }
        block_on(logger.sync()).unwrap();

        let (hdr, temp) = block_on(logger.sink_mut().latest_sensor::<Temperature>())
            .unwrap()
            .unwrap();
        assert_eq!(hdr.timestamp, 4000);
        assert_eq!(temp.celsius, 40.0);

        assert_eq!(
            block_on(logger.sink_mut().count(Some(Temperature::SENSOR_ID))).unwrap(),
            5
        );
    }

    #[test]
    fn async_db_access() {
        let mut logger = make_async_logger(100);

        block_on(logger.log(&Temperature { celsius: 20.0 })).unwrap();
        block_on(logger.log(&Temperature { celsius: 21.0 })).unwrap();
        block_on(logger.log(&Temperature { celsius: 22.0 })).unwrap();
        block_on(logger.sync()).unwrap();

        // db() for non-flash reads
        assert!(logger.sink().is_mounted());
        assert_eq!(logger.sink().stats().total_entries, 3);

        // db_mut() for async queries
        let mut readings = alloc::vec::Vec::new();
        block_on(
            logger
                .sink_mut()
                .query_all_sensor::<Temperature, _>(|hdr, temp| {
                    readings.push((hdr.timestamp, temp.celsius));
                    true
                }),
        )
        .unwrap();

        assert_eq!(readings.len(), 3);
        assert_eq!(readings[0], (100, 20.0));
        assert_eq!(readings[1], (1100, 21.0));
        assert_eq!(readings[2], (2100, 22.0));
    }

    #[test]
    fn async_into_inner_returns_db_and_clock() {
        let logger = make_async_logger(0);
        let (db, clock) = logger.into_inner();
        assert!(db.is_mounted());
        assert_eq!(clock(), 0);
    }
}