Example #1
0
class InputModule(AbstractInput):
    """
    A sensor support class that measures the COZIR's CO2, humidity, and temperature
    and calculates the dew point

    """
    def __init__(self, input_dev, testing=False):
        super(InputModule, self).__init__(input_dev,
                                          testing=testing,
                                          name=__name__)

        if not testing:
            from cozir import Cozir

            self.uart_location = input_dev.uart_location
            self.sensor = Cozir(self.uart_location)

    def get_measurement(self):
        """ Gets the measurements """
        self.return_dict = measurements_dict.copy()

        if self.is_enabled(0):
            self.value_set(0, self.sensor.read_CO2())

        if self.is_enabled(1):
            self.value_set(1, self.sensor.read_temperature())

        if self.is_enabled(2):
            self.value_set(2, self.sensor.read_humidity())

        if (self.is_enabled(3) and self.is_enabled(1) and self.is_enabled(2)):
            self.value_set(
                3, calculate_dewpoint(self.value_get(1), self.value_get(2)))

        return self.return_dict
Example #2
0
    def __init__(self, input_dev, testing=False):
        super(InputModule, self).__init__(input_dev,
                                          testing=testing,
                                          name=__name__)

        if not testing:
            from cozir import Cozir

            self.uart_location = input_dev.uart_location
            self.sensor = Cozir(self.uart_location)
Example #3
0
    def __init__(self, input_dev, testing=False):
        super(InputModule, self).__init__()
        self.setup_logger(testing=testing, name=__name__, input_dev=input_dev)

        if not testing:
            from cozir import Cozir

            self.device_measurements = db_retrieve_table_daemon(
                DeviceMeasurements).filter(
                    DeviceMeasurements.device_id == input_dev.unique_id)

            self.uart_location = input_dev.uart_location
            self.sensor = Cozir(self.uart_location)
Example #4
0
    def __init__(self, input_dev, testing=False):
        super(COZIRSensor, self).__init__()
        self.logger = logging.getLogger("mycodo.inputs.cozir")
        self._co2 = None
        self._dew_point = None
        self._humidity = None
        self._temperature = None

        if not testing:
            from cozir import Cozir
            self.logger = logging.getLogger(
                "mycodo.inputs.cozir_{id}".format(id=input_dev.id))
            self.device_loc = input_dev.device_loc
            self.convert_to_unit = input_dev.convert_to_unit
            self.sensor = Cozir(self.device_loc)
Example #5
0
    def __init__(self, input_dev, testing=False):
        super(InputModule, self).__init__()
        self.logger = logging.getLogger("mycodo.inputs.cozir_co2")

        if not testing:
            from cozir import Cozir
            self.logger = logging.getLogger("mycodo.cozir_co2_{id}".format(
                id=input_dev.unique_id.split('-')[0]))

            self.device_measurements = db_retrieve_table_daemon(
                DeviceMeasurements).filter(
                    DeviceMeasurements.device_id == input_dev.unique_id)

            self.uart_location = input_dev.uart_location
            self.sensor = Cozir(self.uart_location)
Example #6
0
def main():
	rospy.init_node("Measure_CO2", anonymous=True)
	CO2_int_pub = rospy.Publisher("CO2", CO2, queue_size=1000)
	loop_rate = rospy.Rate(RATE)#Set the refresh rate in Hertz
	CO2_value = CO2()
	sensor_attached = True
	try:#Try to connect the sensor
		c = Cozir('/dev/ttyUSB0')#Create the sensor object
		c.set_filter(16)#Set the filter to 16
	except:
		rospy.loginfo("CO2 sensor not attached")
		sensor_attached = False
	
	CO2_value.sensor_attached = sensor_attached;
	
	temperature_calibration_factor = 1.0
	humidity_calibration_factor = 1.0

	while not rospy.is_shutdown():
		if(sensor_attached):
			CO2_value.CO2level = round(c.read_CO2(),1)
			CO2_value.temperature = round(c.read_temperature() *temperature_calibration_factor,1)
			CO2_value.humidity = round(c.read_humidity()* humidity_calibration_factor,1)
		else:#If the sensor is not connected the sensor will give 0.0 measurements
			CO2_value.CO2level = 0.0
			CO2_value.temperature = 0.0
			CO2_value.humidity = 0.0
			
		CO2_int_pub.publish(CO2_value)
		loop_rate.sleep()
Example #7
0
class InputModule(AbstractInput):
    """
    A sensor support class that measures the COZIR's CO2, humidity, and temperature
    and calculates the dew point

    """

    def __init__(self, input_dev, testing=False):
        super(InputModule, self).__init__()
        self.logger = logging.getLogger("mycodo.inputs.cozir_co2")

        if not testing:
            from cozir import Cozir
            self.logger = logging.getLogger(
                "mycodo.cozir_co2_{id}".format(id=input_dev.unique_id.split('-')[0]))

            self.device_measurements = db_retrieve_table_daemon(
                DeviceMeasurements).filter(
                    DeviceMeasurements.device_id == input_dev.unique_id)

            self.uart_location = input_dev.uart_location
            self.sensor = Cozir(self.uart_location)

    def get_measurement(self):
        """ Gets the measurements """
        return_dict = measurements_dict.copy()

        if self.is_enabled(0):
            return_dict[0]['value'] = self.sensor.read_CO2()

        if self.is_enabled(1):
            return_dict[1]['value'] = self.sensor.read_temperature()

        if self.is_enabled(2):
            return_dict[2]['value'] = self.sensor.read_humidity()

        if (self.is_enabled(3) and
                self.is_enabled(1) and
                self.is_enabled(2)):
            return_dict[3]['value'] = calculate_dewpoint(
                return_dict[1]['value'], return_dict[2]['value'])

        return return_dict
Example #8
0
class InputModule(AbstractInput):
    """
    A sensor support class that measures the COZIR's CO2, humidity, and temperature
    and calculates the dew point

    """
    def __init__(self, input_dev, testing=False):
        super(InputModule, self).__init__()
        self.logger = logging.getLogger("mycodo.inputs.cozir_co2")

        if not testing:
            from cozir import Cozir
            self.logger = logging.getLogger("mycodo.cozir_co2_{id}".format(
                id=input_dev.unique_id.split('-')[0]))

            self.device_measurements = db_retrieve_table_daemon(
                DeviceMeasurements).filter(
                    DeviceMeasurements.device_id == input_dev.unique_id)

            self.uart_location = input_dev.uart_location
            self.sensor = Cozir(self.uart_location)

    def get_measurement(self):
        """ Gets the measurements """
        return_dict = measurements_dict.copy()

        if self.is_enabled(0):
            return_dict[0]['value'] = self.sensor.read_CO2()

        if self.is_enabled(1):
            return_dict[1]['value'] = self.sensor.read_temperature()

        if self.is_enabled(2):
            return_dict[2]['value'] = self.sensor.read_humidity()

        if (self.is_enabled(3) and self.is_enabled(1) and self.is_enabled(2)):
            return_dict[3]['value'] = calculate_dewpoint(
                return_dict[1]['value'], return_dict[2]['value'])

        return return_dict
Example #9
0
class InputModule(AbstractInput):
    """
    A sensor support class that measures the COZIR's CO2, humidity, and temperature
    and calculates the dew point
    """
    def __init__(self, input_dev, testing=False):
        super().__init__(input_dev, testing=testing, name=__name__)

        self.sensor = None

        if not testing:
            self.try_initialize()

    def initialize(self):
        from cozir import Cozir

        self.sensor = Cozir(self.input_dev.uart_location)

    def get_measurement(self):
        """Gets the measurements."""
        if not self.sensor:
            self.logger.error("Error 101: Device not set up. See https://kizniche.github.io/Mycodo/Error-Codes#error-101 for more info.")
            return

        self.return_dict = copy.deepcopy(measurements_dict)

        if self.is_enabled(0):
            self.value_set(0, self.sensor.read_CO2())

        if self.is_enabled(1):
            self.value_set(1, self.sensor.read_temperature())

        if self.is_enabled(2):
            self.value_set(2, self.sensor.read_humidity())

        if self.is_enabled(1) and self.is_enabled(2):
            self.value_set(3, calculate_dewpoint(self.value_get(1), self.value_get(2)))

        return self.return_dict
Example #10
0
class InputModule(AbstractInput):
    """
    A sensor support class that measures the COZIR's CO2, humidity, and temperature
    and calculates the dew point

    """
    def __init__(self, input_dev, testing=False):
        super(InputModule, self).__init__()
        self.setup_logger(testing=testing, name=__name__, input_dev=input_dev)

        if not testing:
            from cozir import Cozir

            self.device_measurements = db_retrieve_table_daemon(
                DeviceMeasurements).filter(
                    DeviceMeasurements.device_id == input_dev.unique_id)

            self.uart_location = input_dev.uart_location
            self.sensor = Cozir(self.uart_location)

    def get_measurement(self):
        """ Gets the measurements """
        self.return_dict = measurements_dict.copy()

        if self.is_enabled(0):
            self.set_value(0, self.sensor.read_CO2())

        if self.is_enabled(1):
            self.set_value(1, self.sensor.read_temperature())

        if self.is_enabled(2):
            self.set_value(2, self.sensor.read_humidity())

        if (self.is_enabled(3) and self.is_enabled(1) and self.is_enabled(2)):
            self.set_value(
                3, calculate_dewpoint(self.get_value(1), self.get_value(2)))

        return self.return_dict
Example #11
0
    def __init__(self, input_dev, testing=False):
        super(InputModule, self).__init__()
        self.logger = logging.getLogger("mycodo.inputs.cozir_co2")

        if not testing:
            from cozir import Cozir
            self.logger = logging.getLogger(
                "mycodo.cozir_co2_{id}".format(id=input_dev.unique_id.split('-')[0]))

            self.device_measurements = db_retrieve_table_daemon(
                DeviceMeasurements).filter(
                    DeviceMeasurements.device_id == input_dev.unique_id)

            self.uart_location = input_dev.uart_location
            self.sensor = Cozir(self.uart_location)
Example #12
0
    def initialize_input(self):
        from cozir import Cozir

        self.sensor = Cozir(self.input_dev.uart_location)
Example #13
0
class COZIRSensor(AbstractInput):
    """
    A sensor support class that measures the COZIR's CO2, humidity, and temperature
    and calculates the dew point

    """
    def __init__(self, input_dev, testing=False):
        super(COZIRSensor, self).__init__()
        self.logger = logging.getLogger("mycodo.inputs.cozir")
        self._co2 = None
        self._dew_point = None
        self._humidity = None
        self._temperature = None

        if not testing:
            from cozir import Cozir
            self.logger = logging.getLogger(
                "mycodo.inputs.cozir_{id}".format(id=input_dev.id))
            self.device_loc = input_dev.device_loc
            self.convert_to_unit = input_dev.convert_to_unit
            self.sensor = Cozir(self.device_loc)

    def __repr__(self):
        """  Representation of object """
        return "<{cls}(co2={co2})(dewpoint={dpt})(humidity={hum})(temperature={temp})>".format(
            cls=type(self).__name__,
            co2="{0:.2f}".format(self._co2),
            dpt="{0:.2f}".format(self._dew_point),
            hum="{0:.2f}".format(self._humidity),
            temp="{0:.2f}".format(self._temperature))

    def __str__(self):
        """ Return measurement information """
        return "CO2: {co2}, Dew Point: {dpt}, Humidity: {hum}, Temperature: {temp}".format(
            co2="{0:.2f}".format(self._co2),
            dpt="{0:.2f}".format(self._dew_point),
            hum="{0:.2f}".format(self._humidity),
            temp="{0:.2f}".format(self._temperature))

    def __iter__(self):  # must return an iterator
        """ COZIRSensor iterates through live measurement readings """
        return self

    def next(self):
        """ Get next measurement reading """
        if self.read():  # raised an error
            raise StopIteration  # required
        return dict(co2=float('{0:.2f}'.format(self._co2)),
                    dewpoint=float('{0:.2f}'.format(self._dew_point)),
                    humidity=float('{0:.2f}'.format(self._humidity)),
                    temperature=float('{0:.2f}'.format(self._temperature)))

    @property
    def co2(self):
        """ COZIR CO2 in ppm """
        if self._co2 is None:  # update if needed
            self.read()
        return self._co2

    @property
    def dew_point(self):
        """ COZIR dew point in Celsius """
        if self._dew_point is None:  # update if needed
            self.read()
        return self._dew_point

    @property
    def humidity(self):
        """ COZIR relative humidity in percent """
        if self._humidity is None:  # update if needed
            self.read()
        return self._humidity

    @property
    def temperature(self):
        """ COZIR temperature in Celsius """
        if self._temperature is None:  # update if needed
            self.read()
        return self._temperature

    def get_measurement(self):
        """ Gets the humidity and temperature """
        self._co2 = None
        self._dew_point = None
        self._humidity = None
        self._temperature = None

        co2 = self.sensor.read_CO2()
        temperature = self.sensor.read_temperature()
        humidity = self.sensor.read_humidity()
        dew_pt = dewpoint(temperature, humidity)

        # Check for conversions
        co2 = convert_units('co2', 'ppm', self.convert_to_unit, co2)
        dew_pt = convert_units('dewpoint', 'celsius', self.convert_to_unit,
                               dew_pt)
        temperature = convert_units('temperature', 'celsius',
                                    self.convert_to_unit, temperature)

        return co2, dew_pt, humidity, temperature

    def read(self):
        """
        Takes a reading from the COZIR and updates the self._co2, self._humidity and
        self._temperature values

        :returns: None on success or 1 on error
        """
        try:
            (self._co2, self._dew_point, self._humidity,
             self._temperature) = self.get_measurement()
            if self._dew_point is not None:
                return  # success - no errors
        except Exception as e:
            self.logger.exception(
                "{cls} raised an exception when taking a reading: "
                "{err}".format(cls=type(self).__name__, err=e))
        return 1
Example #14
0
    help="name or number of the serial port on which the sensor is connected. Examples: '/dev/ttyUSB0' or 'COM3'")
args = parser.parse_args()


log_fname = args.output
if log_fname is None:
    log_time = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
    log_fname = 'cozir_log_{}.csv'.format(log_time)

sleep_duration = args.time # s


### Open the sensor
port =  args.port
# TODO: add a try/except for port opening errors
c = Cozir(port)

with open(log_fname, 'w') as log:
    print('logging to "{}"'.format(log_fname))
    print('logging interval: {} s'.format(sleep_duration))
    log.write('datetime,CO2,Temperature,Humidity\n')
    
    while True:
        co2 = c.read_CO2()
        temp = c.read_temperature()
        humid = c.read_humidity()
        
        t = datetime.now().isoformat()
        line = '{},{:.0f},{:.1f},{:.1f}'.format(t, co2, temp, humid)
        line_units = '{:.0f} ppm, {:.1f} °C, {:.1f} %'.format(co2, temp, humid)
        print(line_units)
Example #15
0
def get_co2_sensor(device):
    return Cozir(device)