Exemplo n.º 1
0
    def get_measurement(self):
        """ Gets the pwm """
        self._frequency = None
        self._pulse_width = None
        self._duty_cycle = None

        pi = self.pigpio.pi()
        if not pi.connected:  # Check if pigpiod is running
            self.logger.error("Could not connect to pigpiod."
                         "Ensure it is running and try again.")
            return None, None, None

        read_pwm = ReadPWM(pi, self.gpio, self.pigpio, self.weighting)
        time.sleep(self.sample_time)
        frequency = convert_units(
            'frequency', 'Hz', self.convert_to_unit,
            read_pwm.frequency())
        pulse_width = int(read_pwm.pulse_width() + 0.5)
        duty_cycle = read_pwm.duty_cycle()
        read_pwm.cancel()
        pi.stop()

        duty_cycle = convert_units(
            'duty_cycle', 'percent', self.convert_to_unit,
            duty_cycle)

        return frequency, pulse_width, duty_cycle
Exemplo n.º 2
0
    def get_measurement(self):
        """ Gets the measurement in units by reading the """
        self._altitude = None
        self._dew_point = None
        self._humidity = None
        self._pressure = None
        self._temperature = None

        temperature = convert_units(
            'temperature', 'C', self.convert_to_unit,
            self.sensor.read_temperature())

        pressure_pa = self.sensor.read_pressure()
        pressure = convert_units(
            'pressure', 'Pa', self.convert_to_unit,
            pressure_pa)

        alt = convert_units(
            'altitude', 'm', self.convert_to_unit,
            altitude(pressure_pa))

        humidity = convert_units(
            'humidity', 'percent', self.convert_to_unit,
            self.sensor.read_humidity())

        dew_pt = convert_units(
            'dewpoint', 'C', self.convert_to_unit,
            calculate_dewpoint(temperature, humidity))

        return alt, dew_pt, humidity, pressure, temperature
    def get_measurement(self):
        """ Measures temperature and humidity """
        # Resetting these values ensures old measurements aren't mistaken for new measurements
        self._dewpoint = None
        self._humidity = None
        self._temperature = None

        dewpoint = None
        humidity = None
        temperature = None

        # Actual input measurement code
        try:
            humidity = self.random.randint(0, 100)
            temperature = self.random.randint(0, 50)
            dewpoint = calculate_dewpoint(temperature, humidity)
        except Exception as msg:
            self.logger.error("Exception: {}".format(msg))

        # Unit conversions
        # A conversion may be specified for each measurement

        # Humidity is returned as %, but may be converted to another unit (e.g. decimal)
        humidity = convert_units('humidity', '%', self.convert_to_unit,
                                 humidity)

        # Temperature is returned as C, but may be converted to another unit (e.g. K, F)
        temperature = convert_units('temperature', 'C', self.convert_to_unit,
                                    temperature)

        # Dewpoint is returned as C, but may be converted to another unit (e.g. K, F)
        dewpoint = convert_units('dewpoint', 'C', self.convert_to_unit,
                                 dewpoint)

        return humidity, temperature, dewpoint
Exemplo n.º 4
0
    def get_measurement(self):
        """ Gets the humidity and temperature """
        self._dew_point = None
        self._humidity = None
        self._temperature = None

        if not self.pi.connected:  # Check if pigpiod is running
            self.logger.error("Could not connect to pigpiod."
                              "Ensure it is running and try again.")
            return None, None, None

        self.htu_reset()
        # wtreg = 0xE6
        # rdreg = 0xE7
        rdtemp = 0xE3
        rdhumi = 0xE5

        handle = self.pi.i2c_open(self.i2c_bus,
                                  self.i2c_address)  # open i2c bus
        self.pi.i2c_write_byte(handle, rdtemp)  # send read temp command
        time.sleep(0.055)  # readings take up to 50ms, lets give it some time
        (_, byte_array) = self.pi.i2c_read_device(handle,
                                                  3)  # vacuum up those bytes
        self.pi.i2c_close(handle)  # close the i2c bus
        t1 = byte_array[0]  # most significant byte msb
        t2 = byte_array[1]  # least significant byte lsb
        temp_reading = (t1 *
                        256) + t2  # combine both bytes into one big integer
        temp_reading = float(temp_reading)
        temperature = (
            (temp_reading / 65536) * 175.72) - 46.85  # formula from datasheet

        handle = self.pi.i2c_open(self.i2c_bus,
                                  self.i2c_address)  # open i2c bus
        self.pi.i2c_write_byte(handle, rdhumi)  # send read humi command
        time.sleep(0.055)  # readings take up to 50ms, lets give it some time
        (_, byte_array) = self.pi.i2c_read_device(handle,
                                                  3)  # vacuum up those bytes
        self.pi.i2c_close(handle)  # close the i2c bus
        h1 = byte_array[0]  # most significant byte msb
        h2 = byte_array[1]  # least significant byte lsb
        humi_reading = (h1 *
                        256) + h2  # combine both bytes into one big integer
        humi_reading = float(humi_reading)
        uncomp_humidity = (
            (humi_reading / 65536) * 125) - 6  # formula from datasheet
        humidity = ((25 - temperature) * -0.15) + uncomp_humidity
        dew_pt = calculate_dewpoint(temperature, humidity)

        # Check for conversions
        dew_pt = convert_units('dewpoint', 'C', self.convert_to_unit, dew_pt)

        temperature = convert_units('temperature', 'C', self.convert_to_unit,
                                    temperature)

        humidity = convert_units('humidity', 'percent', self.convert_to_unit,
                                 humidity)

        return dew_pt, humidity, temperature
Exemplo n.º 5
0
    def get_measurement(self):
        """ Gets the measurement in units by reading the BMP180/085 """
        time.sleep(2)

        temperature = convert_units('temperature', 'C', self.convert_to_unit,
                                    self.bmp.read_temperature())

        pressure = convert_units('pressure', 'Pa', self.convert_to_unit,
                                 self.bmp.read_pressure())

        altitude = convert_units('altitude', 'm', self.convert_to_unit,
                                 self.bmp.read_altitude())

        return temperature, pressure, altitude
Exemplo n.º 6
0
    def get_measurement(self):
        """ Gets the humidity and temperature """
        self._dew_point = None
        self._humidity = None
        self._temperature = None

        dew_point = None
        humidity = None
        temperature = None

        for _ in range(2):
            try:
                # Send temperature measurement command
                # 0xF3(243) NO HOLD master
                self.sht2x.write_byte(self.i2c_address, 0xF3)
                time.sleep(0.5)
                # Read data back, 2 bytes
                # Temp MSB, Temp LSB
                data0 = self.sht2x.read_byte(self.i2c_address)
                data1 = self.sht2x.read_byte(self.i2c_address)
                temperature = -46.85 + (((data0 * 256 + data1) * 175.72) / 65536.0)
                # Send humidity measurement command
                # 0xF5(245) NO HOLD master
                self.sht2x.write_byte(self.i2c_address, 0xF5)
                time.sleep(0.5)
                # Read data back, 2 bytes
                # Humidity MSB, Humidity LSB
                data0 = self.sht2x.read_byte(self.i2c_address)
                data1 = self.sht2x.read_byte(self.i2c_address)
                humidity = -6 + (((data0 * 256 + data1) * 125.0) / 65536.0)
                dew_point = calculate_dewpoint(temperature, humidity)
                return dew_point, humidity, temperature
            except Exception as e:
                self.logger.exception(
                    "Exception when taking a reading: {err}".format(err=e))
            # Send soft reset and try a second read
            self.sht2x.write_byte(self.i2c_address, 0xFE)
            time.sleep(0.1)

        dew_point = convert_units(
            'dewpoint', 'C', self.convert_to_unit, dew_point)

        temperature = convert_units(
            'temperature', 'C', self.convert_to_unit, temperature)

        humidity = convert_units(
            'humidity', 'percent', self.convert_to_unit,
            humidity)

        return dew_point, humidity, temperature
Exemplo n.º 7
0
    def get_measurement(self):
        """ Gets the measurement in units by reading the """
        self._temperature = None
        self._temperature_die = None

        temp = self.sensor.readThermocoupleTemp()
        temp = convert_units(
            'temperature', 'C', self.convert_to_unit, temp)

        temp_die = self.sensor.readJunctionTemp()
        temp_die = convert_units(
            'temperature_die', 'C', self.convert_to_unit, temp_die)

        return temp, temp_die
Exemplo n.º 8
0
    def get_measurement(self):
        """ Gets the measurement in units by reading the """
        self._temperature = None
        self._temperature_die = None

        temp = self.sensor.readTempC()
        temp = convert_units(
            'temperature', 'C', self.convert_to_unit, temp)

        temp_die = self.sensor.readInternalC()
        temp_die = convert_units(
            'temperature_die', 'C', self.convert_to_unit, temp_die)

        return temp, temp_die
Exemplo n.º 9
0
    def get_measurement(self):
        """ Gets the TMP006's temperature in Celsius """
        self._temperature_die = None
        self._temperature_object = None

        self.sensor.begin()

        temperature_die = convert_units('temperature_die', 'C',
                                        self.convert_to_unit,
                                        self.sensor.readDieTempC())

        temperature_object = convert_units('temperature_object', 'C',
                                           self.convert_to_unit,
                                           self.sensor.readObjTempC())

        return temperature_die, temperature_object
Exemplo n.º 10
0
    def math_sum_single(self, measurement_dict):
        (device_id, math_dev_measurement, math_unit, measure_channel,
         measure_unit,
         measure_measurement) = self.return_single_measure_info()

        try:
            return_value = sum_past_seconds(device_id,
                                            measure_unit,
                                            measure_channel,
                                            self.max_measure_age,
                                            measure=measure_measurement)

            if math_dev_measurement.conversion_id:
                return_value = convert_units(
                    math_dev_measurement.conversion_id, return_value)

            if return_value:
                measurement_dict = {
                    math_dev_measurement.channel: {
                        'measurement': measure_measurement,
                        'unit': math_unit,
                        'value': return_value
                    }
                }
            else:
                self.error_not_within_max_age()
        except Exception as msg:
            self.logger.exception("sum_single Error: {err}".format(err=msg))
        return measurement_dict
Exemplo n.º 11
0
    def get_measurement(self):
        """ Gets the DS18B20's temperature in Celsius """
        self._temperature = None
        temperature = None
        n = 2
        for i in range(n):
            try:
                temperature = self.sensor.get_temperature()
                break
            except Exception as e:
                if i == n:
                    self.logger.exception(
                        "{cls} raised an exception when taking a reading: "
                        "{err}".format(cls=type(self).__name__, err=e))
                time.sleep(1)

        if temperature == 85:
            self.logger.error(
                "Measurement returned 85 C, "
                "Indicating an issue communicating with the sensor.")
            return None
        elif temperature is not None and -55 > temperature > 125:
            self.logger.error(
                "Measurement outside the expected range of -55 C to 125 C: "
                "{temp} C".format(temp=self._temperature))
            return None

        temperature = convert_units('temperature', 'C', self.convert_to_unit,
                                    temperature)

        return temperature
Exemplo n.º 12
0
    def get_measurement(self):
        """ Gets the sensor's Electrical Conductivity measurement via UART/I2C """
        self._electrical_conductivity = None
        electrical_conductivity = None

        # Read sensor via UART
        if self.interface == 'UART':
            if self.atlas_sensor_uart.setup:
                lines = self.atlas_sensor_uart.query('R')
                if lines:
                    self.logger.debug("All Lines: {lines}".format(lines=lines))

                    # 'check probe' indicates an error reading the sensor
                    if 'check probe' in lines:
                        self.logger.error('"check probe" returned from sensor')
                    # if a string resembling a float value is returned, this
                    # is out measurement value
                    elif str_is_float(lines[0]):
                        electrical_conductivity = float(lines[0])
                        self.logger.debug('Value[0] is float: {val}'.format(
                            val=electrical_conductivity))
                    else:
                        # During calibration, the sensor is put into
                        # continuous mode, which causes a return of several
                        # values in one string. If the return value does
                        # not represent a float value, it is likely to be a
                        # string of several values. This parses and returns
                        # the first value.
                        if str_is_float(lines[0].split(b'\r')[0]):
                            electrical_conductivity = lines[0].split(b'\r')[0]
                        # Lastly, this is called if the return value cannot
                        # be determined. Watchthe output in the GUI to see
                        # what it is.
                        else:
                            electrical_conductivity = lines[0]
                            self.logger.error(
                                'Value[0] is not float or "check probe": '
                                '{val}'.format(val=electrical_conductivity))
            else:
                self.logger.error('UART device is not set up.'
                                  'Check the log for errors.')

        # Read sensor via I2C
        elif self.interface == 'I2C':
            if self.atlas_sensor_i2c.setup:
                ec_status, ec_str = self.atlas_sensor_i2c.query('R')
                if ec_status == 'error':
                    self.logger.error(
                        "Sensor read unsuccessful: {err}".format(err=ec_str))
                elif ec_status == 'success':
                    electrical_conductivity = float(ec_str)
            else:
                self.logger.error(
                    'I2C device is not set up. Check the log for errors.')

        electrical_conductivity = convert_units('electrical_conductivity',
                                                'μS_cm', self.convert_to_unit,
                                                electrical_conductivity)

        return electrical_conductivity
Exemplo n.º 13
0
    def get_measurement(self):
        """ Gets the MH-Z16's CO2 concentration in ppmv via UART"""
        self._co2 = None
        co2 = None

        if self.interface == 'UART':
            if not self.serial_device:  # Don't measure if device isn't validated
                return None

            self.ser.flushInput()
            time.sleep(1)
            self.ser.write(
                bytearray(
                    [0xff, 0x01, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x79]))
            time.sleep(.01)
            resp = self.ser.read(9)
            if len(resp) != 0:
                high = resp[2]
                low = resp[3]
                co2 = (high * 256) + low

        elif self.interface == 'I2C':
            self.write_register(self.FCR, 0x07)
            self.send(self.cmd_measure)
            try:
                co2 = self.parse(self.receive())
            except Exception:
                co2 = None

        co2 = convert_units('co2', 'ppm', self.convert_to_unit, co2)

        return co2
Exemplo n.º 14
0
    def get_measurement(self, silent=False):
        """ Gets the MH-Z19's CO2 concentration in ppmv via UART"""
        self._co2 = None
        co2 = None

        if not self.serial_device:  # Don't measure if device isn't validated
            return None

        self.ser.flushInput()
        self.ser.write(
            bytearray([0xff, 0x01, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x79]))
        time.sleep(.01)
        resp = self.ser.read(9)

        if resp[0] != 0xff or resp[1] != 0x86:
            self.logger.error("Bad checksum")
        elif len(resp) >= 4:
            high = resp[2]
            low = resp[3]
            co2 = (high * 256) + low
        else:
            self.logger.error("Bad response")

        co2 = convert_units('co2', 'ppm', self.convert_to_unit, co2)

        return co2
Exemplo n.º 15
0
    def get_measurement(self):
        """ Gets the revolutions """
        self._revolutions = None

        pi = self.pigpio.pi()
        if not pi.connected:  # Check if pigpiod is running
            self.logger.error("Could not connect to pigpiod."
                              "Ensure it is running and try again.")
            return None

        read_revolutions = ReadRPM(pi, self.gpio, self.pigpio,
                                   self.rpm_pulses_per_rev, self.weighting)
        time.sleep(self.sample_time)

        rpm = read_revolutions.RPM()
        if rpm:
            rpm = int(rpm + 0.5)

        rpm = convert_units('revolutions', 'RPM', self.convert_to_unit, rpm)

        read_revolutions.cancel()
        pi.stop()

        if rpm:
            return rpm
        elif rpm == 0:
            return 0
        else:
            return None
Exemplo n.º 16
0
    def get_measurement(self):
        """ Gets the measurement in units by reading the """
        self._temperature = None

        temp = self.sensor.readTemp(self.thermocouple_type, self.ref_ohm)
        temp = convert_units('temperature', 'C', self.convert_to_unit, temp)

        return temp
Exemplo n.º 17
0
    def get_measurement(self):
        """ Gets the CO2, VOC, and temperature """
        self._co2 = None
        self._voc = None
        self._temperature = None

        temperature = convert_units('temperature', 'C', self.convert_to_unit,
                                    self.sensor.calculateTemperature())

        if not self.sensor.readData():
            co2 = convert_units('co2', 'ppm', self.convert_to_unit,
                                self.sensor.geteCO2())
            voc = convert_units('voc', 'ppb', self.convert_to_unit,
                                self.sensor.getTVOC())
            return co2, voc, temperature
        else:
            return None, None, None
Exemplo n.º 18
0
    def get_measurement(self):
        """ Gets the free space """
        f = os.statvfs(self.path)
        disk_space = (f.f_bsize * f.f_bavail) / 1000000.0

        disk_space = convert_units('disk_space', 'MB', self.convert_to_unit,
                                   disk_space)

        return disk_space
Exemplo n.º 19
0
    def get_measurement(self):
        """ Gets the light, moisture, and temperature """
        self._lux = None
        self._moisture = None
        self._temperature = None

        lux = self.filter_average('lux', measurement=self.light())
        lux = convert_units(
            'light', 'lux', self.convert_to_unit,
            lux)

        moisture = self.moist()

        temperature = convert_units(
            'temperature', 'C', self.convert_to_unit,
            self.temp() / 10.0)

        return lux, moisture, temperature
Exemplo n.º 20
0
 def get_measurement(self):
     """ Calls the vcgencmd in a subprocess and reads the GPU temperature """
     gputempstr = subprocess.check_output(
         ('/opt/vc/bin/vcgencmd',
          'measure_temp'))  # example output: temp=42.8'C
     temperature = float(gputempstr.split('=')[1].split("'")[0])
     temperature = convert_units('temperature', 'C', self.convert_to_unit,
                                 temperature)
     return temperature
Exemplo n.º 21
0
    def get_measurement(self):
        """ Gets the TSL2591's lux """
        full, ir = self.tsl.get_full_luminosity()  # read raw values (full spectrum and ir spectrum)

        # convert raw values to lux (and convert to user-selected unit, if necessary)
        lux = convert_units(
            'light', 'lux', self.convert_to_unit,
            self.tsl.calculate_lux(full, ir))

        return lux
Exemplo n.º 22
0
    def get_measurement(self):
        """ Gets the humidity and temperature """
        self._dew_point = None
        self._humidity = None
        self._temperature = None

        temperature = convert_units('temperature', 'C', self.convert_to_unit,
                                    self.sht_sensor.read_t())

        humidity = self.sht_sensor.read_rh()

        dew_point = self.sht_sensor.read_dew_point(temperature, humidity)
        dew_point = convert_units('dewpoint', 'C', self.convert_to_unit,
                                  dew_point)

        humidity = convert_units('humidity', 'percent', self.convert_to_unit,
                                 humidity)

        return dew_point, humidity, temperature
Exemplo n.º 23
0
    def get_measurement(self):
        """ Gets the measurement in units by reading the """
        self._altitude = None
        self._pressure = None
        self._temperature = None

        temperature = convert_units(
            'temperature', 'C', self.convert_to_unit,
            self.read_temperature())

        pressure_pa = self.read_pressure()
        pressure = convert_units(
            'pressure', 'Pa', self.convert_to_unit,
            pressure_pa)

        alt = convert_units(
            'altitude', 'm', self.convert_to_unit,
            altitude(pressure_pa))

        return temperature, pressure, alt
Exemplo n.º 24
0
    def get_measurement(self):
        """ Gets the humidity and temperature """
        self._dew_point = None
        self._humidity = None
        self._temperature = None

        temperature = self.read_temperature()
        humidity = self.read_humidity()
        dew_pt = calculate_dewpoint(temperature, humidity)

        # Check for conversions
        dew_pt = convert_units('dewpoint', 'C', self.convert_to_unit, dew_pt)

        temperature = convert_units('temperature', 'C', self.convert_to_unit,
                                    temperature)

        humidity = convert_units('humidity', 'percent', self.convert_to_unit,
                                 humidity)

        return dew_pt, humidity, temperature
Exemplo n.º 25
0
 def is_measurement_unit(self, unit_from, unit_to, value):
     """ Converts value from one measurement to another """
     if unit_from != unit_to:
         for each_conv in db_retrieve_table_daemon(Conversion, entry='all'):
             if (each_conv.convert_unit_from == unit_from
                     and each_conv.convert_unit_to == unit_to):
                 return_value = convert_units(each_conv.unique_id, value)
                 return return_value, 'success'
             else:
                 self.logger.error(
                     "Could not find conversion for unit "
                     "{unit_from} to {unit_to}".format(unit_from=unit_from,
                                                       unit_to=unit_to))
                 return None, 'error'
Exemplo n.º 26
0
    def get_measurement(self):
        """ Gets the measurement in units by reading resource """
        self._disk_space = None
        disk_space = None

        try:
            disk_space = resource.getrusage(
                resource.RUSAGE_SELF).ru_maxrss / float(1000)
        except Exception:
            pass

        disk_space = convert_units('disk_space', 'MB', self.convert_to_unit,
                                   disk_space)

        return disk_space
Exemplo n.º 27
0
    def get_measurement(self):
        """ Gets the BH1750's lux """
        self._lux = None

        if self.resolution == 0:
            lux = self.measure_low_res()
        elif self.resolution == 1:
            lux = self.measure_high_res()
        elif self.resolution == 2:
            lux = self.measure_high_res2()
        else:
            return None

        lux = convert_units('light', 'lux', self.convert_to_unit, lux)

        return lux
Exemplo n.º 28
0
    def get_measurement(self):
        """ Gets the humidity and temperature """
        self._dew_point = None
        self._humidity = None
        self._temperature = None

        # Ensure if the power pin turns off, it is turned back on
        if (self.power_output_id and db_retrieve_table_daemon(
                Output, unique_id=self.power_output_id)
                and self.control.output_state(self.power_output_id) == 'off'):
            self.logger.error(
                'Sensor power output {rel} detected as being off. '
                'Turning on.'.format(rel=self.power_output_id))
            self.start_sensor()
            time.sleep(2)

        # Try twice to get measurement. This prevents an anomaly where
        # the first measurement fails if the sensor has just been powered
        # for the first time.
        for _ in range(2):
            dew_point, humidity, temperature = self.return_measurements()
            if dew_point is not None:
                dew_point = convert_units('dewpoint', 'C',
                                          self.convert_to_unit, dew_point)
                temperature = convert_units('temperature', 'C',
                                            self.convert_to_unit, temperature)
                humidity = convert_units('humidity', 'percent',
                                         self.convert_to_unit, humidity)
                return dew_point, humidity, temperature  # success - no errors
            time.sleep(2)

        # Measurement failure, power cycle the sensor (if enabled)
        # Then try two more times to get a measurement
        if self.power_output_id:
            self.stop_sensor()
            time.sleep(2)
            self.start_sensor()
            for _ in range(2):
                dew_point, humidity, temperature = self.return_measurements()
                if dew_point is not None:
                    dew_point = convert_units('dewpoint', 'C',
                                              self.convert_to_unit, dew_point)
                    temperature = convert_units('temperature', 'C',
                                                self.convert_to_unit,
                                                temperature)
                    humidity = convert_units('humidity', 'percent',
                                             self.convert_to_unit, humidity)
                    return dew_point, humidity, temperature  # success
                time.sleep(2)

        self.logger.debug("Could not acquire a measurement")
        return None, None, None
Exemplo n.º 29
0
    def get_measurement(self):
        """ Gets the Raspberry pi's temperature in Celsius by reading the temp file and div by 1000 """
        # import psutil
        # import resource
        # open_files_count = 0
        # for proc in psutil.process_iter():
        #     if proc.open_files():
        #         open_files_count += 1
        # self.logger.info("Open files: {of}".format(of=open_files_count))
        # soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
        # self.logger.info("LIMIT: Soft: {sft}, Hard: {hrd}".format(sft=soft, hrd=hard))
        with open('/sys/class/thermal/thermal_zone0/temp') as cpu_temp_file:

            temperature = convert_units('temperature', 'C',
                                        self.convert_to_unit,
                                        float(cpu_temp_file.read()) / 1000)

            return temperature
Exemplo n.º 30
0
    def get_measurement(self):
        """ Gets the DS18S20's temperature in Celsius """
        self._temperature = None
        temperature = None
        n = 2
        for i in range(n):
            try:
                temperature = self.sensor.get_temperature()
                break
            except Exception as e:
                if i == n:
                    self.logger.exception(
                        "{cls} raised an exception when taking a reading: "
                        "{err}".format(cls=type(self).__name__, err=e))
                time.sleep(1)

        temperature = convert_units('temperature', 'C', self.convert_to_unit,
                                    temperature)

        return temperature
Exemplo n.º 31
0
    def calculate_math(self):
        measurement_dict = {}

        if self.math_type == 'average':

            device_measurement = self.device_measurements.filter(
                DeviceMeasurements.channel == 0).first()

            if device_measurement:
                conversion = db_retrieve_table_daemon(
                    Conversion, unique_id=device_measurement.conversion_id)
            else:
                conversion = None
            channel, unit, measurement = return_measurement_info(
                device_measurement, conversion)

            success, measure = self.get_measurements_from_str(self.inputs)
            if success:
                average = float(sum(measure) / float(len(measure)))

                measurement_dict = {
                    channel: {
                        'measurement': measurement,
                        'unit': unit,
                        'value': average
                    }
                }
            elif measure:
                self.logger.error(measure)
            else:
                self.error_not_within_max_age()

        elif self.math_type == 'average_single':

            device_id = self.inputs.split(',')[0]
            measurement_id = self.inputs.split(',')[1]

            device_measurement = db_retrieve_table_daemon(
                DeviceMeasurements, unique_id=measurement_id)
            if device_measurement:
                conversion = db_retrieve_table_daemon(
                    Conversion, unique_id=device_measurement.conversion_id)
            else:
                conversion = None
            channel, unit, measurement = return_measurement_info(
                device_measurement, conversion)

            try:
                last_measurements = read_past_influxdb(
                    device_id,
                    unit,
                    measurement,
                    channel,
                    self.max_measure_age)

                if last_measurements:
                    measure_list = []
                    for each_set in last_measurements:
                        if len(each_set) == 2:
                            measure_list.append(each_set[1])
                    average = sum(measure_list) / float(len(measure_list))

                    measurement_dict = {
                        channel: {
                            'measurement': measurement,
                            'unit': unit,
                            'value': average
                        }
                    }
                else:
                    self.error_not_within_max_age()
            except Exception as msg:
                self.logger.exception("average_single Error: {err}".format(err=msg))

        elif self.math_type == 'difference':

            device_measurement = self.device_measurements.filter(
                DeviceMeasurements.channel == 0).first()
            if device_measurement:
                conversion = db_retrieve_table_daemon(
                    Conversion, unique_id=device_measurement.conversion_id)
            else:
                conversion = None
            channel, unit, measurement = return_measurement_info(
                device_measurement, conversion)

            success, measure = self.get_measurements_from_str(self.inputs)
            if success:
                if self.difference_reverse_order:
                    difference = measure[1] - measure[0]
                else:
                    difference = measure[0] - measure[1]
                if self.difference_absolute:
                    difference = abs(difference)

                measurement_dict = {
                    channel: {
                        'measurement': measurement,
                        'unit': unit,
                        'value': difference
                    }
                }
            elif measure:
                self.logger.error(measure)
            else:
                self.error_not_within_max_age()

        elif self.math_type == 'equation':

            device_measurement = self.device_measurements.filter(
                DeviceMeasurements.channel == 0).first()
            if device_measurement:
                conversion = db_retrieve_table_daemon(
                    Conversion, unique_id=device_measurement.conversion_id)
            else:
                conversion = None
            channel, unit, measurement = return_measurement_info(
                device_measurement, conversion)

            success, measure = self.get_measurements_from_str(self.inputs)
            if success:
                replaced_str = self.equation.replace('x', str(measure[0]))
                equation_output = eval(replaced_str)

                measurement_dict = {
                    channel: {
                        'measurement': measurement,
                        'unit': unit,
                        'value': float(equation_output)
                    }
                }
            elif measure:
                self.logger.error(measure)
            else:
                self.error_not_within_max_age()

        elif self.math_type == 'redundancy':
            list_order = self.order_of_use.split(';')
            measurement_success = False

            for each_id_measurement_id in list_order:
                device_id = each_id_measurement_id.split(',')[0]
                measurement_id = each_id_measurement_id.split(',')[1]

                device_measurement = self.device_measurements.filter(
                    DeviceMeasurements.channel == 0).first()
                if device_measurement:
                    conversion = db_retrieve_table_daemon(
                        Conversion, unique_id=device_measurement.conversion_id)
                else:
                    conversion = None
                channel, unit, measurement = return_measurement_info(
                    device_measurement, conversion)

                try:
                    success_measure, measure = self.get_measurements_from_id(
                        device_id, measurement_id)

                    if success_measure:
                        measurement_dict = {
                            channel: {
                                'measurement': measurement,
                                'unit': unit,
                                'value': float(measure[1]),
                                'timestamp': measure[0],
                            }
                        }
                        measurement_success = True
                        break

                except Exception as msg:
                    self.logger.exception("redundancy Error: {err}".format(err=msg))

            if not measurement_success:
                self.error_not_within_max_age()

        elif self.math_type == 'statistics':

            success, measure = self.get_measurements_from_str(self.inputs)
            if success:
                # Perform some math
                stat_mean = float(sum(measure) / float(len(measure)))
                stat_median = median(measure)
                stat_minimum = min(measure)
                stat_maximum = max(measure)
                stdev_ = stdev(measure)
                stdev_mean_upper = stat_mean + stdev_
                stdev_mean_lower = stat_mean - stdev_

                list_measurement = [
                    stat_mean,
                    stat_median,
                    stat_minimum,
                    stat_maximum,
                    stdev_,
                    stdev_mean_upper,
                    stdev_mean_lower
                ]

                for each_measurement in self.device_measurements.all():
                    conversion = db_retrieve_table_daemon(
                        Conversion, unique_id=each_measurement.conversion_id)
                    channel, unit, measurement = return_measurement_info(
                        each_measurement, conversion)

                    measurement_dict[channel] = {
                            'measurement': measurement,
                            'unit': unit,
                            'value': list_measurement[channel]
                    }

            elif measure:
                self.logger.error(measure)
            else:
                self.error_not_within_max_age()

        elif self.math_type == 'verification':

            device_measurement = self.device_measurements.filter(
                DeviceMeasurements.channel == 0).first()
            if device_measurement:
                conversion = db_retrieve_table_daemon(
                    Conversion, unique_id=device_measurement.conversion_id)
            else:
                conversion = None
            channel, unit, measurement = return_measurement_info(
                device_measurement, conversion)

            success, measure = self.get_measurements_from_str(self.inputs)
            if (success and
                    max(measure) - min(measure) <
                    self.max_difference):
                difference = max(measure) - min(measure)

                measurement_dict = {
                    channel: {
                        'measurement': measurement,
                        'unit': unit,
                        'value': difference
                    }
                }
            elif measure:
                self.logger.error(measure)
            else:
                self.error_not_within_max_age()

        elif self.math_type == 'humidity':

            pressure_pa = 101325
            critical_error = False

            if self.pressure_pa_id and self.pressure_pa_measure_id:
                success_pa, pressure = self.get_measurements_from_id(
                    self.pressure_pa_id, self.pressure_pa_measure_id)
                if success_pa:
                    pressure_pa = int(pressure[1])
                    # Pressure must be in Pa, convert if not

                    if db_retrieve_table_daemon(DeviceMeasurements, unique_id=self.pressure_pa_measure_id):
                        measurement = db_retrieve_table_daemon(DeviceMeasurements, unique_id=self.pressure_pa_measure_id)
                    else:
                        self.logger.error("Could not find pressure measurement")
                        measurement = None
                        critical_error = True

                    if measurement and measurement.unit != 'Pa':
                        for each_conv in db_retrieve_table_daemon(Conversion, entry='all'):
                            if (each_conv.convert_unit_from == measurement.unit and
                                    each_conv.convert_unit_to == 'Pa'):
                                pressure_pa = convert_units(
                                    each_conv.unique_id, pressure_pa)
                            else:
                                self.logger.error(
                                    "Could not find conversion for unit "
                                    "{unit} to Pa (Pascals)".format(
                                        unit=measurement.unit))
                                critical_error = True

            success_dbt, dry_bulb_t = self.get_measurements_from_id(
                self.dry_bulb_t_id, self.dry_bulb_t_measure_id)
            success_wbt, wet_bulb_t = self.get_measurements_from_id(
                self.wet_bulb_t_id, self.wet_bulb_t_measure_id)

            if success_dbt and success_wbt:
                dbt_kelvin = float(dry_bulb_t[1])
                wbt_kelvin = float(wet_bulb_t[1])

                if db_retrieve_table_daemon(DeviceMeasurements, unique_id=self.dry_bulb_t_measure_id):
                    measurement = db_retrieve_table_daemon(DeviceMeasurements, unique_id=self.dry_bulb_t_measure_id)
                else:
                    self.logger.error("Could not find pressure measurement")
                    measurement = None
                    critical_error = True

                if measurement and measurement.unit != 'K':
                    conversion_found = False
                    for each_conv in db_retrieve_table_daemon(Conversion, entry='all'):
                        if (each_conv.convert_unit_from == measurement.unit and
                                each_conv.convert_unit_to == 'K'):
                            dbt_kelvin = convert_units(
                                each_conv.unique_id, dbt_kelvin)
                            conversion_found = True
                    if not conversion_found:
                        self.logger.error(
                            "Could not find conversion for unit "
                            "{unit} to K (Kelvin)".format(
                                unit=measurement.unit))
                        critical_error = True

                if db_retrieve_table_daemon(DeviceMeasurements, unique_id=self.dry_bulb_t_measure_id):
                    measurement = db_retrieve_table_daemon(DeviceMeasurements, unique_id=self.dry_bulb_t_measure_id)
                else:
                    self.logger.error("Could not find pressure measurement")
                    measurement = None
                    critical_error = True

                if measurement and measurement.unit != 'K':
                    conversion_found = False
                    for each_conv in db_retrieve_table_daemon(Conversion, entry='all'):
                        if (each_conv.convert_unit_from == measurement.unit and
                                each_conv.convert_unit_to == 'K'):
                            wbt_kelvin = convert_units(
                                each_conv.unique_id, wbt_kelvin)
                            conversion_found = True
                    if not conversion_found:
                        self.logger.error(
                            "Could not find conversion for unit "
                            "{unit} to K (Kelvin)".format(
                                unit=measurement.unit))
                        critical_error = True

                # Convert temperatures to Kelvin (already done above)
                # dbt_kelvin = celsius_to_kelvin(dry_bulb_t_c)
                # wbt_kelvin = celsius_to_kelvin(wet_bulb_t_c)
                psypi = None

                try:
                    if not critical_error:
                        psypi = SI.state(
                            "DBT", dbt_kelvin, "WBT", wbt_kelvin, pressure_pa)
                    else:
                        self.logger.error(
                            "One or more critical errors prevented the "
                            "humidity from being calculated")
                except TypeError as err:
                    self.logger.error("TypeError: {msg}".format(msg=err))

                if psypi:
                    percent_relative_humidity = psypi[2] * 100

                    # Ensure percent humidity stays within 0 - 100 % range
                    if percent_relative_humidity > 100:
                        percent_relative_humidity = 100
                    elif percent_relative_humidity < 0:
                        percent_relative_humidity = 0

                    # Dry bulb temperature: psypi[0])
                    # Wet bulb temperature: psypi[5])

                    specific_enthalpy = float(psypi[1])
                    humidity = float(percent_relative_humidity)
                    specific_volume = float(psypi[3])
                    humidity_ratio = float(psypi[4])

                    list_measurement = [
                        specific_enthalpy,
                        humidity,
                        specific_volume,
                        humidity_ratio
                    ]

                    for each_measurement in self.device_measurements.all():
                        conversion = db_retrieve_table_daemon(
                            Conversion, unique_id=each_measurement.conversion_id)
                        channel, unit, measurement = return_measurement_info(
                            each_measurement, conversion)

                        measurement_dict[channel] = {
                            'measurement': measurement,
                            'unit': unit,
                            'value': list_measurement[channel]
                        }
            else:
                self.error_not_within_max_age()

        elif self.math_type == 'vapor_pressure_deficit':

            vpd_pa = None
            critical_error = False

            success_dbt, temperature = self.get_measurements_from_id(
                self.unique_id_1, self.unique_measurement_id_1)
            success_wbt, humidity = self.get_measurements_from_id(
                self.unique_id_2, self.unique_measurement_id_2)

            if success_dbt and success_wbt:
                vpd_temperature_celsius = float(temperature[1])
                vpd_humidity_percent = float(humidity[1])

                if db_retrieve_table_daemon(
                        DeviceMeasurements,
                        unique_id=self.unique_measurement_id_1):
                    measurement = db_retrieve_table_daemon(
                        DeviceMeasurements,
                        unique_id=self.unique_measurement_id_1)
                else:
                    self.logger.error("Could not find temperature measurement")
                    measurement = None
                    critical_error = True

                if measurement and measurement.unit != 'C':
                    conversion_found = False
                    for each_conv in db_retrieve_table_daemon(Conversion, entry='all'):
                        if (each_conv.convert_unit_from == measurement.unit and
                                each_conv.convert_unit_to == 'C'):
                            vpd_temperature_celsius = convert_units(
                                each_conv.unique_id, vpd_temperature_celsius)
                            conversion_found = True
                    if not conversion_found:
                        self.logger.error(
                            "Could not find conversion for unit "
                            "{unit} to C (Celsius)".format(
                                unit=measurement.unit))
                        critical_error = True

                if db_retrieve_table_daemon(
                        DeviceMeasurements,
                        unique_id=self.unique_measurement_id_2):
                    measurement = db_retrieve_table_daemon(
                        DeviceMeasurements,
                        unique_id=self.unique_measurement_id_2)
                else:
                    self.logger.error("Could not find humidity measurement")
                    measurement = None
                    critical_error = True

                if measurement and measurement.unit != 'percent':
                    conversion_found = False
                    for each_conv in db_retrieve_table_daemon(Conversion, entry='all'):
                        if (each_conv.convert_unit_from == measurement.unit and
                                each_conv.convert_unit_to == 'percent'):
                            vpd_humidity_percent = convert_units(
                                each_conv.unique_id, vpd_humidity_percent)
                            conversion_found = True
                    if not conversion_found:
                        self.logger.error(
                            "Could not find conversion for unit "
                            "{unit} to percent (%)".format(
                                unit=measurement.unit))
                        critical_error = True

                try:
                    if not critical_error:
                        vpd_pa = calculate_vapor_pressure_deficit(
                            vpd_temperature_celsius, vpd_humidity_percent)
                    else:
                        self.logger.error(
                            "One or more critical errors prevented the "
                            "vapor pressure deficit from being calculated")
                except TypeError as err:
                    self.logger.error("TypeError: {msg}".format(msg=err))

                if vpd_pa:
                    measure = self.device_measurements.first()
                    conversion = db_retrieve_table_daemon(
                        Conversion, unique_id=measure.conversion_id)
                    channel, unit, measurement = return_measurement_info(
                        measure, conversion)

                    measurement_dict[channel] = {
                        'measurement': measurement,
                        'unit': unit,
                        'value': vpd_pa
                    }
            else:
                self.error_not_within_max_age()

        else:
            self.logger.error("Unknown math type: {type}".format(type=self.math_type))

        # Finally, add measurements to influxdb
        add_measurements_influxdb(self.unique_id, measurement_dict)