"""Driver for the Sensirion SHT31 temperature and humidity sensor.
Provides I2C communication with the SHT31-D digital humidity and temperature
sensor via the Adafruit CircuitPython SHT31D library. Supports reading
temperature and humidity values, and activating the on-chip heater for
condensation removal.
Hardware:
- Interface: I2C (bus 0 or 1)
- Default address: 0x44 (alternate: 0x45)
- Supply: 3.3V
- Accuracy: +/-0.3C temperature, +/-2% RH humidity
- Features: Built-in heater for de-condensation
Typical usage::
sensor = SHT31(i2c_port=0, address=0x44)
temp = sensor.get_temperature()
hum = sensor.get_humidity()
Note:
Requires ``adafruit-circuitpython-sht31d``, ``board``, and ``busio``.
"""
import time
import adafruit_sht31d
import board
import busio
from utils.oizom_logger import OizomLogger
# -----------------------------------------------------------------------------
# Configure logging
# -----------------------------------------------------------------------------
basic_logger = OizomLogger(__name__).get()
context_logger = OizomLogger(__name__)
[docs]
class SHT31:
"""I2C driver for the Sensirion SHT31-D temperature and humidity sensor.
Wraps the Adafruit SHT31D library for temperature and humidity readout.
Includes a heater activation method for clearing condensation from the
sensor element in high-humidity environments.
Attributes:
sensor: Active Adafruit SHT31D sensor instance, or ``None`` if
initialization failed.
"""
sensor = None
[docs]
def __init__(self, i2c_port: int = 0, address: int = 0x44) -> None:
try:
if i2c_port not in (0, 1):
context_logger.error_with_context("SHT31", "Invalid i2c_port number. Must be 0 or 1.")
return
if i2c_port == 0:
self.i2c = busio.I2C(board.D1, board.D0)
else:
self.i2c = busio.I2C(board.SCL, board.SDA)
self.sensor = adafruit_sht31d.SHT31D(i2c_bus=self.i2c, address=address)
except Exception as e:
context_logger.error_with_context("SHT31", f"Initialization error: {e}")
[docs]
def get_temperature(self) -> float:
try:
temp = self.sensor.temperature
temp = round(temp, 2)
context_logger.debug_with_context("SHT31", f"Temp value retrieved: {temp}")
return temp
except Exception:
context_logger.error_with_context("SHT31", "Failed to retrieve temp value from SHT31 sensor.")
return 0.0
[docs]
def get_humidity(self) -> float:
try:
hum = self.sensor.relative_humidity
hum = round(hum, 2)
context_logger.debug_with_context("SHT31", f"Humidity Index retrieved: {hum}")
return hum
except Exception:
context_logger.error_with_context("SHT31", "Failed to retrieve humidity from SHT31 sensor.")
return 0.0
[docs]
def start_heater(self) -> None:
try:
context_logger.debug_with_context("SHT31", "Starting Heater")
self.sensor.heater = True
time.sleep(1)
self.sensor.heater = False
context_logger.debug_with_context("SHT31", "Heater Off")
except Exception:
context_logger.error_with_context("SHT31", "Failed to start/stop heater from SHT31 sensor.")