Source code for sensirion_i2c_stc3x.device

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# (c) Copyright 2024 Sensirion AG, Switzerland
#
#     THIS FILE IS AUTOMATICALLY GENERATED!
#
# Generator:     sensirion-driver-generator 0.38.1
# Product:       stc3x
# Model-Version: 1.0.0
#
"""
The class Stc3xDeviceBase implements the low level interface of the sensor.
The class Stc3xDevice extends the Stc3xDeviceBase. It provides additional functions to ease the use of the
sensor.
"""

from sensirion_driver_adapters.transfer import execute_transfer
from sensirion_driver_support_types.mixin_access import MixinAccess

from sensirion_i2c_stc3x.commands import (ApplyState, DisableAutomaticSelfCalibration, DisableStrongFilter,
                                          DisableWeakFilter, EnableAutomaticSelfCalibration, EnableStrongFilter,
                                          EnableWeakFilter, EnterSleepMode, ExitSleepMode, ForcedRecalibration,
                                          PrepareProductIdentifier, PrepareReadState,
                                          ReadProductIdentifier, ReadSensorState, SelfTest, SetBinaryGas, SetPressure,
                                          SetRelativeHumidityRaw, SetTemperatureRaw, TestResultT, WriteSensorState,
                                          MeasureGasConcentrationRawFast, MeasureGasConcentrationRawSlow)
from sensirion_i2c_stc3x.result_types import (SignalGasConcentration, SignalTemperature)


[docs]class Stc3xDeviceBase: """Low level API implementation of STC3X"""
[docs] def __init__(self, channel): self._channel = channel self._measurement_command = MeasureGasConcentrationRawFast()
@property def channel(self): return self._channel
[docs] def set_binary_gas(self, binary_gas): """ The STC3x measures the concentration of binary gas mixtures. It is important to note that the STC3x is not selective for gases, and it assumes that the binary gas is set correctly. The sensor can only give a correct concentration value when only the gases set with this command are present. When the system is reset, or wakes up from sleep mode, the sensor goes back to default mode, in which no binary gas is selected. This means that the binary gas must be reconfigured. When no binary gas is selected (default mode) the concentration measurement will return undefined results. This allows to detect unexpected sensor interruption (e.g. due to temporary power loss) and consequently reset the binary gas to the appropriate mixture. :param binary_gas: See section 3.3.2 in the corresponding datasheet for a list of available binary gases. STC31-C: - 0x0010: CO₂ in N₂ for range in 0 to 100 vol% - 0x0011: CO₂ in air for range in 0 to 100 vol% - 0x0012: CO₂ in N₂ for range in 0 to 40 vol% - 0x0013: CO₂ in air for range in 0 to 40 vol% STC31: - 0x0000: CO₂ in N₂ for range in 0 to 100 vol% - 0x0001: CO₂ in air for range in 0 to 100 vol% - 0x0002: CO₂ in N₂ for range in 0 to 25 vol% - 0x0003: CO₂ in air for range in 0 to 25 vol% :Example: .. code-block:: python sensor.set_binary_gas(19) """ if binary_gas < 0x10: self._measurement_command = MeasureGasConcentrationRawFast() else: self._measurement_command = MeasureGasConcentrationRawSlow() transfer = SetBinaryGas(binary_gas) return execute_transfer(self._channel, transfer)
[docs] def set_relative_humidity_raw(self, relative_humidity_ticks): """ As mentioned in section 5.1 of the datasheet, the measurement principle of the concentration measurement is dependent on the humidity of the gas. With the set relative humidity command, the sensor uses internal algorithms to compensate the concentration results. When no value is written to the sensor after a soft reset, wake-up or power-up, a relative humidity of 0% is assumed. The value written to the sensor is used until a new value is written to the sensor :param relative_humidity_ticks: Convert %RH to value by: RH * (2^16 - 1) / 100 :Example: .. code-block:: python sensor.set_relative_humidity_raw(32768) """ transfer = SetRelativeHumidityRaw(relative_humidity_ticks) return execute_transfer(self._channel, transfer)
[docs] def set_temperature_raw(self, temperature_ticks): """ The concentration measurement requires a compensation of temperature. Per default, the sensor uses the internal temperature sensor to compensate the concentration results. However, when using the SHTxx, it is recommended to also use its temperature value, because it is more accurate. When no value is written to the sensor after a soft reset, wake-up or power-up, the internal temperature signal is used. The value written to the sensor is used until a new value is written to the sensor. :param temperature_ticks: Convert °C to value by: T * 200 """ transfer = SetTemperatureRaw(temperature_ticks) return execute_transfer(self._channel, transfer)
[docs] def set_pressure(self, absolue_pressure): """ A pressure value can be written into the sensor, for density compensation of the gas concentration measurement. It is recommended to set the pressure level, if it differs significantly from 1013mbar. Pressure compensation is valid from 600mbar to 1200mbar. When no value is written to the sensor after a soft reset, wake-up or power-up, a pressure of 1013mbar is assumed. The value written is used until a new value is written to the sensor. :param absolue_pressure: Ambient pressure in mbar (milli-bars) """ transfer = SetPressure(absolue_pressure) return execute_transfer(self._channel, transfer)
[docs] def measure_gas_concentration_raw(self): """ The measurement of gas concentration is done in one measurement in a single shot, and takes less than 66ms. When measurement data is available, it can be read out by sending an I2C read header and reading out the data from the sensor. If no measurement data is available yet, the sensor will respond with a NACK on the I2C read header. In case the ‘Set temperature command’ has been used prior to the measurement command, the temperature value given out by the STC3x will be that one of the ‘Set temperature command’. When the ‘Set temperature command’ has not been used, the internal temperature value can be read out. During product development it is recommended to compare the internal temperature value of the STC3x and the temperature value of the SHTxx, to check whether both sensors are properly thermally coupled. The values must be within 0.7°C. :return gas_ticks: Gas concentration. Convert to vol % by 100 * (value - 2^14) / 2^15 :return temperature_ticks: Temperature. Convert to °C by value / 200 .. note:: The Gas concentration is a 16-bit unsigned integer. The temperature and byte 7 and 8 don’t need to be read out. The read sequence can be aborted after any byte by a NACK and a STOP condition. The measurement command should not be triggered more often than once a second. """ transfer = self._measurement_command return execute_transfer(self._channel, transfer)
[docs] def forced_recalibration(self, reference_concentration): """ Forced recalibration (FRC) is used to improve the sensor output with a known reference value. See the Field Calibration Guide for more details. If no argument is given, the sensor will assume a default value of 0 vol%. This command will trigger a concentration measurement as described in 3.3.6 of the datasheet and therefore it will take the same measurement time. :param reference_concentration: Reference concentration :Example: .. code-block:: python sensor.forced_recalibration(0) """ transfer = ForcedRecalibration(reference_concentration) return execute_transfer(self._channel, transfer)
[docs] def enable_automatic_self_calibration(self): """ Enable the automatic self-calibration (ASC). The sensor can run in automatic self-calibration mode. This mode will enhance the accuracy for applications where the target gas is not present for the majority of the time. See the Field Calibration Guide for more details. This feature can be enabled or disabled by using the commands as shown below. The automatic self-calibration is optimized for a gas concentration measurement interval of 1s. Substantially different measurement intervals may decrease the self-calibration performance. The default state is disabled. Automatic self-calibration in combination with sleep mode requires a specific sequence of steps. See section 3.3.9 in the datasheet for more detailed instructions .. note:: The sensor will apply automatic self-calibration """ transfer = EnableAutomaticSelfCalibration() return execute_transfer(self._channel, transfer)
[docs] def disable_automatic_self_calibration(self): """ Disable the automatic self-calibration (ASC). The sensor can run in automatic self-calibration mode. This mode will enhance the accuracy for applications where the target gas is not present for the majority of the time. See the Field Calibration Guide for more details. This feature can be enabled or disabled by using the commands as shown below. The default state is disabled. .. note:: The sensor will not apply automatic self-calibration. This is the default state of the sensor. """ transfer = DisableAutomaticSelfCalibration() return execute_transfer(self._channel, transfer)
[docs] def prepare_read_state(self): """ The sensor will prepare its current state to be read out. .. note:: See section 3.3.9 of the datasheet for detailed instructions. """ transfer = PrepareReadState() return execute_transfer(self._channel, transfer)
[docs] def read_sensor_state(self): """ Read out the sensor state. The 30 bytes must be stored on the microcontroller to be written back to the sensor after exiting sleep mode. :return state: Current sensor state .. note:: See section 3.3.9 of the datasheet for detailed instructions. """ transfer = ReadSensorState() return execute_transfer(self._channel, transfer)[0]
[docs] def write_sensor_state(self, state): """ Write the sensor state. The 30 bytes must be stored on the microcontroller to be written back to the sensor after exiting sleep mode. :param state: Current sensor state .. note:: See section 3.3.9 of the datasheet for detailed instructions. """ transfer = WriteSensorState(state) return execute_transfer(self._channel, transfer)
[docs] def apply_state(self): """ The sensor will apply the written state data. .. note:: See section 3.3.9 of the datasheet for detailed instructions. """ transfer = ApplyState() return execute_transfer(self._channel, transfer)
[docs] def self_test(self): """ The sensor will run an on-chip self-test. A successful self-test will return zero. The 16-bit result of a sensor self-test is a combination of possible error states, encoded as bits (starting with lsb): - 0-1: Memory error - 2: VDD out of range - 3-8: Measurement value error - 9: Difference between externally supplied temperature (see 2.3.4) and internally measured temperatures exceeds the accuracy specifications. In case of a successful self-test the sensor returns 0x0000 with correct CRC. :return self_test_output: Self test result. Error code or 0x0000 on success. """ transfer = SelfTest() res_0 = execute_transfer(self._channel, transfer)[0] return TestResultT(res_0)
[docs] def prepare_product_identifier(self): """Prepare for reading the product identifier and sensor serial number.""" transfer = PrepareProductIdentifier() return execute_transfer(self._channel, transfer)
[docs] def read_product_identifier(self): """ Read the product identifier and sensor serial number. :return product_number: 32-bit unique product and revision number. The number is listed below: STC31: 0x08010301 :return serial_number_high: Higher 32-bit of the 64-bit unique serial number :return serial_number_low: Lower 32-bit of the 64-bit unique serial number .. note:: Make sure to call 'prepare product identifier' immediately before. """ transfer = ReadProductIdentifier() return execute_transfer(self._channel, transfer)
[docs] def enter_sleep_mode(self): """ Put sensor into sleep mode. In sleep mode the sensor uses the minimum amount of current. The mode can only be entered from idle mode, i.e. when the sensor is not measuring. This mode is particularly useful for battery operated devices. To minimize the current in this mode, the complexity of the sleep mode circuit has been reduced as much as possible, which is mainly reflected by the way the sensor exits the sleep mode. The sleep command can be sent after the result have been read out and the sensor is in idle mode. .. note:: Only available in idle mode """ transfer = EnterSleepMode() return execute_transfer(self._channel, transfer)
[docs] def exit_sleep_mode(self): """ Exit the sleep mode. The sensor exits the sleep mode and enters the idle mode when it receives the valid I2C address and a write bit (‘0’). Note that the I2C address is not acknowledged. It is possible to poll the sensor to see whether the sensor has received the address and has woken up. This takes maximum 12ms. """ transfer = ExitSleepMode() return execute_transfer(self._channel, transfer)
[docs] def enable_weak_filter(self): """ The STC31 has two built-in noise filters that run an exponential smoothing over the past measurement points. By default, no filter is applied to the data. If weak smoothing is desired, the following command(s) must be executed once upon starting the sensor. When enabled, the weak filter is applied for all subsequent concentration measurements. .. note:: - Both filters can be activated at the same time (chained) for stronger smoothing. - FRC can only benefit from this filtering if sufficient measurement points have been taken before executing the FRC. - The response time (specified in section 1.2) will increase if a noise filter is applied. - Filtering will not function if the sensor is put to sleep between each concentration measurement, asthe last output value is lost. """ transfer = EnableWeakFilter() return execute_transfer(self._channel, transfer)
[docs] def disable_weak_filter(self): """disable the weak smoothing filter""" transfer = DisableWeakFilter() return execute_transfer(self._channel, transfer)
[docs] def enable_strong_filter(self): """ The STC31 has two built-in noise filters that run an exponential smoothing over the past measurement points. By default, no filter is applied to the data. If strong smoothing is desired, the following command(s) must be executed once upon starting the sensor. When enabled, the strong filter is applied for all subsequent concentration measurements. .. note:: - Both filters can be activated at the same time (chained) for stronger smoothing. - FRC can only benefit from this filtering if sufficient measurement points have been taken before executing the FRC. - The response time (specified in section 1.2) will increase if a noise filter is applied. - Filtering will not function if the sensor is put to sleep between each concentration measurement, asthe last output value is lost. """ transfer = EnableStrongFilter() return execute_transfer(self._channel, transfer)
[docs] def disable_strong_filter(self): """disable the strong smoothing filter""" transfer = DisableStrongFilter() return execute_transfer(self._channel, transfer)
[docs]class Stc3xDevice(Stc3xDeviceBase): """Driver class implementation of STC3X""" #: Access to base class stc3x = MixinAccess()
[docs] def __init__(self, channel): super().__init__(channel)
[docs] def set_relative_humidity(self, relative_humidity): """ The measurement principle of the concentration measurement is dependent on the humidity of the gas. The new low cross sensitivity mode reduces this sensitivity by smart internal compensation to a minimum. If possible, it is still recommended to compensate for relative humidity and to update the compensation input whenever the relative humidity changes. With the set relative humidity command, the sensor uses the set humidity in the gas model to compensate the concentration results. :param relative_humidity: Relative humidity in percent %. """ rh_ticks = int((relative_humidity * 65535.0) / 100.0) return self.stc3x.set_relative_humidity_raw(rh_ticks)
[docs] def set_temperature(self, temperature): """ The concentration measurement requires a compensation of temperature. Per default, the sensor uses the internal temperature sensor to compensate the concentration results. However, when using the SHTxx, it is recommended to also use its temperature value, because it is more accurate. The temperature compensation input should be updated whenever the temperature changes. :param temperature: Temperature in degree celsius. """ temperature_ticks = int(temperature * 200.0) return self.stc3x.set_temperature_raw(temperature_ticks)
[docs] def measure_gas_concentration(self): """ The measurement of gas concentration is done in one measurement in a single shot, and takes less than 66ms. When measurement data is available, it can be read out by sending an I2C read header and reading out the data from the sensor. If no measurement data is available yet, the sensor will respond with a NACK on the I2C read header. :return co2_concentration: :return temperature: """ (raw_gas_concentration, raw_temperature ) = self.stc3x.measure_gas_concentration_raw() return (SignalGasConcentration(raw_gas_concentration), SignalTemperature(raw_temperature))
[docs] def get_sensor_state(self): """ The sensor stores settings like the Gas Mode or reference values of FRC and ASC in volatile memory. These are not retained when the sensor loses power and must be stored externally to be sent to the sensor after each power cycle. To store the state externally use the methods get_sensor_state and set_sensor_state. The sensor state contains the following information: - Selected binary gas index. - ON or OFF flag and offset value to apply to the sensor's output for the automatic self-calibration. - Offset value to apply to the sensor's output used in forced recalibration. - Compensation inputs: last supplied values of temperature, humidity and pressure :return state: Current sensor state """ self.stc3x.prepare_read_state() return self.stc3x.read_sensor_state()
[docs] def set_sensor_state(self, sensor_state): """ The sensor stores settings like the Gas Mode or reference values of FRC and ASC in volatile memory. These are not retained when the sensor loses power and must be stored externally to be sent to the sensor after each power cycle. To store the state externally use the methods get_sensor_state and set_sensor_state. The sensor state contains the following information: - Selected binary gas index. - ON or OFF flag and offset value to apply to the sensor's output for the automatic self-calibration. - Offset value to apply to the sensor's output used in forced recalibration. - Compensation inputs: last supplied values of temperature, humidity and pressure :param sensor_state: """ self.stc3x.write_sensor_state(sensor_state) return self.stc3x.apply_state()
[docs] def get_product_id(self): """ Get the 32-bit product identifier and 64-bit sensor serial number. Please check the datasheet to get the expected product identifier for your STC31. :return product_id: :return serial_number: """ self.stc3x.prepare_product_identifier() (product_number, serial_number_high, serial_number_low ) = self.stc3x.read_product_identifier() return (product_number, (int(serial_number_high) * 4294967296) + serial_number_low)