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 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)
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()
def connect(self, type, uid): self.ipcon.connect(self.host, self.port) self.connected_type = type if self.connected_type == TYPE_PTC: ptc = PTC(uid, self.ipcon) if ptc.get_identity().device_identifier == PTCV2.DEVICE_IDENTIFIER: ptc = PTCV2(uid, self.ipcon) self.func = ptc.get_temperature self.name = 'temperature' self.unit = '°C' elif self.connected_type == TYPE_TEMPERATURE: temperature = Temperature(uid, self.ipcon) if temperature.get_identity().device_identifier == TemperatureV2.DEVICE_IDENTIFIER: temperature = TemperatureV2(uid, self.ipcon) self.func = temperature.get_temperature self.name = 'temperature' self.unit = '°C' elif self.connected_type == TYPE_HUMIDITY: humidity = Humidity(uid, self.ipcon) if humidity.get_identity().device_identifier == HumidityV2.DEVICE_IDENTIFIER: humidity = HumidityV2(uid, self.ipcon) self.is_humidity_v2 = True else: self.is_humidity_v2 = False self.func = humidity.get_humidity self.name = 'humidity' self.unit = '%RH' elif self.connected_type == TYPE_MOTION_DETECTOR: md = MotionDetector(uid, self.ipcon) if md.get_identity().device_identifier == MotionDetectorV2.DEVICE_IDENTIFIER: md = MotionDetectorV2(uid, self.ipcon) self.func = md.get_motion_detected elif self.connected_type == TYPE_AMBIENT_LIGHT: al = AmbientLight(uid, self.ipcon) if al.get_identity().device_identifier == AmbientLightV2.DEVICE_IDENTIFIER: al = AmbientLightV2(uid, self.ipcon) elif al.get_identity().device_identifier == AmbientLightV3.DEVICE_IDENTIFIER: al = AmbientLightV3(uid, self.ipcon) self.func = al.get_illuminance self.name = 'Illuminance' self.unit = 'lux' elif self.connected_type == TYPE_SEGMENT_DISPLAY_4X7: display = SegmentDisplay4x7(uid, self.ipcon) self.func = display.set_segments
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)
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)
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: if device_identifier == AmbientLight.DEVICE_IDENTIFIER: try: self.al = AmbientLight(uid, self.ipcon) self.al.set_illuminance_callback_period(1000) self.al.register_callback(self.al.CALLBACK_ILLUMINANCE, self.cb_illuminance) log.info('Ambient Light initialized') except Error as e: log.error('Ambient Light init failed: ' + str(e.description)) self.al = None elif device_identifier == AmbientLightV2.DEVICE_IDENTIFIER: try: self.al_v2 = AmbientLightV2(uid, self.ipcon) self.al_v2.set_illuminance_callback_period(1000) self.al_v2.register_callback(self.al_v2.CALLBACK_ILLUMINANCE, self.cb_illuminance_v2) log.info('Ambient Light 2.0 initialized') except Error as e: log.error('Ambient Light 2.0 init failed: ' + str(e.description)) self.al_v2 = None elif device_identifier == Temperature.DEVICE_IDENTIFIER: try: self.temp = Temperature(uid, self.ipcon) self.temp.set_temperature_callback_period(1000) self.temp.register_callback(self.temp.CALLBACK_TEMPERATURE, self.cb_temperature) log.info('Temperature initialized') except Error as e: log.error('Temperature init failed: ' + str(e.description)) self.temp = None
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("")
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
def connect(self, type, uid): self.ipcon.connect(self.host, self.port) self.connected_type = type if self.connected_type == TYPE_PTC: ptc = PTC(uid, self.ipcon) if ptc.get_identity().device_identifier == PTCV2.DEVICE_IDENTIFIER: ptc = PTCV2(uid, self.ipcon) self.func = ptc.get_temperature elif self.connected_type == TYPE_TEMPERATURE: temperature = Temperature(uid, self.ipcon) if temperature.get_identity().device_identifier == TemperatureV2.DEVICE_IDENTIFIER: temperature = TemperatureV2(uid, self.ipcon) self.func = temperature.get_temperature
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 __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 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 LCD Bricklet if device_identifier == LCD20x4.DEVICE_IDENTIFIER: # Create lcd device object self.lcd = LCD20x4(uid, self.ipcon) self.lcd.register_callback(self.lcd.CALLBACK_BUTTON_PRESSED, self.cb_button_pressed) self.lcd.clear_display() self.lcd.backlight_on() # Enumeration is for Temperature Bricklet if device_identifier == Temperature.DEVICE_IDENTIFIER: # Create temperature device object self.temp = Temperature(uid, self.ipcon) self.temp.register_callback(self.temp.CALLBACK_TEMPERATURE, self.cb_temperature) self.temp.set_temperature_callback_period(50)
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()
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
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()
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
# -*- 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 # Callback function for temperature callback (parameter has unit °C/100) def cb_temperature(temperature): print('Temperature: ' + str(temperature/100.0) + ' °C') 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 # Set Period for temperature callback to 1s (1000ms) # Note: The callback is only called every second if the # temperature has changed since the last call! t.set_temperature_callback_period(1000) # Register temperature callback to function cb_temperature t.register_callback(t.CALLBACK_TEMPERATURE, cb_temperature) raw_input('Press key to exit\n') # Use input() in Python 3 ipcon.disconnect()
class ExampleRugged: HOST = "localhost" PORT = 4223 def __init__(self): self.lcd = None self.temp = None # 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(ExampleRugged.HOST, ExampleRugged.PORT) self.ipcon.enumerate() # Callback switches lcd backlight on/off based on lcd button 0 def cb_button_pressed(self, button): if self.lcd: if button == 0: if self.lcd.is_backlight_on(): self.lcd.backlight_off() else: self.lcd.backlight_on() # Callback updates temperature displayed on lcd def cb_temperature(self, temperature): if self.lcd: self.lcd.clear_display() s = 'Temperature: {0:.2f}{1:c}C'.format(temperature/100.0, 0xdf) self.lcd.write_line(0, 0, s) # 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 LCD Bricklet if device_identifier == LCD20x4.DEVICE_IDENTIFIER: # Create lcd device object self.lcd = LCD20x4(uid, self.ipcon) self.lcd.register_callback(self.lcd.CALLBACK_BUTTON_PRESSED, self.cb_button_pressed) self.lcd.clear_display() self.lcd.backlight_on() # Enumeration is for Temperature Bricklet if device_identifier == Temperature.DEVICE_IDENTIFIER: # Create temperature device object self.temp = Temperature(uid, self.ipcon) self.temp.register_callback(self.temp.CALLBACK_TEMPERATURE, self.cb_temperature) self.temp.set_temperature_callback_period(50) # 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()
#!/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()
def cb_enumerate(self, uid, connected_uid, position, hardware_version, firmware_version, device_identifier, enumeration_type): """Recherche des brickets et configuration.""" if enumeration_type == IPConnection.ENUMERATION_TYPE_CONNECTED or \ enumeration_type == IPConnection.ENUMERATION_TYPE_AVAILABLE: if device_identifier == Temperature.DEVICE_IDENTIFIER: try: self.temp = Temperature(uid, self.ipcon) log.info( time.strftime("%Y-%m-%d %H:%M:%S") + ' Temperature initialized') except Error as err: log.error( time.strftime("%Y-%m-%d %H:%M:%S") + ' Temperature init failed: ' + str(err.description)) self.temp = None elif device_identifier == SoundIntensity.DEVICE_IDENTIFIER: try: self.sound = SoundIntensity(uid, self.ipcon) log.info( time.strftime("%Y-%m-%d %H:%M:%S") + ' Sound intensity initialized') except Error as err: log.error( time.strftime("%Y-%m-%d %H:%M:%S") + ' Sound intensity init failed: ' + str(err.description)) self.sound = None elif device_identifier == Accelerometer.DEVICE_IDENTIFIER: try: self.accel = Accelerometer(uid, self.ipcon) log.info( time.strftime("%Y-%m-%d %H:%M:%S") + ' Accelerometer initialized') except Error as err: log.error( time.strftime("%Y-%m-%d %H:%M:%S") + ' Accelerometer init failed: ' + str(err.description)) self.accel = None elif device_identifier == IndustrialAnalogOut.DEVICE_IDENTIFIER: try: self.aout = IndustrialAnalogOut(uid, self.ipcon) self.aout.set_configuration( self.aout.VOLTAGE_RANGE_0_TO_5V, self.aout.CURRENT_RANGE_0_TO_20MA) self.aout.enable() self.aout_connected = True log.info( time.strftime("%Y-%m-%d %H:%M:%S") + ' IndustrialAnalogOut initialized') except Error as err: log.error( time.strftime("%Y-%m-%d %H:%M:%S") + ' IndustrialAnalogOut init failed: ' + str(err.description)) self.aout = None elif device_identifier == IndustrialDualAnalogIn.DEVICE_IDENTIFIER: try: self.ain = IndustrialDualAnalogIn(uid, self.ipcon) self.ain.set_sample_rate(6) self.ain_connected = True log.info( time.strftime("%Y-%m-%d %H:%M:%S") + ' IndustrialDualAnalogIn initialized') except Error as err: log.error( time.strftime("%Y-%m-%d %H:%M:%S") + ' IndustrialDualAnalogIn init failed: ' + str(err.description)) self.ain = None elif device_identifier == IndustrialDigitalIn4.DEVICE_IDENTIFIER: try: self.din = IndustrialDigitalIn4(uid, self.ipcon) self.din.set_interrupt(8) self.din.set_debounce_period(0) self.din.register_callback(self.din.CALLBACK_INTERRUPT, self.cb_compteur_turbine) self.din_connected = True log.info( time.strftime("%Y-%m-%d %H:%M:%S") + ' IndustrialDigitalIn4 initialized') except Error as err: log.error( time.strftime("%Y-%m-%d %H:%M:%S") + ' IndustrialDigitalIn4 init failed: ' + str(err.description)) self.din = None
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)
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()
HOST = "localhost" PORT = 4223 UID = "XYZ" # Change to your UID from tinkerforge.ip_connection import IPConnection from tinkerforge.bricklet_temperature import Temperature # Callback for temperature greater than 30 °C def cb_reached(temperature): print('We have ' + str(temperature/100.0) + ' °C.') print('It is too hot, we need air conditioning!') 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 threshold callbacks with a debounce time of 10 seconds (10000ms) t.set_debounce_period(10000) # Register threshold reached callback to function cb_reached t.register_callback(t.CALLBACK_TEMPERATURE_REACHED, cb_reached) # Configure threshold for "greater than 30 °C" (unit is °C/100) t.set_temperature_callback_threshold('>', 30*100, 0) raw_input('Press key to exit\n') # Use input() in Python 3 ipcon.disconnect()
#!/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()
from tinkerforge.ip_connection import IPConnection from tinkerforge.bricklet_lcd_20x4 import LCD20x4 from tinkerforge.bricklet_barometer import Barometer from tinkerforge.bricklet_ambient_light import AmbientLight from tinkerforge.brick_master import Master from tinkerforge.bricklet_temperature import Temperature from tinkerforge.bricklet_humidity import Humidity if __name__ == "__main__": ipcon1 = IPConnection() # Create IP connection ipcon2 = IPConnection() # Create IP connection 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()
from tinkerforge.bricklet_temperature import Temperature from tinkerforge.bricklet_ambient_light import AmbientLight from tinkerforge.bricklet_uv_light import BrickletUVLight from tinkerforge.bricklet_motion_detector import BrickletMotionDetector from tinkerforge.bricklet_humidity_v2 import HumidityV2 import time from datetime import datetime if __name__ == "__main__": ipcon = IPConnection() # Create IP connection co2 = BrickletCO2(CO2_UID, ipcon) # Create device object humidity = HumidityV2(HUMIDITY_UID, ipcon) sound_intensity = SoundIntensity(SOUND_INTENSITY_UID, ipcon) dust_density = DustDetector(DUST_UID, ipcon) temperature = Temperature(TEMPERATURE_UID, ipcon) ambientlight = AmbientLight(AMBIENTLIGHT_UID, ipcon) uvlight = BrickletUVLight(UVLIGHT_UID, ipcon) motiondetect = BrickletMotionDetector(MOTIONDETECTOR_UID, ipcon) ipcon.connect(HOST, PORT) # Connect to brickd while (True): curtime = datetime.now() print("Time: " + curtime.strftime('%Y/%m/%d %H:%M:%S')) motion = motiondetect.get_motion_detected() print("Motion: " + str(motion)) illuminance = ambientlight.get_illuminance() / 10.0 print("Illuminance: " + str(illuminance))
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)
class ServerRoomMonitoring: HOST = "ServerMonitoring" PORT = 4223 ipcon = None al = None al_v2 = None temp = None def __init__(self): self.xively = Xively() self.ipcon = IPConnection() while True: try: self.ipcon.connect(ServerRoomMonitoring.HOST, ServerRoomMonitoring.PORT) break except Error as e: log.error('Connection Error: ' + str(e.description)) time.sleep(1) except socket.error as e: log.error('Socket error: ' + str(e)) time.sleep(1) self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, self.cb_enumerate) self.ipcon.register_callback(IPConnection.CALLBACK_CONNECTED, self.cb_connected) while True: try: self.ipcon.enumerate() break except Error as e: log.error('Enumerate Error: ' + str(e.description)) time.sleep(1) def cb_illuminance(self, illuminance): self.xively.put('AmbientLight', illuminance/10.0) log.info('Ambient Light ' + str(illuminance/10.0)) def cb_illuminance_v2(self, illuminance): self.xively.put('AmbientLight', illuminance/100.0) log.info('Ambient Light ' + str(illuminance/100.0)) def cb_temperature(self, temperature): self.xively.put('Temperature', temperature/100.0) log.info('Temperature ' + str(temperature/100.0)) 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: if device_identifier == AmbientLight.DEVICE_IDENTIFIER: try: self.al = AmbientLight(uid, self.ipcon) self.al.set_illuminance_callback_period(1000) self.al.register_callback(self.al.CALLBACK_ILLUMINANCE, self.cb_illuminance) log.info('Ambient Light initialized') except Error as e: log.error('Ambient Light init failed: ' + str(e.description)) self.al = None elif device_identifier == AmbientLightV2.DEVICE_IDENTIFIER: try: self.al_v2 = AmbientLightV2(uid, self.ipcon) self.al_v2.set_illuminance_callback_period(1000) self.al_v2.register_callback(self.al_v2.CALLBACK_ILLUMINANCE, self.cb_illuminance_v2) log.info('Ambient Light 2.0 initialized') except Error as e: log.error('Ambient Light 2.0 init failed: ' + str(e.description)) self.al_v2 = None elif device_identifier == Temperature.DEVICE_IDENTIFIER: try: self.temp = Temperature(uid, self.ipcon) self.temp.set_temperature_callback_period(1000) self.temp.register_callback(self.temp.CALLBACK_TEMPERATURE, self.cb_temperature) log.info('Temperature initialized') except Error as e: log.error('Temperature init failed: ' + str(e.description)) self.temp = None def cb_connected(self, connected_reason): if connected_reason == IPConnection.CONNECT_REASON_AUTO_RECONNECT: log.info('Auto Reconnect') while True: try: self.ipcon.enumerate() break except Error as e: log.error('Enumerate Error: ' + str(e.description)) time.sleep(1)