rigless 0.2.1

Virtual hardware-in-the-loop runtime: run unmodified firmware on an emulated MCU with every peripheral, chip model and unit of virtual time in Rust, and a CPU core of its own that translates the firmware's instructions to host code
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
// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: MIT OR Apache-2.0
//! The DPS310, a barometric pressure sensor on an I2C bus: a measurement commanded or run in the
//! background, two raw words, and the calibration coefficients a driver turns them into a pressure
//! and a temperature with.
//!
//! Written against the Infineon DPS310 datasheet, document `V1.2`, 2020-10-15. Every section, table
//! and figure below is that document's.
//!
//! The chip does no compensation. It hands a driver two 24 bit words and the coefficients, and the
//! driver computes pressure and temperature from them by 4.9.1 and 4.9.2. The model holds a pressure
//! and a temperature instead, the signals a bench or a plant drives. At each measurement it runs those
//! formulas backwards with the chip's own coefficients, so what the driver computes is what the model
//! was told.
//!
//! **The measurements are derived from virtual time.** Nothing is scheduled. At each access, the
//! measurements that finished since the last one are counted from the instants the mode, the rates
//! and the precisions give, and the results land in the registers from the signals as held.
//!
//! **The coefficients are a stated choice.** The datasheet gives no example coefficients, and its
//! figure 6 is the flow and not a worked case. These are sized so the 24 bit words span the 300 to
//! 1200 hPa of table 3 and the temperatures of table 6 at every oversampling of table 9, which the
//! 8 times scale factor limits most, since the words there reach only a little past one unit of
//! `Praw_sc`. Both words fall as the quantity rises, so `c1` and `c10` are negative. A word is
//! 0.2 Pa at 16 times, the oversampling a driver runs, and 0.001 °C. A real part's differ, and
//! nothing a driver does depends on them but through the formulas.
//!
//! | Register or section | Behavior | Source | Test |
//! |---|---|---|---|
//! | The address | "0x77 (if SDO pin is left floating or pulled-up to VDDIO) or 0x76 (if the SDO pin is pulled-down to GND)", chosen by [`Sdo`] | 4.5, 6.1 | `it_answers_at_0x77_or_at_0x76_with_sdo_pulled_down` |
//! | The transfers | "incremental read (address is auto increment) and auto-incremental write is supported" in one access without a stop. The first byte after a write start is the register | 6.1 | `a_write_lands_in_one_register_and_a_read_walks_on` |
//! | `ID` | `REV_ID` 1 and `PROD_ID` 0, "Reset value 0x10" | 8.10, table 15 | `the_product_id_is_0x10` |
//! | Start-up | The chip answers no address in the first 2.5 ms, "No chip access". `SENSOR_RDY` is set at 12 ms and `COEF_RDY` at 40 ms, the maximums of table 8, from power-up or a soft reset. `MEAS_CFG` reads `0xC0` once both are set | 3.6 table 8, 4.3 figure 4, 8.5 | `nothing_answers_for_2_5_ms_and_the_ready_flags_rise_at_12_and_40` |
//! | The coefficients | `c0` to `c30` in registers `0x10` to `0x21` as table 18 packs them, "2's complement". `COEF_SRCE` bit 7 says the coefficients are from the external sensor. All read zero until `COEF_RDY` | 8.11, 8.12, table 18 | `the_coefficients_pack_as_table_18_does_and_the_driver_unpacks_them` |
//! | `PRS_CFG`, `TMP_CFG`, `CFG_REG` | Keep what is written, reset zero. `PM_RATE` and `TMP_RATE` are 1, 2, 4, 8, 16, 32, 64 and 128 measurements a second, and the precision code 0 to 7 is 1, 2, 4, 8, 16, 32, 64 and 128 times | 8.3, 8.4, 8.6 | `the_configuration_registers_keep_what_is_written` |
//! | Command mode | `MEAS_CTRL` 001 or 010 runs one pressure or temperature measurement, taking 3.6, 5.2, 8.4, 14.8, 27.6, 53.2, 104.4 or 206.8 ms by the precision. The temperature's is "similar". It sets `PRS_RDY` or `TMP_RDY` and "will return to Standby Mode when the measurement is finished", so `MEAS_CTRL` reads 000 | 4.1, 8.5, table 16 | `a_command_measurement_takes_its_oversampling_time_and_returns_to_standby` |
//! | Background mode | `MEAS_CTRL` 101, 110 and 111 measure pressure, temperature, or both, "continuously according to the selected measurement precision and rate. The temperature measurement is performed immediately after the pressure measurement". The first starts at the write | 4.1, 4.4 figure 5, 8.5 | `background_mode_measures_pressure_then_temperature_at_the_rate`, `stopping_background_mode_ends_the_measuring` |
//! | A rate past the limit | 4.4 limits the rates to "Ratetemperature*Timetemperature + Ratepressure*Timepressure< 1 second" and doesn't say what a setting past it does. The model runs one measurement at a time, the one that has been due longest first and pressure first on a tie, each as soon as it is due and the sensor is free | 4.4 | `a_rate_past_the_limit_runs_one_measurement_at_a_time` |
//! | A precision code with bit 3 set | "1xxx - Reserved". The measurement doesn't start | 8.3, 8.4 | `a_reserved_oversampling_code_starts_no_measurement` |
//! | The result registers | 24 bit two's complement, most significant byte first. A read doesn't change them. `PRS_RDY` and `TMP_RDY` are set by a finished measurement and "Cleared when" it "is read", which the model takes as a read of the last byte | 8.1, 8.2, 8.5, 4.7 | `a_result_stays_after_it_is_read_and_its_ready_flag_does_not` |
//! | The words | The pressure and temperature set are turned into the words the compensation formulas of 4.9.1 and 4.9.2 come back to, with `kP` and `kT` by the oversampling, table 9 | 4.9.1 to 4.9.3, table 9 | `the_raw_words_compensate_back_to_the_signals` |
//! | `RESET` | Writing `1001` to `SOFT_RST` "will run though the same sequences as in power-on reset": every register at its reset, no measurement, and the start-up again | 8.9, 3.6 | `a_soft_reset_restores_the_registers_and_starts_the_start_up_again` |
//! | Registers the datasheet doesn't list | The driver's fix for the temperature writes `0xA5` and `0x96` to `0x0E` and `0x0F`, `0x02` to `0x62`, then zero to `0x0E` and `0x0F`, as the Infineon library does. The writes are acknowledged and keep nothing, and the registers read zero | table 15 | `the_drivers_undocumented_writes_are_taken_and_change_nothing` |
//! | What it measures | A pressure in pascals and a temperature in hundredths of a degree, [`Dps310::set_pressure`] and [`Dps310::set_temperature`], taken at the access that finds the measurement finished | 4.9 | `the_raw_words_compensate_back_to_the_signals` |
//! | A driver's start and reads | ArduPilot's `AP_Baro_DPS280` as it runs a DPS310: the identity, the coefficients and their source, the configuration, the undocumented writes, then the ready flag and the six result bytes | 4.9, 8 | `ardupilot_starts_the_dps310_and_reads_pressure_and_temperature` |
//! | Determinism | The same accesses at the same instants give the same bytes, and a chip restored from its saved state goes on as the original does | Not a datasheet behavior | `the_same_accesses_give_the_same_bytes_and_a_restored_chip_goes_on_alike` |
//!
//! # What is not, and why
//!
//! | Departure | Reason |
//! |---|---|
//! | A signal changing during a measurement | A result is made at the access that finds it finished, from the signal held then, so the words don't average a change. A driver reading at its own rate can't tell |
//! | The FIFO: `FIFO_EN`, `FIFO_STS`, `FIFO_FLUSH` | Stored, and `FIFO_STS` reads its reset. 4.8 gives a 32 result FIFO that a driver can leave off, and ArduPilot does. With it off "reading the result register will not affect the register value", which is what the model does |
//! | Interrupts: `INT_STS`, `INT_HL`, `INT_FIFO`, `INT_TMP`, `INT_PRS` | Stored, and `INT_STS` reads zero. The interrupt is on the `SDO` pin, which a chip's seam doesn't carry back, and the driver polls `MEAS_CFG` |
//! | The SPI interface and `SPI_MODE` | The model is the I2C chip, which is the interface the board it is for uses. `SPI_MODE` is stored. Everything behind the interface would be shared by an SPI one |
//! | `T_SHIFT` and `P_SHIFT` | Stored. 4.9.3 says the result is shifted right in the data register above 8 times oversampling, and table 9's scale factors are for the word after the shift, so the model gives the word the factor expects. A word read with the bit missing is something the page doesn't describe |
//! | `TMP_EXT` against `TMP_COEF_SRCE` | Stored. 8.4 "highly recommended" the same sensor and doesn't say how a mismatch reads. The model gives the same temperature either way |
//! | A measurement started before `SENSOR_RDY` | 8.5 only "recommend not to start measurements" before. The model runs it |
//! | Stopping, or reconfiguring, in the middle of a measurement | The page says neither. A write of `MEAS_CTRL` that changes the mode drops the measurement under way and starts the new mode from that instant. A change to a rate or a precision applies from the next measurement that starts, and the one under way takes the scale factors the registers give when it finishes |
//! | Noise and accuracy | The precision in Pa RMS of tables 7 and 16 and the accuracies of table 7 are characteristics. A plant that wants noise drives the signals |
//! | `0x22` to `0x27` | Reserved, reset "XXh", read zero |
//! | The 3.4 MHz and 10 MHz clock ceilings | The seam carries bytes, not a clock |

use crate::chip::i2c::Peer;
use crate::chip::{Timeline, round};
use crate::snapshot::store;
use crate::time::VirtualNanos;

const PRS_B0: u8 = 0x02;
const TMP_B2: u8 = 0x03;
const TMP_B0: u8 = 0x05;
const PRS_CFG: u8 = 0x06;
const TMP_CFG: u8 = 0x07;
const MEAS_CFG: u8 = 0x08;
const CFG_REG: u8 = 0x09;
const RESET: u8 = 0x0C;
const ID: u8 = 0x0D;
const COEF: u8 = 0x10;
const COEF_END: u8 = 0x21;
const COEF_SRCE: u8 = 0x28;

// 8.10: `REV_ID` 1 and `PROD_ID` 0
const PRODUCT_ID: u8 = 0x10;
const COEF_RDY: u8 = 0x80;
const SENSOR_RDY: u8 = 0x40;
const TMP_RDY: u8 = 0x20;
const PRS_RDY: u8 = 0x10;
const MEAS_CTRL: u8 = 0x07;
// 8.5: `MEAS_CTRL` bit 2 is background mode and bits 1 and 0 are the temperature and the pressure
const BACKGROUND: u8 = 0x04;
const MEASURE_TEMPERATURE: u8 = 0x02;
const MEASURE_PRESSURE: u8 = 0x01;
// 8.3 and 8.4: the rate in bits 6:4 and the oversampling in bits 3:0, 1xxx of them reserved
const RATE: u8 = 0x70;
const RATE_SHIFT: u32 = 4;
const OVERSAMPLING: u8 = 0x0F;
const RESERVED_OVERSAMPLING: u8 = 0x08;
const SOFT_RST: u8 = 0x0F;
const SOFT_RESET: u8 = 0b1001;
// 8.12: the coefficients are from the external sensor, which is a choice, since the page says `XXh`
const TMP_COEF_SRCE: u8 = 0x80;

// 4.3 figure 4 and 3.6 table 8: when the chip first answers, when `SENSOR_RDY` rises and when `COEF_RDY` does
const ANSWERS_FROM: u64 = 2_500_000;
const SENSOR_READY_AT: u64 = 12_000_000;
const COEFFICIENTS_READY_AT: u64 = 40_000_000;
// 8.3 table 16: the measurement time at each oversampling, in nanoseconds
const MEASUREMENT_NANOS: [u64; 8] = [
    3_600_000,
    5_200_000,
    8_400_000,
    14_800_000,
    27_600_000,
    53_200_000,
    104_400_000,
    206_800_000,
];
// 4.9.3 table 9: the scale factor `kP` or `kT` at each oversampling
const SCALE_FACTORS: [i64; 8] = [
    524_288, 1_572_864, 3_670_016, 7_864_320, 253_952, 516_096, 1_040_384, 2_088_960,
];
const SECOND_NANOS: u64 = 1_000_000_000;

const C0: i64 = 204;
const C1: i64 = -258;
const C00: i64 = 75_000;
const C10: i64 = -52_000;
const C01: i64 = -2_000;
const C11: i64 = 300;
const C20: i64 = 200;
const C21: i64 = -20;
const C30: i64 = -5;
const TWELVE_BITS: u64 = 0xFFF;
const TWENTY_BITS: u64 = 0xF_FFFF;
const SIXTEEN_BITS: u64 = 0xFFFF;
const WORD_MIN: i64 = -0x80_0000;
const WORD_MAX: i64 = 0x7F_FFFF;

/// How the board wires the `SDO` pin, which sets the least significant bit of the chip's address.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum Sdo {
    /// Left floating or tied to `VDDIO`, which makes the address `0x77`.
    High,
    /// Tied to ground, which makes the address `0x76`.
    Low,
}

impl Sdo {
    /// The address the pin selects, 4.5.
    #[must_use]
    pub fn address(self) -> u8 {
        match self {
            Self::High => 0x77,
            Self::Low => 0x76,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
enum Kind {
    Pressure,
    Temperature,
}

impl Kind {
    fn index(self) -> usize {
        match self {
            Self::Pressure => 0,
            Self::Temperature => 1,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
enum Phase {
    Idle,
    Register,
    Data,
}

/// One DPS310.
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct Dps310 {
    address: u8,
    started_at: VirtualNanos,
    prs_cfg: u8,
    tmp_cfg: u8,
    cfg_reg: u8,
    meas_ctrl: u8,
    pressure: i32,
    temperature: i32,
    pressure_ready: bool,
    temperature_ready: bool,
    running: Option<(Kind, VirtualNanos)>,
    free_at: VirtualNanos,
    due: [VirtualNanos; 2],
    pascals: u32,
    centi_celsius: i32,
    pointer: u8,
    phase: Phase,
}

impl Dps310 {
    /// A chip at power-up with its `SDO` pin as given, measuring the standard atmosphere at 25 °C, in
    /// standby with nothing measured.
    #[must_use]
    pub fn new(sdo: Sdo) -> Self {
        Self {
            address: sdo.address(),
            started_at: VirtualNanos(0),
            prs_cfg: 0,
            tmp_cfg: 0,
            cfg_reg: 0,
            meas_ctrl: 0,
            pressure: 0,
            temperature: 0,
            pressure_ready: false,
            temperature_ready: false,
            running: None,
            free_at: VirtualNanos(0),
            due: [VirtualNanos(0); 2],
            pascals: 101_325,
            centi_celsius: 2_500,
            pointer: 0,
            phase: Phase::Idle,
        }
    }

    /// The pressure the chip measures from now on, in pascals.
    pub fn set_pressure(&mut self, pascals: u32) {
        self.pascals = pascals;
    }

    /// The temperature the chip measures from now on, in hundredths of a degree Celsius.
    pub fn set_temperature(&mut self, centi_celsius: i32) {
        self.centi_celsius = centi_celsius;
    }

    // 8.9: every register at its reset, no measurement, and the start-up timed from `now`
    fn reset(&mut self, now: VirtualNanos) {
        *self = Self {
            address: self.address,
            started_at: now,
            free_at: now,
            due: [now; 2],
            pascals: self.pascals,
            centi_celsius: self.centi_celsius,
            pointer: self.pointer,
            phase: self.phase,
            ..Self::new(Sdo::High)
        };
    }

    fn since_start(&self, now: VirtualNanos) -> u64 {
        now.0.saturating_sub(self.started_at.0)
    }

    fn coefficients_ready(&self, now: VirtualNanos) -> bool {
        self.since_start(now) >= COEFFICIENTS_READY_AT
    }

    fn oversampling(&self, kind: Kind) -> u8 {
        match kind {
            Kind::Pressure => self.prs_cfg & OVERSAMPLING,
            Kind::Temperature => self.tmp_cfg & OVERSAMPLING,
        }
    }

    // 8.3 table 16: how long a measurement of a kind takes, or nothing for a reserved code
    fn duration(&self, kind: Kind) -> Option<u64> {
        let code = self.oversampling(kind);
        (code & RESERVED_OVERSAMPLING == 0).then(|| MEASUREMENT_NANOS[usize::from(code)])
    }

    fn period(&self, kind: Kind) -> u64 {
        let register = match kind {
            Kind::Pressure => self.prs_cfg,
            Kind::Temperature => self.tmp_cfg,
        };
        SECOND_NANOS >> ((register & RATE) >> RATE_SHIFT)
    }

    fn scale(&self, kind: Kind) -> i64 {
        SCALE_FACTORS[usize::from(self.oversampling(kind) & !RESERVED_OVERSAMPLING)]
    }

    // 4.9.2 inverted: the temperature word for the temperature held
    fn temperature_word(&self) -> i32 {
        let scale = self.scale(Kind::Temperature);
        let numerator = (i64::from(self.centi_celsius) - 50 * C0) * scale;
        let word = round(numerator, 100 * C1).clamp(WORD_MIN, WORD_MAX);
        i32::try_from(word).expect("held to twenty-four bits")
    }

    // 4.9.1 inverted. The formula falls as the word rises, since c10 is negative, across every word,
    // so the nearest word is found by bisection on its negation in whole numbers.
    fn pressure_word(&self) -> i32 {
        let temperature = i128::from(self.temperature_word());
        let (pressure_scale, temperature_scale) = (
            i128::from(self.scale(Kind::Pressure)),
            i128::from(self.scale(Kind::Temperature)),
        );
        let rising =
            |word: i128| -compensated(word, temperature, pressure_scale, temperature_scale);
        let target =
            -i128::from(self.pascals) * compensation_scale(pressure_scale, temperature_scale);
        let (mut low, mut high) = (i128::from(WORD_MIN), i128::from(WORD_MAX));
        while low < high {
            let middle = (low + high).div_euclid(2);
            if rising(middle) < target {
                low = middle + 1;
            } else {
                high = middle;
            }
        }
        let below = (low - 1).max(i128::from(WORD_MIN));
        let nearest = if (target - rising(below)).abs() < (rising(low) - target).abs() {
            below
        } else {
            low
        };
        i32::try_from(nearest).expect("held to twenty-four bits")
    }

    fn begin(&mut self, kind: Kind, start: VirtualNanos) {
        let Some(duration) = self.duration(kind) else {
            return;
        };
        self.running = Some((kind, VirtualNanos(start.0 + duration)));
        self.due[kind.index()] = VirtualNanos(start.0 + self.period(kind));
    }

    // 4.1 and 4.4: the kind of measurement that starts next in background mode
    fn next(&self) -> Option<Kind> {
        [
            (Kind::Pressure, self.meas_ctrl & MEASURE_PRESSURE != 0),
            (Kind::Temperature, self.meas_ctrl & MEASURE_TEMPERATURE != 0),
        ]
        .into_iter()
        .filter(|&(kind, measured)| measured && self.duration(kind).is_some())
        .map(|(kind, _)| kind)
        .min_by_key(|kind| self.due[kind.index()])
    }

    // The measurements that finished since the last access land: the flags in order, each word once.
    fn advance(&mut self, now: VirtualNanos) {
        let mut finished = [false; 2];
        loop {
            if let Some((kind, ends_at)) = self.running {
                if ends_at > now {
                    break;
                }
                finished[kind.index()] = true;
                self.running = None;
                self.free_at = ends_at;
                if self.meas_ctrl & BACKGROUND == 0 {
                    self.meas_ctrl = 0;
                    break;
                }
            }
            if self.meas_ctrl & BACKGROUND == 0 {
                break;
            }
            let Some(kind) = self.next() else {
                break;
            };
            let start = self.due[kind.index()].max(self.free_at);
            if start > now {
                break;
            }
            self.begin(kind, start);
        }
        if finished[Kind::Pressure.index()] {
            self.pressure = self.pressure_word();
            self.pressure_ready = true;
        }
        if finished[Kind::Temperature.index()] {
            self.temperature = self.temperature_word();
            self.temperature_ready = true;
        }
    }

    // 8.5: a write of `MEAS_CTRL`
    fn set_mode(&mut self, control: u8, now: VirtualNanos) {
        if control == self.meas_ctrl {
            return;
        }
        self.meas_ctrl = control;
        self.running = None;
        self.free_at = now;
        self.due = [now; 2];
        match control {
            MEASURE_PRESSURE => self.begin(Kind::Pressure, now),
            MEASURE_TEMPERATURE => self.begin(Kind::Temperature, now),
            _ => {}
        }
    }

    fn meas_cfg(&self, now: VirtualNanos) -> u8 {
        let mut flags = 0;
        if self.since_start(now) >= SENSOR_READY_AT {
            flags |= SENSOR_RDY;
        }
        if self.coefficients_ready(now) {
            flags |= COEF_RDY;
        }
        if self.temperature_ready {
            flags |= TMP_RDY;
        }
        if self.pressure_ready {
            flags |= PRS_RDY;
        }
        flags | self.meas_ctrl
    }

    fn read_register(&mut self, register: u8, now: VirtualNanos) -> u8 {
        match register {
            0..=PRS_B0 => {
                let bytes = self.pressure.to_be_bytes();
                if register == PRS_B0 {
                    self.pressure_ready = false;
                }
                bytes[usize::from(register) + 1]
            }
            TMP_B2..=TMP_B0 => {
                let bytes = self.temperature.to_be_bytes();
                if register == TMP_B0 {
                    self.temperature_ready = false;
                }
                bytes[usize::from(register - TMP_B2) + 1]
            }
            PRS_CFG => self.prs_cfg,
            TMP_CFG => self.tmp_cfg,
            MEAS_CFG => self.meas_cfg(now),
            CFG_REG => self.cfg_reg,
            ID => PRODUCT_ID,
            COEF..=COEF_END if self.coefficients_ready(now) => {
                coefficient_bytes()[usize::from(register - COEF)]
            }
            COEF_SRCE if self.coefficients_ready(now) => TMP_COEF_SRCE,
            _ => 0,
        }
    }

    fn write_register(&mut self, register: u8, byte: u8, now: VirtualNanos) {
        match register {
            PRS_CFG => self.prs_cfg = byte,
            TMP_CFG => self.tmp_cfg = byte,
            CFG_REG => self.cfg_reg = byte,
            MEAS_CFG => self.set_mode(byte & MEAS_CTRL, now),
            RESET if byte & SOFT_RST == SOFT_RESET => self.reset(now),
            _ => {}
        }
    }
}

fn coefficient_bytes() -> [u8; 18] {
    let packed = |value: i64, mask: u64| value.cast_unsigned() & mask;
    let mut bytes = [0; 18];
    let c0_c1 = (packed(C0, TWELVE_BITS) << 12) | packed(C1, TWELVE_BITS);
    bytes[0..3].copy_from_slice(&c0_c1.to_be_bytes()[5..8]);
    let c00_c10 = (packed(C00, TWENTY_BITS) << 20) | packed(C10, TWENTY_BITS);
    bytes[3..8].copy_from_slice(&c00_c10.to_be_bytes()[3..8]);
    for (pair, value) in [C01, C11, C20, C21, C30].into_iter().enumerate() {
        let start = 8 + 2 * pair;
        bytes[start..start + 2].copy_from_slice(&packed(value, SIXTEEN_BITS).to_be_bytes()[6..8]);
    }
    bytes
}

fn compensation_scale(pressure_scale: i128, temperature_scale: i128) -> i128 {
    temperature_scale * pressure_scale.pow(3)
}

fn compensated(word: i128, temperature: i128, kp: i128, kt: i128) -> i128 {
    let c = [C00, C10, C20, C30, C01, C11, C21].map(i128::from);
    c[0] * kt * kp.pow(3)
        + word * (c[1] * kt * kp.pow(2) + word * (c[2] * kt * kp + word * c[3] * kt))
        + temperature * (c[4] * kp.pow(3) + word * (c[5] * kp.pow(2) + word * c[6] * kp))
}

impl Peer for Dps310 {
    // 4.5: acknowledges its own address, once the start-up has let it
    fn start(&mut self, address: u8, read: bool, context: &mut Timeline<'_, '_>) -> bool {
        let now = context.now();
        self.advance(now);
        if address != self.address || self.since_start(now) < ANSWERS_FROM {
            self.phase = Phase::Idle;
            return false;
        }
        self.phase = if read { Phase::Data } else { Phase::Register };
        true
    }

    fn write(&mut self, byte: u8, context: &mut Timeline<'_, '_>) -> bool {
        let now = context.now();
        self.advance(now);
        match self.phase {
            Phase::Register => {
                self.pointer = byte;
                self.phase = Phase::Data;
            }
            Phase::Data => {
                self.write_register(self.pointer, byte, now);
                self.pointer = self.pointer.wrapping_add(1);
            }
            Phase::Idle => return false,
        }
        true
    }

    fn read(&mut self, _last: bool, context: &mut Timeline<'_, '_>) -> u8 {
        let now = context.now();
        self.advance(now);
        match self.phase {
            Phase::Data => {
                let register = self.pointer;
                self.pointer = self.pointer.wrapping_add(1);
                self.read_register(register, now)
            }
            Phase::Register | Phase::Idle => 0,
        }
    }

    fn stop(&mut self, _context: &mut Timeline<'_, '_>) {
        self.phase = Phase::Idle;
    }
}

store!(Dps310);