ph-veml7700-als 0.1.0-incubating.1

Async no_std VEML7700 ambient-light driver with explicit one-shot and threshold-monitor semantics
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
//! Configuration-register value types and codec.

/// Driver gain-codec reaction to `S-14`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Gain {
    /// Gain ×1.
    X1,
    /// Gain ×2.
    X2,
    /// Gain ×1/8.
    Div8,
    /// Gain ×1/4.
    Div4,
}

impl Gain {
    pub(crate) const fn bits(self) -> u16 {
        match self {
            Self::X1 => 0b00 << 11,
            Self::X2 => 0b01 << 11,
            Self::Div8 => 0b10 << 11,
            Self::Div4 => 0b11 << 11,
        }
    }

    pub(crate) const fn from_bits(bits: u16) -> Self {
        match (bits >> 11) & 0b11 {
            0b00 => Self::X1,
            0b01 => Self::X2,
            0b10 => Self::Div8,
            _ => Self::Div4,
        }
    }
}

/// Driver integration-codec reaction to `S-15`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum IntegrationTime {
    /// 25 ms.
    Ms25,
    /// 50 ms.
    Ms50,
    /// 100 ms.
    Ms100,
    /// 200 ms.
    Ms200,
    /// 400 ms.
    Ms400,
    /// 800 ms.
    Ms800,
}

impl IntegrationTime {
    /// Return the nominal integration time in milliseconds.
    pub const fn milliseconds(self) -> u32 {
        match self {
            Self::Ms25 => 25,
            Self::Ms50 => 50,
            Self::Ms100 => 100,
            Self::Ms200 => 200,
            Self::Ms400 => 400,
            Self::Ms800 => 800,
        }
    }

    pub(crate) const fn bits(self) -> u16 {
        match self {
            Self::Ms25 => 0b1100 << 6,
            Self::Ms50 => 0b1000 << 6,
            Self::Ms100 => 0b0000 << 6,
            Self::Ms200 => 0b0001 << 6,
            Self::Ms400 => 0b0010 << 6,
            Self::Ms800 => 0b0011 << 6,
        }
    }

    pub(crate) const fn from_bits(bits: u16) -> Result<Self, ConfigDecodeError> {
        match (bits >> 6) & 0b1111 {
            0b1100 => Ok(Self::Ms25),
            0b1000 => Ok(Self::Ms50),
            0b0000 => Ok(Self::Ms100),
            0b0001 => Ok(Self::Ms200),
            0b0010 => Ok(Self::Ms400),
            0b0011 => Ok(Self::Ms800),
            observed => Err(ConfigDecodeError::ReservedIntegrationTime { observed }),
        }
    }
}

/// Threshold persistence protect number (`ALS_PERS`).
///
/// # What this selects, and what it does not promise
///
/// The driver programs the four persistence encodings recorded by `S-16`.
/// `S-39`, `S-49`, and `S-50` leave the assertion rule incomplete.
///
/// This driver therefore promises nothing about *when*
/// [`read_threshold_status`](crate::Veml7700::read_threshold_status) will report
/// a flag for any persistence value.
///
/// Poll the status. Do not compute an expected assertion time from the count and
/// refresh cadence. The driver stays silent rather than supplying the two
/// missing propositions.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Persistence {
    /// Protect number 1 (encoded count 1).
    One,
    /// Protect number 2.
    Two,
    /// Protect number 4.
    Four,
    /// Protect number 8.
    Eight,
}

impl Persistence {
    /// Return the programmed protect number.
    ///
    /// This is the encoded field value, not an input to any timing calculation
    /// the driver performs — nothing in this driver reads it.
    pub const fn count(self) -> u8 {
        match self {
            Self::One => 1,
            Self::Two => 2,
            Self::Four => 4,
            Self::Eight => 8,
        }
    }

    pub(crate) const fn bits(self) -> u16 {
        match self {
            Self::One => 0b00 << 4,
            Self::Two => 0b01 << 4,
            Self::Four => 0b10 << 4,
            Self::Eight => 0b11 << 4,
        }
    }

    pub(crate) const fn from_bits(bits: u16) -> Self {
        match (bits >> 4) & 0b11 {
            0b00 => Self::One,
            0b01 => Self::Two,
            0b10 => Self::Four,
            _ => Self::Eight,
        }
    }
}

/// Driver power-state codec reaction to `S-17`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum PowerState {
    /// Conversions are enabled.
    Active,
    /// Conversion circuitry is shut down; the driver treats data retention as
    /// the separate consequence of `S-25`.
    Shutdown,
}

impl PowerState {
    pub(crate) const fn bit(self) -> u16 {
        match self {
            Self::Active => 0,
            Self::Shutdown => 1,
        }
    }

    pub(crate) const fn from_word(word: u16) -> Self {
        if word & 1 == 0 {
            Self::Active
        } else {
            Self::Shutdown
        }
    }
}

/// Driver monitor-enable codec reaction to `S-17`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum ThresholdMonitorState {
    /// Threshold monitoring is disabled.
    Disabled,
    /// Threshold monitoring is enabled; this driver exposes status only by
    /// polling (`S-41`).
    Enabled,
}

impl ThresholdMonitorState {
    pub(crate) const fn bit(self) -> u16 {
        match self {
            Self::Disabled => 0,
            Self::Enabled => 1 << 1,
        }
    }

    pub(crate) const fn from_word(word: u16) -> Self {
        if word & (1 << 1) == 0 {
            Self::Disabled
        } else {
            Self::Enabled
        }
    }
}

/// Gain and integration-time pair defining one measurement domain.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct MeasurementConfig {
    gain: Gain,
    integration_time: IntegrationTime,
}

impl MeasurementConfig {
    /// Construct a measurement configuration.
    pub const fn new(gain: Gain, integration_time: IntegrationTime) -> Self {
        Self {
            gain,
            integration_time,
        }
    }

    /// Driver decoding of the reset-domain measurement fields (`S-12`, `S-14`,
    /// `S-15`), not a recommendation.
    pub const fn silicon_reset_default() -> Self {
        Self::new(Gain::X1, IntegrationTime::Ms100)
    }

    /// Driver starting policy for unknown brightness (`S-28`, `S-34`).
    pub const fn maximum_range_start() -> Self {
        Self::new(Gain::Div8, IntegrationTime::Ms25)
    }

    /// Return the selected gain.
    pub const fn gain(self) -> Gain {
        self.gain
    }

    /// Return the selected integration time.
    pub const fn integration_time(self) -> IntegrationTime {
        self.integration_time
    }

    pub(crate) const fn bits(self) -> u16 {
        self.gain.bits() | self.integration_time.bits()
    }
}

impl Default for MeasurementConfig {
    /// This crate's software policy, **not** the device's reset state.
    ///
    /// Returns [`maximum_range_start`](Self::maximum_range_start), the driver's
    /// `S-28`/`S-34` starting policy. A maximum raw code remains ambiguous
    /// (`S-51`, `S-52`), so
    /// [`AlsCounts::is_max_code`](crate::AlsCounts::is_max_code) must be
    /// checked regardless of configuration. The device's own reset domain is
    /// [`silicon_reset_default`](Self::silicon_reset_default) and is different —
    /// a caller who wants what the hardware powers up in must ask for it by
    /// name.
    ///
    /// The two are deliberately distinct. Conflating them is how a caller ends
    /// up believing `Default` describes the device.
    fn default() -> Self {
        Self::maximum_range_start()
    }
}

/// Decoded configuration-register snapshot.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct ConfigurationSnapshot {
    /// Observed measurement domain.
    pub measurement: MeasurementConfig,
    /// Observed threshold persistence.
    pub persistence: Persistence,
    /// Observed threshold-monitor enable state.
    pub threshold_monitor: ThresholdMonitorState,
    /// Observed sensor power state.
    pub power_state: PowerState,
}

impl ConfigurationSnapshot {
    /// Return the documented reset value decoded as a snapshot.
    pub const fn silicon_reset_default() -> Self {
        Self {
            measurement: MeasurementConfig::silicon_reset_default(),
            persistence: Persistence::One,
            threshold_monitor: ThresholdMonitorState::Disabled,
            power_state: PowerState::Shutdown,
        }
    }

    pub(crate) const fn encode(self) -> u16 {
        self.measurement.bits()
            | self.persistence.bits()
            | self.threshold_monitor.bit()
            | self.power_state.bit()
    }

    pub(crate) const fn with_measurement(mut self, measurement: MeasurementConfig) -> Self {
        self.measurement = measurement;
        self
    }

    pub(crate) const fn with_persistence(mut self, persistence: Persistence) -> Self {
        self.persistence = persistence;
        self
    }

    pub(crate) const fn with_monitor(mut self, state: ThresholdMonitorState) -> Self {
        self.threshold_monitor = state;
        self
    }

    pub(crate) const fn with_power_state(mut self, state: PowerState) -> Self {
        self.power_state = state;
        self
    }
}

/// Failure decoding a configuration register.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[non_exhaustive]
pub enum ConfigDecodeError {
    /// A reserved bit was observed set.
    ReservedBits {
        /// Reserved bits that were observed set.
        observed: u16,
    },
    /// An undocumented integration-time encoding was observed.
    ReservedIntegrationTime {
        /// Undocumented integration-time field value.
        observed: u16,
    },
}

pub(crate) struct ConfigWord(u16);

impl ConfigWord {
    pub(crate) const fn from_raw(raw: u16) -> Self {
        Self(raw)
    }

    pub(crate) const fn from_snapshot(snapshot: ConfigurationSnapshot) -> Self {
        Self(snapshot.encode())
    }

    pub(crate) const fn raw(self) -> u16 {
        self.0
    }

    pub(crate) fn decode(self) -> Result<ConfigurationSnapshot, ConfigDecodeError> {
        // Driver reserved-field reaction to `S-13` and `S-18`.
        let reserved = self.0 & 0b1110_0100_0000_1100;
        if reserved != 0 {
            return Err(ConfigDecodeError::ReservedBits { observed: reserved });
        }
        Ok(ConfigurationSnapshot {
            measurement: MeasurementConfig::new(
                Gain::from_bits(self.0),
                IntegrationTime::from_bits(self.0)?,
            ),
            persistence: Persistence::from_bits(self.0),
            threshold_monitor: ThresholdMonitorState::from_word(self.0),
            power_state: PowerState::from_word(self.0),
        })
    }
}

impl core::fmt::Display for ConfigDecodeError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::ReservedBits { observed } => {
                write!(f, "reserved configuration bits were set: {observed:#06x}")
            }
            Self::ReservedIntegrationTime { observed } => {
                write!(f, "undocumented integration-time encoding {observed:#06b}")
            }
        }
    }
}

impl core::error::Error for ConfigDecodeError {}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn reset_word_decodes() {
        assert_eq!(
            ConfigWord(0x0001).decode(),
            Ok(ConfigurationSnapshot::silicon_reset_default())
        );
    }

    /// Literal words from `docs/HARDWARE_CONTRACT.md` `S-12` / `S-14` / `S-15`, not round trips.
    ///
    /// The exhaustive round-trip test below proves the encoder and decoder agree
    /// with each other. It cannot detect them agreeing on the *wrong* bit
    /// position: shift both fields by one and every round trip still passes.
    /// These vectors are the only tests here that would fail.
    ///
    /// Each field is placed alone so a failure names the field rather than the
    /// word. The encodings deliberately include the two cases where bit order
    /// and magnitude order disagree — gain `10` is ×1/8 while `11` is ×1/4, and
    /// integration `1100` is the *shortest* time — because a plausible-looking
    /// table sorted by magnitude would encode both backwards.
    #[test]
    fn configuration_fields_occupy_the_contract_bit_positions() {
        let base = ConfigurationSnapshot {
            measurement: MeasurementConfig::new(Gain::X1, IntegrationTime::Ms100),
            persistence: Persistence::One,
            threshold_monitor: ThresholdMonitorState::Disabled,
            power_state: PowerState::Active,
        };
        // Every field at its zero encoding is the all-zero word.
        assert_eq!(base.encode(), 0x0000);

        // Gain, bits 12:11.
        for (gain, bits) in [
            (Gain::X1, 0b00_u16),
            (Gain::X2, 0b01),
            (Gain::Div8, 0b10),
            (Gain::Div4, 0b11),
        ] {
            let word = ConfigurationSnapshot {
                measurement: MeasurementConfig::new(gain, IntegrationTime::Ms100),
                ..base
            }
            .encode();
            assert_eq!(word, bits << 11, "gain {gain:?} must occupy bits 12:11");
        }

        // Integration time, bits 9:6.
        for (integration_time, bits) in [
            (IntegrationTime::Ms25, 0b1100_u16),
            (IntegrationTime::Ms50, 0b1000),
            (IntegrationTime::Ms100, 0b0000),
            (IntegrationTime::Ms200, 0b0001),
            (IntegrationTime::Ms400, 0b0010),
            (IntegrationTime::Ms800, 0b0011),
        ] {
            let word = ConfigurationSnapshot {
                measurement: MeasurementConfig::new(Gain::X1, integration_time),
                ..base
            }
            .encode();
            assert_eq!(
                word,
                bits << 6,
                "integration time {integration_time:?} must occupy bits 9:6"
            );
        }

        // Persistence, bits 5:4.
        for (persistence, bits) in [
            (Persistence::One, 0b00_u16),
            (Persistence::Two, 0b01),
            (Persistence::Four, 0b10),
            (Persistence::Eight, 0b11),
        ] {
            let word = ConfigurationSnapshot {
                persistence,
                ..base
            }
            .encode();
            assert_eq!(
                word,
                bits << 4,
                "persistence {persistence:?} must occupy bits 5:4"
            );
        }

        // Monitor enable is bit 1; shutdown is bit 0.
        assert_eq!(
            ConfigurationSnapshot {
                threshold_monitor: ThresholdMonitorState::Enabled,
                ..base
            }
            .encode(),
            1 << 1
        );
        assert_eq!(
            ConfigurationSnapshot {
                power_state: PowerState::Shutdown,
                ..base
            }
            .encode(),
            1 << 0
        );

        // One word carrying every field at once, decoded back. ×1/4 gain,
        // 800 ms, persistence 8, monitor enabled, shut down:
        // 0b0001_1000_1111_0011.
        let combined = (0b11 << 11) | (0b0011 << 6) | (0b11 << 4) | (1 << 1) | 1;
        assert_eq!(combined, 0x18F3);
        assert_eq!(
            ConfigWord(combined).decode(),
            Ok(ConfigurationSnapshot {
                measurement: MeasurementConfig::new(Gain::Div4, IntegrationTime::Ms800),
                persistence: Persistence::Eight,
                threshold_monitor: ThresholdMonitorState::Enabled,
                power_state: PowerState::Shutdown,
            })
        );
    }

    #[test]
    fn every_documented_configuration_field_combination_round_trips() {
        let gains = [Gain::X1, Gain::X2, Gain::Div8, Gain::Div4];
        let times = [
            IntegrationTime::Ms25,
            IntegrationTime::Ms50,
            IntegrationTime::Ms100,
            IntegrationTime::Ms200,
            IntegrationTime::Ms400,
            IntegrationTime::Ms800,
        ];
        let persistence_values = [
            Persistence::One,
            Persistence::Two,
            Persistence::Four,
            Persistence::Eight,
        ];
        let monitor_states = [
            ThresholdMonitorState::Disabled,
            ThresholdMonitorState::Enabled,
        ];
        let power_states = [PowerState::Active, PowerState::Shutdown];

        for gain in gains {
            for integration_time in times {
                for persistence in persistence_values {
                    for threshold_monitor in monitor_states {
                        for power_state in power_states {
                            let expected = ConfigurationSnapshot {
                                measurement: MeasurementConfig::new(gain, integration_time),
                                persistence,
                                threshold_monitor,
                                power_state,
                            };
                            assert_eq!(ConfigWord(expected.encode()).decode(), Ok(expected));
                        }
                    }
                }
            }
        }
    }

    #[test]
    fn every_reserved_configuration_bit_is_rejected() {
        for bit in [2_u32, 3, 10, 13, 14, 15] {
            let raw = 1_u16 << bit;
            assert_eq!(
                ConfigWord(raw).decode(),
                Err(ConfigDecodeError::ReservedBits { observed: raw })
            );
        }
    }

    #[test]
    fn every_reserved_integration_encoding_is_rejected() {
        for observed in [4_u16, 5, 6, 7, 9, 10, 11, 13, 14, 15] {
            assert_eq!(
                ConfigWord(observed << 6).decode(),
                Err(ConfigDecodeError::ReservedIntegrationTime { observed })
            );
        }
    }

    #[test]
    fn public_configuration_accessors_match_the_selected_domain() {
        let config = MeasurementConfig::new(Gain::X2, IntegrationTime::Ms800);
        assert_eq!(config.gain(), Gain::X2);
        assert_eq!(config.integration_time(), IntegrationTime::Ms800);
        assert_eq!(IntegrationTime::Ms25.milliseconds(), 25);
        assert_eq!(IntegrationTime::Ms800.milliseconds(), 800);
        assert_eq!(Persistence::One.count(), 1);
        assert_eq!(Persistence::Eight.count(), 8);
    }
}