I am using multiple sensors in an ESP32 project and am trying to organize the sensor-structs together with other parameters, that configure how the measurements get processed later, in a struct. This is so that the sensor and its configs are together in one place. The sensor is never measured in a context without the other configs, so putting all in one struct seemed like the most sensible way (from an OOP standpoint).
The first naive (comming from other OO-languages) was this (using bme280 as example):
fn main() -> Result<(), EspError> {
...
let let i2c0 = ... // shortened
let i2c_ref_cell = RefCell::new(i2c0);
let rcd1 = RefCellDevice::new(&i2c_ref_cell);
// more rcds
let wrapped_sensor = WrappedBME280::new(rcd1, 1234, ...);
// more sensors
}
// wrapped_bme280.rs
pub struct WrappedBME280<'a> {
bme280: BME280<RefCellDevice<'a, I2cDriver<'a>>>,
config1: u16,
config2: ...
...
}
impl<'a> WrappedBME280<'a> {
pub fn new(rcd: RefCellDevice<'a, I2cDriver<'a>>, config1: u16, ...) -> WrappedBME280<'a> {
let mut bme280 = BME280::new_primary(rcd);
bme280.init(&mut delay::Ets).unwrap();
ModbusBME280 {
bme280,
config1,
config2,
...
}
}
pub fn measure(&mut self) -> Result<(), bme280::Error<I2cError>> {
match self.bme280.measure(&mut delay::Ets) {
Ok(meas) => {
// handle result using configs
...
Ok(())
},
Err(err) => Err(err)
}
}
}
Here I ran into borrowed value does not live long enough
on the borrow of i2c_ref_cell
.
I tried solutions mentioned here and here.
With these I ran into the problem of either not being able to borrow the sensor mutably (as calling measure(...)
requires this) or the same borrowed value does not live long enough
as before.
So my question is how to do this the proper rust way.
user12451192 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.