pub struct Dht {
config: DhtConfig,
gpio_opt: Option<u64>,
gpio_dht22_io: u8,
gpio_dht22_vcc: u8,
instant_last_measurement: Instant,
lock_error_mutex: bool,
pub(crate) lock_warn_max_mutex_access_duration: bool,
lock_error_failed_after_retries: bool,
pub max_mutex_access_duration: Duration,
pub measurement_interval: Duration,
}Expand description
Represents a Digital Humidity and Temperature (DHT) sensor module, typically a DHT22, responsible for reading ambient temperature and humidity.
This struct encapsulates the configuration, GPIO interface details, and internal state required to communicate with a DHT sensor. It handles the low-level GPIO signaling to read data, apply retries, and perform post-processing (checksum validation, signal calculation) before providing the final temperature and humidity values.
The communication with the DHT sensor is highly timing-sensitive and involves precise GPIO manipulation, including setting pin states, managing delays, and capturing pulse durations via interrupts.
Thread Communication:
This module is designed to run in its own dedicated thread, periodically reading sensor data
and making the latest measurements available via a shared Arc<Mutex<DhtResult>>.
Other modules (like SensorManager or DataLogger) can then read from this mutex to get the
current temperature and humidity. It also responds to Quit commands for graceful shutdown.
Platform-Specific Behavior:
The core sensor reading logic (read function) is conditionally compiled:
- On Linux with the
target_hwfeature enabled, it directly usesrppal::gpiofor hardware interaction. - On other platforms or when
target_hwis disabled, it uses a stub implementation (Err(DhtError::IncorrectPlatform)) to allow compilation and testing without physical hardware.
Thread communication of this component is as follows:
Fields§
§config: DhtConfigconfiguration for communication with DHT sensor
gpio_opt: Option<u64>GPIO interface
gpio_dht22_io: u8numeric GPIO pin for communication with DHT22 sensor
gpio_dht22_vcc: u8numeric GPIO pin for providing power to the DHT22 sensor
instant_last_measurement: Instanttime instance of the last recording
lock_error_mutex: boolflag to avoid flooding the log file in case mutex cannot be locked
lock_warn_max_mutex_access_duration: boolinhibition flag to avoid flooding the log file with repeated messages about excessive access time to mutex
lock_error_failed_after_retries: boolinhibition flag to avoid flooding the log file with repeated messages about failure to read from DHT sensor
max_mutex_access_duration: DurationMaximum permissible access duration for Mutex
measurement_interval: DurationDuration between measurements
Implementations§
Source§impl Dht
impl Dht
Sourcepub fn new(
config: DhtConfig,
gpio_opt: Option<u64>,
gpio_dht22_io: u8,
gpio_dht22_vcc: u8,
) -> Dht
pub fn new( config: DhtConfig, gpio_opt: Option<u64>, gpio_dht22_io: u8, gpio_dht22_vcc: u8, ) -> Dht
Creates a new Dht instance for interacting with a DHT22 sensor on the target platform.
This constructor initializes the DHT sensor module, configuring it with the provided
settings and gaining access to the necessary GPIO pins for communication and power supply
to the DHT22 sensor. This specific implementation is enabled only for Linux targets
when the target_hw feature is active.
§Arguments
config- Configuration data for the DHT sensor, including timing parameters for communication.gpio_opt- AGpioinstance fromrppal, providing the interface to the system’s GPIO pins, wrapped in Option.gpio_dht22_io- The GPIO pin used for data input/output with the DHT22 sensor.gpio_dht22_vcc- The GPIO pin used to control the power supply (VCC) to the DHT22 sensor.
§Returns
A new Dht struct, ready to read temperature and humidity.
Sourcepub fn calc_data_bits(
ticks: [u64; 86],
valid_ticks_received: usize,
) -> [bool; 40]
pub fn calc_data_bits( ticks: [u64; 86], valid_ticks_received: usize, ) -> [bool; 40]
Calculates the raw data bits from the timing sequence of GPIO signal changes during DHT22 sensor communication.
This private helper function interprets the pulse widths measured from the DHT22 sensor.
It differentiates between “neutral” pauses (which are ignored) and actual data bits
(distinguished by their duration relative to DHT22_BIT_TIMING_LIMIT).
Longer pulses are interpreted as true bits, shorter as false bits.
§Arguments
ticks- An array ofu64values, where each value represents the duration (in microseconds) of a specific pulse or pause observed on the data line.valid_ticks_received- The actual number of valid (non-timeout) interrupt events captured, indicating how many entries inticksare relevant.
§Returns
A fixed-size array of bool representing the extracted data bits from the sensor.
This array contains true for a ‘1’ bit and false for a ‘0’ bit.
Sourcepub fn calc_byte(
data_bits: [bool; 40],
start_index: usize,
stop_index: usize,
) -> u8
pub fn calc_byte( data_bits: [bool; 40], start_index: usize, stop_index: usize, ) -> u8
Converts a specific range of raw boolean data bits into a single u8 byte.
This private helper function takes a segment of the data_bits array and reconstructs
the corresponding byte by iterating through the bits and shifting them into place.
§Arguments
data_bits- The array ofboolrepresenting the raw data bits received from the sensor.start_index- The starting index (inclusive) withindata_bitsfor the byte’s data.stop_index- The ending index (inclusive) withindata_bitsfor the byte’s data.
§Returns
A u8 representing the reconstructed byte.
Sourcepub fn calc_byte_array(data_bits: [bool; 40]) -> [u8; 5]
pub fn calc_byte_array(data_bits: [bool; 40]) -> [u8; 5]
Arranges the raw boolean bit information received from the DHT22 sensor into a 5-byte array.
This private helper function takes the array of individual data bits (extracted from pulse timings) and reconstructs the full data payload from the sensor, byte by byte, according to the DHT22 communication protocol.
§Arguments
data_bits- The fixed-size array ofboolrepresenting the raw data bits received from the sensor.
§Returns
A fixed-size array of u8 (5 bytes) containing the reconstructed sensor data,
ready for checksum validation and signal calculation.
Sourcepub fn calc_checksum(
byte_vals: [u8; 5],
try_again: &mut bool,
) -> Result<u8, DhtError>
pub fn calc_checksum( byte_vals: [u8; 5], try_again: &mut bool, ) -> Result<u8, DhtError>
Calculates the checksum of the DHT22 sensor data and validates it against the received checksum.
This private helper function computes an 8-bit sum (modulo 256) of the first four data bytes received from the DHT22 sensor. It then compares this calculated checksum with the checksum byte provided by the sensor itself.
If the checksums do not match, a warning or error is logged (depending on build configuration),
and a DhtError is returned, indicating data corruption during transmission.
§Arguments
byte_vals- A fixed-size array ofu8(5 bytes) containing the sensor’s raw data, where the last byte is the received checksum.try_again- A mutable reference to a boolean flag. Set totruewhen the top-level calling function may try again.
§Returns
An empty Result (Ok(())) if the calculated checksum matches the received one.
§Errors
Returns a DhtError if the checksum is invalid:
DhtError::ChecksumError: If the calculated checksum does not match the received checksum, indicating that the data was corrupted during transmission. This is considered a recoverable error, and the calling function should retry the read operation.
Sourcepub fn calc_signals(byte_vals: [u8; 5]) -> Result<(f32, f32), DhtError>
pub fn calc_signals(byte_vals: [u8; 5]) -> Result<(f32, f32), DhtError>
Calculates final temperature and humidity values from the raw byte array.
This function reconstructs the 16-bit integer values for humidity and temperature
from their respective byte pairs. It then performs range checks to ensure the values
are within the sensor’s specified operating limits before converting them into
standard f32 floating-point representations.
§Arguments
byte_vals- A fixed-size array ofu8(5 bytes) containing the validated sensor data.
§Returns
A Result containing a tuple (f32, f32) with the temperature in °C and humidity in %RH.
§Errors
Returns a DhtError if a value is outside the sensor’s valid operating range:
DhtError::TemperatureOutOfRange: If the calculated temperature is invalid.DhtError::HumidityOutOfRange: If the calculated humidity is invalid.
Sourcepub fn read(
&self,
_reset_sensor: bool,
_try_again: &mut bool,
) -> Result<(f32, f32), DhtError>
pub fn read( &self, _reset_sensor: bool, _try_again: &mut bool, ) -> Result<(f32, f32), DhtError>
Stub function for non-target platforms to allow compilation.
This version is used when the target_hw feature is disabled or on a non-Linux OS.
It does not interact with hardware and always returns an error.
§Returns
This function does not return a value.
§Errors
Always returns Err(DhtError::IncorrectPlatform).
Sourcepub fn get_data(&mut self) -> Result<(f32, f32), DhtError>
pub fn get_data(&mut self) -> Result<(f32, f32), DhtError>
Initiates a robust reading process from the DHT22 sensor, with retries.
This function attempts to read temperature and humidity data. It includes an internal retry mechanism for transient, recoverable errors like timeouts or checksum mismatches, making the sensor reading more reliable.
§Returns
A Result containing a tuple (f32, f32) with the temperature and humidity on success.
§Errors
Returns a DhtError if the reading fails permanently or after all retries:
DhtError::FailedAfterRetries: If all attempts fail due to recoverable errors.- Any other
DhtErrorvariant for non-recoverable hardware or configuration failures.
Sourcepub fn execute(
&mut self,
mutex_dht: Arc<Mutex<Result<(f32, f32), DhtError>>>,
dht_channels: &mut DhtChannels,
)
pub fn execute( &mut self, mutex_dht: Arc<Mutex<Result<(f32, f32), DhtError>>>, dht_channels: &mut DhtChannels, )
Executes the main loop for the DHT sensor thread, receiving requests and sending measurement responses.
This function runs indefinitely, acting as a dedicated service for reading ambient
temperature and humidity from the DHT22 sensor. It waits for incoming InternalCommand
from other modules (like Ambient or SignalHandler).
When a RequestSignal for ambient temperature or humidity is received, it performs
a sensor reading (using self.get_data()) and sends the Result back. It handles
Quit commands for graceful shutdown and logs errors/warnings for invalid commands or channel issues.
§Arguments
mutex_dht- Mutex to store the result of the measurementdht_channels- Mutable reference to the struct containing the channel
Trait Implementations§
Source§impl CheckMutexAccessDurationTrait for Dht
impl CheckMutexAccessDurationTrait for Dht
Source§fn get_warn_lock(&self, _key_opt: &Option<&AquariumSignal>) -> bool
fn get_warn_lock(&self, _key_opt: &Option<&AquariumSignal>) -> bool
Method connects the default trait implementation with the specific implementation reading the warn-lock.
Source§fn set_warn_lock(&mut self, _key_opt: &Option<&AquariumSignal>, value: bool)
fn set_warn_lock(&mut self, _key_opt: &Option<&AquariumSignal>, value: bool)
Method connects the default trait implementation with the specific implementation setting the warn-lock.
Source§fn get_max_mutex_access_duration(&self) -> Duration
fn get_max_mutex_access_duration(&self) -> Duration
Method connects the default trait implementation with the specific implementation for getting maximum permissible access duration
Source§fn get_location(&self) -> &str
fn get_location(&self) -> &str
inform the location of the warning for logging purposes
fn check_mutex_access_duration( &mut self, key_opt: Option<&AquariumSignal>, instant_after_locking_mutex: Instant, instant_before_locking_mutex: Instant, )
Source§impl ProcessExternalRequestTrait for Dht
impl ProcessExternalRequestTrait for Dht
Source§fn process_external_request(
&mut self,
rx_from_signal_handler: &mut AquaReceiver<InternalCommand>,
_: Option<&mut AquaReceiver<InternalCommand>>,
) -> (bool, bool, bool)
fn process_external_request( &mut self, rx_from_signal_handler: &mut AquaReceiver<InternalCommand>, _: Option<&mut AquaReceiver<InternalCommand>>, ) -> (bool, bool, bool)
Checks for and processes new commands relevant to the Dht module from external channels.
This is the specialized implementation of ProcessExternalRequestTrait for the DataLogger.
It delegates directly to process_external_request_without_messaging, indicating
that the DataLogger only processes commands from the signal handler and
ignores any input from a messaging channel.
§Arguments
rx_from_signal_handler- A reference to the receiver end of the channel for commands originating from the signal handler._- This parameter is ignored, as theDataLoggerdoes not process messages from a messaging channel.
§Returns
A tuple (bool, bool, bool) indicating the status of commands received:
- The first
boolistrueif aQuitcommand was received; otherwisefalse. - The second
boolis alwaysfalse(no “Start” commands processed). - The third
boolis alwaysfalse(no “Stop” commands processed).