Example #1
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)