예제 #1
0
class Window(QtGui.QWidget):
    qtcb_temperature = QtCore.pyqtSignal(int)

    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.button = QtGui.QPushButton('Refresh', self)
        self.button.clicked.connect(self.handle_button)
        self.label = QtGui.QLabel('TBD')
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.button)
        layout.addWidget(self.label)

        self.ipcon = IPConnection()
        self.temperature = Temperature(UID_TEMPERATURE, self.ipcon)
        self.ipcon.connect(HOST, PORT)

        # We send the callback through the Qt signal/slot
        # system to make sure that we can change the label
        self.qtcb_temperature.connect(self.cb_temperature)
        self.temperature.register_callback(Temperature.CALLBACK_TEMPERATURE, self.qtcb_temperature.emit)

        # Refresh every second
        self.temperature.set_temperature_callback_period(1000)
        
        # Refresh once on startup
        self.handle_button()

    # Refresh by hand
    def handle_button(self):
        self.cb_temperature(self.temperature.get_temperature())

    def cb_temperature(self, temperature):
        # Show temperature
        self.label.setText(u"Temperature: {0} °C".format(temperature/100.0))
예제 #2
0
class Window(QtGui.QWidget):
    qtcb_temperature = QtCore.pyqtSignal(int)

    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.button = QtGui.QPushButton('Refresh', self)
        self.button.clicked.connect(self.handle_button)
        self.label = QtGui.QLabel('TBD')
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.button)
        layout.addWidget(self.label)

        self.ipcon = IPConnection()
        self.temperature = Temperature(UID_TEMPERATURE, self.ipcon)
        self.ipcon.connect(HOST, PORT)

        # We send the callback through the Qt signal/slot
        # system to make sure that we can change the label
        self.qtcb_temperature.connect(self.cb_temperature)
        self.temperature.register_callback(Temperature.CALLBACK_TEMPERATURE,
                                           self.qtcb_temperature.emit)

        # Refresh every second
        self.temperature.set_temperature_callback_period(1000)

        # Refresh once on startup
        self.handle_button()

    # Refresh by hand
    def handle_button(self):
        self.cb_temperature(self.temperature.get_temperature())

    def cb_temperature(self, temperature):
        # Show temperature
        self.label.setText(u"Temperature: {0} °C".format(temperature / 100.0))
def temperature(connection, table):
    ipcon = IPConnection()
    t = Temperature(TEMPERATURE_UID, ipcon)
    ipcon.connect(HOST, PORT)
    value = t.get_temperature() / 100.0
    insert(connection, table, time.time(), value)
    ipcon.disconnect()
예제 #4
0
class BrickletTemperature:
    _QUOTIENT = 100.0

    def __init__(self, uid, connection, logging_daemon, queue, value=0.0, trigger_difference=0.1):
        self._bricklet = Temperature(uid, connection)
        self._value = value
        self._value_old = value
        self.trigger_difference = trigger_difference
        self._rising = False
        self._falling = False
        self.uid = uid
        self._logging_daemon = logging_daemon
        self._queue = queue
        self._logging_daemon.info('Tinkerforge ... Temperature-Bricklet UID "%s" initialisiert' % uid)

    def set_callback(self, timeframe=5000):
        self._bricklet.set_temperature_callback_period(timeframe)
        self._bricklet.register_callback(self._bricklet.CALLBACK_TEMPERATURE, self._changed)
        self._logging_daemon.debug('Tinkerforge ... Temperature-Bricklet UID "%s" Callback gesetzt' % self.uid)

    def read(self):
        return self._bricklet.get_temperature() / self._QUOTIENT

    def read_rising(self):
        return self._rising

    def read_falling(self):
        return self._falling

    def _changed(self, tmp_value):
        tmp_value = (tmp_value / self._QUOTIENT)
        if abs(self._value - tmp_value) >= self.trigger_difference:
            tmp_value = (tmp_value / self._QUOTIENT)
        if abs(self._value - tmp_value) >= self.trigger_difference:
            if tmp_value > self._value_old:
                self._rising = True
                self._falling = False
            elif tmp_value < self._value_old:
                self._rising = False
                self._falling = True
            self._logging_daemon.debug(
                'Tinkerforge ... Temperature-Bricklet UID "%s" , Neu = %f , Alt = %f , rising = %s , falling = %s' % (
                    self.uid, tmp_value, self._value_old, self._rising, self._falling))
            self._value_old = tmp_value
            self._value = tmp_value
            tmp_json = json.dumps(["send_changed_data", self.uid, "sensor", "temperature", self._value])
            for consumer in self._queue:
                consumer(tmp_json)
                self._logging_daemon.info(
                    'Tinkerforge ... Temperature-Bricklet UID "%s" , neuer Wert %f -> SocketServer Warteschlange ' % (
                        self.uid, self._value))

    temperature = property(read)
    rising = property(read_rising)
    falling = property(read_falling)
예제 #5
0
파일: index.py 프로젝트: qidouhai/doc-2
def index():
    ipcon = IPConnection() # Create IP connection
    t = Temperature(UID, ipcon) # Create device object

    ipcon.connect(HOST, PORT) # Connect to brickd
    # Don't use device before ipcon is connected

    # Get current temperature (unit is °C/100)
    temperature = t.get_temperature()/100.0

    ipcon.disconnect()
    return PAGE.format(temperature)
예제 #6
0
파일: weather.py 프로젝트: RaphaelVogel/ha2
def read_data(fake=None):
    """ Reads data from all weather sensors and returns it as Dictionary.
        In case of an error or outlier None is returned"""
    if fake:
        return weather_data

    try:
        ipcon = IPConnection()
        temp_bricklet = Temperature('qnk', ipcon)
        humidity_bricklet = Humidity('nLC', ipcon)
        barometer_bricklet = Barometer('k5g', ipcon)
        ipcon.connect(cfg['weather']['host'], int(cfg['weather']['port']))
        temp_bricklet.set_i2c_mode(Temperature.I2C_MODE_SLOW)

        temp = temp_bricklet.get_temperature() / 100.0
        if 45 < temp < -30:
            weather_data['temperature'] = None
            logger.warn(
                'Got temperature value of %s Grade which is out of range' %
                temp)
        else:
            weather_data['temperature'] = temp

        humidity = humidity_bricklet.get_humidity() / 10.0
        if humidity < 5:
            weather_data['humidity'] = None
            logger.warn('Got humidity value of %s RH which is out of range' %
                        humidity)
        else:
            weather_data['humidity'] = humidity

        pressure = barometer_bricklet.get_air_pressure() / 1000.0
        if 1080 < pressure < 930:
            weather_data['pressure'] = None
            logger.warn('Got pressure value of %s mbar which is out of range' %
                        pressure)
        else:
            weather_data['pressure'] = pressure

        ipcon.disconnect()
        return weather_data

    except Exception as e:
        logger.error('Cloud not connect to weather sensors: %s' % str(e))
        return
예제 #7
0
def read_data():
    try:
        ipcon = IPConnection()
        temp_bricklet = Temperature('qnk', ipcon)
        humidity_bricklet = Humidity('nLC', ipcon)
        barometer_bricklet = Barometer('k5g', ipcon)
        ipcon.connect(cfg['weather']['host'], int(cfg['weather']['port']))
        temp_bricklet.set_i2c_mode(Temperature.I2C_MODE_SLOW)

        temp = temp_bricklet.get_temperature() / 100.0
        if 45 < temp < -30:
            weather_data['temperature'] = None
            logger.warn('Got temperature value of %s Grade which is out of range' % temp)
        else:
            weather_data['temperature'] = temp

        humidity = humidity_bricklet.get_humidity() / 10.0
        if humidity < 5:
            weather_data['humidity'] = None
            logger.warn('Got humidity value of %s RH which is out of range' % humidity)
        else:
            weather_data['humidity'] = humidity

        pressure = barometer_bricklet.get_air_pressure() / 1000.0
        if 1090 < pressure < 920:
            weather_data['pressure'] = None
            logger.warn('Got pressure value of %s mbar which is out of range' % pressure)
        else:
            weather_data['pressure'] = pressure

        ipcon.disconnect()
        return weather_data

    except Exception as e:
        logger.error('Cloud not connect to weather sensors: %s' % str(e))
        return
class readTFsensors:

    def __init__(self):
        self.tmpHW = None
        self.tmpFR = None
        self.tmpMain = None
        self.tmpHWval = 0
        self.tmpFRval = 0
        self.tmpMainval = 0

        # Create IP Connection
        self.ipcon = IPConnection() 

        # Register IP Connection callbacks
        self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, self.cb_enumerate)
        self.ipcon.register_callback(IPConnection.CALLBACK_CONNECTED, self.cb_connected)

        # Connect to brickd, will trigger cb_connected
        self.ipcon.connect( HOST, PORT ) 

        self.ipcon.enumerate()
        
        # wait until all values are being received
        Logger.debug('waiting for all sensors to send values ...')
        while self.tmpHWval==0 or self.tmpFRval==0 or self.tmpMainval==0:
            now = round( datetime.datetime.timestamp(datetime.datetime.now()) ) 
            Logger.debug( str(now) + ' (HW, FR, main) ' + str(self.tmpHWval)+', '+str(self.tmpFRval)+', '+str(self.tmpMainval) )
            time.sleep(15)               # wait 15 seconds
        Logger.debug( 'all sensors found: (HW, FR, main)' + str(self.tmpHWval)+', '+str(self.tmpFRval)+', '+str(self.tmpMainval) )    
        
        # loop to check if source code was changed, 
        # then exit the python program in order to get it restarted by the shell script
        while True:
            time.sleep(120)               # wait 2 minutes
            # check if script source code has changed
            newScrChgDate = os.path.getmtime(__file__)
            if ( scriptChangeDate != newScrChgDate ):
                Logger.info("Source code changed, (ending script). Old: "+str(scriptChangeDate) + ", New: " + str(newScrChgDate) )
                sys.exit(9)  # means 'reload and restart'
                
            # check if debugging is requested
            if os.path.isfile('debug_off'):
                Logger.setLevel(logging.INFO) 
                
            # check if debugging is requested
            if os.path.isfile('debug_on'):
                Logger.setLevel(logging.DEBUG) 
                
        
    # Callback updates temperature 
    # - for heatwater temperature
    def cb_tempHW(self, temperature):   
        self.tmpHWval = temperature/100.0
        writeSensFile("HW", self.tmpHWval, self.tmpHWval, self.tmpFRval, self.tmpMainval)
    # - for front room temperature
    def cb_tempFR( self, temperature):
        self.tmpFRval  = temperature/100.0
        writeSensFile("FR", self.tmpFRval, self.tmpHWval, self.tmpFRval, self.tmpMainval)
    # - for main room temperature
    def cb_tempMain(self, temperature):
        self.tmpMainval = temperature/100.0
        writeSensFile("Main", self.tmpMainval, self.tmpHWval, self.tmpFRval, self.tmpMainval)


    # Callback handles device connections and configures possibly lost 
    # configuration of lcd and temperature callbacks, backlight etc.
    def cb_enumerate(self, uid, connected_uid, position, hardware_version, firmware_version, device_identifier, enumeration_type):
        if enumeration_type == IPConnection.ENUMERATION_TYPE_CONNECTED or \
           enumeration_type == IPConnection.ENUMERATION_TYPE_AVAILABLE:
                
            # Enumeration is for Temperature Bricklets
            if device_identifier == Temperature.DEVICE_IDENTIFIER:
                # Create individual temperature device objects for each sensor
                if uid==HW_ID:
                    self.tmpHW = Temperature(uid, self.ipcon) 
                    self.tmpHWval = self.tmpHW.get_temperature()/100.0    # read initial value
                    writeSensFile("HW", self.tmpHWval, self.tmpHWval, self.tmpFRval, self.tmpMainval)
                    self.tmpHW.register_callback( self.tmpHW.CALLBACK_TEMPERATURE, self.cb_tempHW )
                    self.tmpHW.set_temperature_callback_period(500)
                elif uid==FR_ID:
                    self.tmpFR = Temperature(uid, self.ipcon) 
                    self.tmpFRval = self.tmpFR.get_temperature()/100.0    # read initial value
                    writeSensFile("FR", self.tmpFRval, self.tmpHWval, self.tmpFRval, self.tmpMainval)
                    self.tmpFR.register_callback( self.tmpFR.CALLBACK_TEMPERATURE, self.cb_tempFR )
                    self.tmpFR.set_temperature_callback_period(500)
                elif uid==MAIN_ID:
                    self.tmpMain = Temperature(uid, self.ipcon) 
                    self.tmpMainval = self.tmpMain.get_temperature()/100.0    # read initial value
                    writeSensFile("Main", self.tmpMainval, self.tmpHWval, self.tmpFRval, self.tmpMainval)
                    self.tmpMain.register_callback( self.tmpMain.CALLBACK_TEMPERATURE, self.cb_tempMain )
                    self.tmpMain.set_temperature_callback_period(500)

    # Callback handles reconnection of IP Connection
    def cb_connected(self, connected_reason):
        # Enumerate devices again. If we reconnected, the Bricks/Bricklets
        # may have been offline and the configuration may be lost.
        # In this case we don't care for the reason of the connection
        self.ipcon.enumerate()
예제 #9
0
class BrickletTemperature:
    _QUOTIENT = 100.0

    def __init__(self,
                 uid,
                 connection,
                 logging_daemon,
                 queue,
                 value=0.0,
                 trigger_difference=0.1):
        self._bricklet = Temperature(uid, connection)
        self._value = value
        self._value_old = value
        self.trigger_difference = trigger_difference
        self._rising = False
        self._falling = False
        self.uid = uid
        self._logging_daemon = logging_daemon
        self._queue = queue
        self._logging_daemon.info(
            'Tinkerforge ... Temperature-Bricklet UID "%s" initialisiert' %
            uid)

    def set_callback(self, timeframe=5000):
        self._bricklet.set_temperature_callback_period(timeframe)
        self._bricklet.register_callback(self._bricklet.CALLBACK_TEMPERATURE,
                                         self._changed)
        self._logging_daemon.debug(
            'Tinkerforge ... Temperature-Bricklet UID "%s" Callback gesetzt' %
            self.uid)

    def read(self):
        return self._bricklet.get_temperature() / self._QUOTIENT

    def read_rising(self):
        return self._rising

    def read_falling(self):
        return self._falling

    def _changed(self, tmp_value):
        tmp_value = (tmp_value / self._QUOTIENT)
        if abs(self._value - tmp_value) >= self.trigger_difference:
            tmp_value = (tmp_value / self._QUOTIENT)
        if abs(self._value - tmp_value) >= self.trigger_difference:
            if tmp_value > self._value_old:
                self._rising = True
                self._falling = False
            elif tmp_value < self._value_old:
                self._rising = False
                self._falling = True
            self._logging_daemon.debug(
                'Tinkerforge ... Temperature-Bricklet UID "%s" , Neu = %f , Alt = %f , rising = %s , falling = %s'
                % (self.uid, tmp_value, self._value_old, self._rising,
                   self._falling))
            self._value_old = tmp_value
            self._value = tmp_value
            tmp_json = json.dumps([
                "send_changed_data", self.uid, "sensor", "temperature",
                self._value
            ])
            for consumer in self._queue:
                consumer(tmp_json)
                self._logging_daemon.info(
                    'Tinkerforge ... Temperature-Bricklet UID "%s" , neuer Wert %f -> SocketServer Warteschlange '
                    % (self.uid, self._value))

    temperature = property(read)
    rising = property(read_rising)
    falling = property(read_falling)
class ClimateSensors:

    def __init__(self, host, port):
        self.hum = None
        self.hum_value = 0.0
        self.temp = None
        self.temp_value = 0.0
        self.lcd = None

        self.port = port
        self.host = host
        self.conn = IPConnection()

        self.conn.register_callback(IPConnection.CALLBACK_ENUMERATE, self.cb_enumerate)
        self.conn.register_callback(IPConnection.CALLBACK_CONNECTED, self.cb_connected)

    def update_display(self):
        if self.lcd is not None:
            self.lcd.write_line(1, 2, 'Temp:   {:3.2f} C'.format(self.temp_value))
            self.lcd.write_line(2, 2, 'RelHum: {:3.2f} %'.format(self.hum_value))

    def connect(self):
        if self.conn.get_connection_state() == self.conn.CONNECTION_STATE_DISCONNECTED:
            self.conn.connect(self.host, self.port)
            self.conn.enumerate()

    def disconnect(self):
        if self.conn.get_connection_state() != self.conn.CONNECTION_STATE_DISCONNECTED:
            if self.lcd is not None:
                self.lcd.backlight_off()
                self.lcd.clear_display()
            self.conn.disconnect()

    def cb_connected(self, connected_reason):
        self.conn.enumerate()

    def cb_enumerate(self, uid, connected_uid, position, hardware_version, firmware_version, device_identifier, enumeration_type):
        if enumeration_type == IPConnection.ENUMERATION_TYPE_DISCONNECTED:
            # print("DISCONNECTED")
            return

        if device_identifier == Temperature.DEVICE_IDENTIFIER:
            self.temp = Temperature(uid, self.conn)
            self.temp.register_callback(self.temp.CALLBACK_TEMPERATURE, self.cb_temperature)
            self.update_temperature(self.temp.get_temperature())
            self.temp.set_temperature_callback_period(UPDATE_PERIOD)

        if device_identifier == Humidity.DEVICE_IDENTIFIER:
            self.hum = Humidity(uid, self.conn)
            self.hum.register_callback(self.hum.CALLBACK_HUMIDITY, self.cb_humidity)
            self.update_humidity(self.hum.get_humidity())
            self.hum.set_humidity_callback_period(UPDATE_PERIOD)

        if device_identifier == LCD20x4.DEVICE_IDENTIFIER:
            self.lcd = LCD20x4(uid, self.conn)
            self.lcd.backlight_on()

    def cb_temperature(self, temperature):
        self.update_temperature(temperature)
        self.update_display()

    def update_temperature(self, raw_temperature):
        self.temp_value = raw_temperature / 100.0

    def cb_humidity(self, humidity):
        self.update_humidity(humidity)
        self.update_display()

    def update_humidity(self, raw_humidity):
        self.hum_value = raw_humidity / 10.0
예제 #11
0
        uv_light = uvlight.get_uv_light()
        print("UV Light: " + str(uv_light))

        # Get current CO2 concentration (unit is ppm)
        cur_co2_concentration = co2.get_co2_concentration()
        print("CO2: " + str(cur_co2_concentration))

        # Get current sound intensity level
        cur_si = sound_intensity.get_intensity()
        print("Sound intensity: " + str(cur_si))

        # Get current dust density
        cur_dd = dust_density.get_dust_density()
        print("Dust density: " + str(cur_dd))

        # Get current humidity level
        cur_humidity = humidity.get_humidity() / 100.0
        print("Humidity: " + str(cur_humidity))

        # Get temperature from humidity sensor
        cur_humidity = humidity.get_temperature() / 100.0
        print("Temperature (Humidity sensor): " + str(cur_humidity))

        # Temperature
        cur_temp = temperature.get_temperature() / 100.00
        print("Temperature: " + str(cur_temp), flush=True)

        # Print out values every 10 seconds
        time.sleep(10)
예제 #12
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-  

HOST = "localhost"
PORT = 4223
UID = "XYZ" # Change to your UID

from tinkerforge.ip_connection import IPConnection
from tinkerforge.bricklet_temperature import Temperature

if __name__ == "__main__":
    ipcon = IPConnection() # Create IP connection
    t = Temperature(UID, ipcon) # Create device object

    ipcon.connect(HOST, PORT) # Connect to brickd
    # Don't use device before ipcon is connected

    # Get current temperature (unit is °C/100)
    temperature = t.get_temperature()/100.0

    print('Temperature: ' + str(temperature) + ' °C')

    raw_input('Press key to exit\n') # Use input() in Python 3
    ipcon.disconnect()
예제 #13
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

HOST = "localhost"
PORT = 4223
UID = "XYZ"  # Change to your UID

import time

from tinkerforge.ip_connection import IPConnection
from tinkerforge.bricklet_temperature import Temperature

if __name__ == "__main__":
    ipcon = IPConnection()  # Create IP connection
    t = Temperature(UID, ipcon)  # Create device object

    ipcon.connect(HOST, PORT)  # Connect to brickd
    # Don't use device before ipcon is connected

    # Get current temperature (unit is °C/100)
    temperature = t.get_temperature() / 100.0
    print('Temperature of ' + str(temperature) + ' °C on ' + time.ctime())

    ipcon.disconnect()
예제 #14
0
class TF(object):
    def __init__(self, host, port, secret, timeout, verbose):
        self.host = host
        self.port = port
        self.secret = secret
        self.timeout = timeout
        self.verbose = verbose
        self.device_type = None
        self.ptc = None
        self.temp = None
        self.al = None
        self.hum = None
        self.dist = None
        self.motion = None

        self.type_ptc = "ptc"
        self.type_temperature = "temperature"
        self.type_ambient_light = "ambient_light"
        self.type_humidity = "humidity"
        self.type_distance = "distance"
        self.type_motion = "motion"

        self.ipcon = IPConnection()
        self.ipcon.set_timeout(self.timeout)

    def connect(self, device_type, run_enumeration):
        self.device_type = device_type

        self.ipcon.connect(self.host, self.port)

        self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, self.cb_enumerate)

        if self.verbose:
            print("Connected to host '%s' on port %s." % (self.host, self.port))

        if self.secret:
            try:
                self.ipcon.authenticate(self.secret)
                if self.verbose:
                    print("DEBUG: Authentication succeeded.")
            except IPConnectionError:
                output("Cannot authenticate", 3)

        if run_enumeration is True:
            self.ipcon.enumerate()
            if self.verbose:
                print("Enumerate request sent.")

    def cb_enumerate(self, uid, connected_uid, position, hardware_version,
                     firmware_version, device_identifier, enumeration_type):
        if enumeration_type == IPConnection.ENUMERATION_TYPE_DISCONNECTED:
            return

        # Note: The order is important, detect PTC before Humidity
        #
        # https://www.tinkerforge.com/en/doc/Software/Bricklets/PTCV2_Bricklet_Python.html
        if device_identifier == BrickletPTCV2.DEVICE_IDENTIFIER:
            self.ptc = BrickletPTCV2(uid, self.ipcon)
            self.device_type = self.type_ptc

        # https://www.tinkerforge.com/en/doc/Software/Bricklets/Temperature_Bricklet_Python.html
        if device_identifier == Temperature.DEVICE_IDENTIFIER:
            self.temp = Temperature(uid, self.ipcon)
            self.device_type = self.type_temperature

        # https://www.tinkerforge.com/en/doc/Software/Bricklets/AmbientLightV2_Bricklet_Python.html
        if device_identifier == BrickletAmbientLightV2.DEVICE_IDENTIFIER:
            self.al = BrickletAmbientLightV2(uid, self.ipcon)
            self.device_type = self.type_ambient_light

        # https://www.tinkerforge.com/en/doc/Software/Bricklets/HumidityV2_Bricklet_Python.html
        if device_identifier == BrickletHumidityV2.DEVICE_IDENTIFIER:
            self.hum = BrickletHumidityV2(uid, self.ipcon)
            self.device_type = self.type_humidity

        # https://www.tinkerforge.com/en/doc/Software/Bricklets/DistanceIRV2_Bricklet_Python.html
        if device_identifier == BrickletDistanceIRV2.DEVICE_IDENTIFIER:
            self.dist = BrickletDistanceIRV2(uid, self.ipcon)
            self.device_type = self.type_distance

        # https://www.tinkerforge.com/de/doc/Software/Bricklets/MotionDetectorV2_Bricklet_Python.html
        if device_identifier == BrickletMotionDetectorV2.DEVICE_IDENTIFIER:
            self.dist = BrickletMotionDetectorV2(uid, self.ipcon)
            self.device_type = self.type_motion

        if self.verbose:
            print("UID:               " + uid)
            print("Enumeration Type:  " + str(enumeration_type))
            print("Connected UID:     " + connected_uid)
            print("Position:          " + position)
            print("Hardware Version:  " + str(hardware_version))
            print("Firmware Version:  " + str(firmware_version))
            print("Device Identifier: " + str(device_identifier))
            print("Device Type:       " + str(self.device_type))
            print("")

    @staticmethod
    def parse_threshold(t):
        # ranges
        if ":" in t:
            return t.split(":")
        else:
            return [t]

    def eval_threshold_generic(self, val, threshold):
        t_arr = self.parse_threshold(threshold)

        # if we only have one value, treat this as 0..value range
        if len(t_arr) == 1:
            if self.verbose:
                print("Evaluating thresholds, single %s on value %s" % (" ".join(t_arr), val))

            if val > (float(t_arr[0])):
                return True
        else:
            if self.verbose:
                print("Evaluating thresholds, rangle %s on value %s" % (":".join(t_arr), val))

            if val < float(t_arr[0]) or val > float(t_arr[1]):
                return True

        return False

    def eval_thresholds(self, val, warning, critical):
        status = 0

        if warning:
            if self.eval_threshold_generic(val, warning):
                status = 1

        if critical:
            if self.eval_threshold_generic(val, critical):
                status = 2

        return status

    def check(self, uid, warning, critical):
        # PTC
        # https://www.tinkerforge.com/en/doc/Software/Bricklets/PTCV2_Bricklet_Python.html
        if self.device_type == self.type_ptc:
            ticks = 0
            if uid:
                self.ptc = BrickletPTCV2(uid, self.ipcon)
            else:
                # TODO: refactor
                while not self.ptc:
                    time.sleep(0.1)
                    ticks = ticks + 1
                    if ticks > self.timeout * 10:
                        output("Timeout %s s reached while detecting bricklet. "
                               "Please use -u to specify the device UID." % self.timeout, 3)

            ptc_value = self.ptc.get_temperature() / 100.0

            status = self.eval_thresholds(ptc_value, warning, critical)

            perfdata = {
                "temperature": ptc_value
            }

            output("Temperature is %s degrees celcius" % ptc_value, status, [], perfdata)

        # Temperature
        # https://www.tinkerforge.com/en/doc/Software/Bricklets/Temperature_Bricklet_Python.html
        if self.device_type == self.type_temperature:
            ticks = 0
            if uid:
                self.temp = Temperature(uid, self.ipcon)
            else:
                # TODO: refactor
                while not self.temp:
                    time.sleep(0.1)
                    ticks = ticks + 1
                    if ticks > self.timeout * 10:
                        output("Timeout %s s reached while detecting bricklet. "
                               "Please use -u to specify the device UID." % self.timeout, 3)

            temp_value = self.temp.get_temperature() / 100.0

            status = self.eval_thresholds(temp_value, warning, critical)

            perfdata = {
                "temperature": temp_value
            }

            output("Temperature is %s degrees celcius" % temp_value, status, [], perfdata)

        # Ambient Light
        # https://www.tinkerforge.com/en/doc/Software/Bricklets/AmbientLightV2_Bricklet_Python.html
        if self.device_type == self.type_ambient_light:
            ticks = 0
            if uid:
                self.al = BrickletAmbientLightV2(uid, self.ipcon)
            else:
                # TODO: refactor
                while not self.al:
                    time.sleep(0.1)
                    ticks = ticks + 1
                    if ticks > self.timeout * 10:
                        output("Timeout %s s reached while detecting bricklet. "
                               "Please use -u to specify the device UID." % self.timeout, 3)

            al_value = self.al.get_illuminance() / 100.0

            status = self.eval_thresholds(al_value, warning, critical)

            perfdata = {
                "illuminance": al_value
            }

            output("Illuminance is %s lx" % al_value, status, [], perfdata)

        # Humidity
        # https://www.tinkerforge.com/en/doc/Software/Bricklets/HumidityV2_Bricklet_Python.html
        if self.device_type == self.type_humidity:
            ticks = 0
            if uid:
                self.hum = BrickletHumidityV2(uid, self.ipcon)
            else:
                # TODO: refactor
                while not self.hum:
                    time.sleep(0.1)
                    ticks = ticks + 1
                    if ticks > self.timeout * 10:
                        output("Timeout %s s reached while detecting bricklet. "
                               "Please use -u to specify the device UID." % self.timeout, 3)

            hum_value = self.hum.get_humidity() / 100.0
            hum_temp_value = self.hum.get_temperature() / 100.0

            status = self.eval_thresholds(hum_value, warning, critical)

            perfdata = {
                "humidity": hum_value,
                "temperature": hum_temp_value
            }

            output("Humidity is %s %%HR (Temperature is %s degrees celcius)" % (hum_value, hum_temp_value),
                   status, [], perfdata)

        # Distance
        # https://www.tinkerforge.com/en/doc/Software/Bricklets/DistanceIRV2_Bricklet_Python.html
        if self.device_type == self.type_distance:
            ticks = 0
            if uid:
                self.dist = BrickletDistanceIRV2(uid, self.ipcon)
            else:
                # TODO: refactor
                while not self.dist:
                    time.sleep(0.1)
                    ticks = ticks + 1
                    if ticks > self.timeout * 10:
                        output("Timeout %s s reached while detecting bricklet. "
                               "Please use -u to specify the device UID." % self.timeout, 3)

            dist_value = self.dist.get_distance() / 10.0

            status = self.eval_thresholds(dist_value, warning, critical)

            perfdata = {
                "distance": dist_value,
            }

            output("Distance is %s cm" % dist_value, status, [], perfdata)

        # Motion
        # https://www.tinkerforge.com/de/doc/Software/Bricklets/MotionDetectorV2_Bricklet_Python.html
        if self.device_type == self.type_motion:
            ticks = 0
            if uid:
                self.motion = BrickletMotionDetectorV2(uid, self.ipcon)
            else:
                # TODO: refactor
                while not self.motion:
                    time.sleep(0.1)
                    ticks = ticks + 1
                    if ticks > self.timeout * 10:
                        output("Timeout %s s reached while detecting bricklet. "
                               "Please use -u to specify the device UID." % self.timeout, 3)

            motion_value = self.motion.get_motion_detected()

            perfdata = {
                    "motion": motion_value
            }
            
            if motion_value:
                output("Motion detected!", motion_value, [], perfdata)
            else:
                output("No motion detected", motion_value, [], perfdata)
예제 #15
0
    lcd = LCD20x4(UID_L, ipcon1) # Create device object
    b = Barometer(UID_B, ipcon2) # Create device object
    temp1 = Temperature(UID_T1, ipcon2)
    temp2 = Temperature(UID_T2, ipcon1)
    al = AmbientLight(UID_A, ipcon1) # Create device object
    h = Humidity(UID_F, ipcon2) # Create device object
    master = Master(UID_M, ipcon2) # Create device object
    ipcon1.connect(HOST1, PORT) # Connect to brickd
    ipcon2.connect(HOST2, PORT) 

    while True:
        air_pressure = b.get_air_pressure()/1000.0
        altitude = b.get_altitude()/100.0
        illuminance = al.get_illuminance()/10.0
        bartemp = b.get_chip_temperature()/100.0
        esszimm = temp1.get_temperature()/100.0
        flur = temp2.get_temperature()/100.0
        voltage = master.get_stack_voltage()
        current = master.get_stack_current()
        wifi = master.get_wifi_configuration()
        wifistatus = master.get_wifi_status()
        wifipower = master.get_wifi_power_mode()
        wifihost = master.get_wifi_hostname()
        usbvoltage = master.get_usb_voltage()
        masterid = master.get_identity()
        feuchte = h.get_humidity()/10.0

        os.system('clear')
        
        luxwert = 10