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))
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))
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 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()
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
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)
# -*- 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()