def barometer(connection, table):
    ipcon = IPConnection()
    b = Barometer(BAROMETER_UID, ipcon)
    ipcon.connect(HOST, PORT)
    value = b.get_air_pressure() / 1000.0  # Get current air pressure (unit is mbar/1000)
    insert(connection, table, time.time(), value)
    ipcon.disconnect()
Esempio n. 2
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 == LCD20x4.DEVICE_IDENTIFIER:
             try:
                 self.lcd = LCD20x4(uid, self.ipcon)
                 self.lcd.clear_display()
                 self.lcd.backlight_on()
                 log.info('LCD 20x4 initialized')
             except Error as e:
                 log.error('LCD 20x4 init failed: ' + str(e.description))
                 self.lcd = None
         elif device_identifier == AmbientLight.DEVICE_IDENTIFIER:
             try:
                 self.al = AmbientLight(uid, self.ipcon)
                 self.al.set_illuminance_callback_period(5000)
                 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_configuration(
                     AmbientLightV2.ILLUMINANCE_RANGE_64000LUX,
                     AmbientLightV2.INTEGRATION_TIME_200MS)
                 self.al_v2.set_illuminance_callback_period(5000)
                 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 = None
         elif device_identifier == Humidity.DEVICE_IDENTIFIER:
             try:
                 self.hum = Humidity(uid, self.ipcon)
                 self.hum.set_humidity_callback_period(5000)
                 self.hum.register_callback(self.hum.CALLBACK_HUMIDITY,
                                            self.cb_humidity)
                 log.info('Humidity initialized')
             except Error as e:
                 log.error('Humidity init failed: ' + str(e.description))
                 self.hum = None
         elif device_identifier == Barometer.DEVICE_IDENTIFIER:
             try:
                 self.baro = Barometer(uid, self.ipcon)
                 self.baro.set_air_pressure_callback_period(5000)
                 self.baro.register_callback(
                     self.baro.CALLBACK_AIR_PRESSURE, self.cb_air_pressure)
                 log.info('Barometer initialized')
             except Error as e:
                 log.error('Barometer init failed: ' + str(e.description))
                 self.baro = None
Esempio n. 3
0
class BrickletAirPressure:
    _QUOTIENT = 1000.0

    def __init__(self, uid, connection, logging_daemon, queue, value=0.0, trigger_difference=0.5):
        self.bricklet = Barometer(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 ... Barometer-Bricklet UID "%s" initialisiert' % uid)

    def set_callback(self, timeframe=5000):
        self.bricklet.set_air_pressure_callback_period(timeframe)
        self.bricklet.register_callback(self.bricklet.CALLBACK_AIR_PRESSURE, self._changed)
        self._logging_daemon.debug('Tinkerforge ... Barometer-Bricklet UID "%s" Callback gesetzt' % self.uid)

    def read(self):
        return self.bricklet.get_air_pressure() / 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:
            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 ... Barometer-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", "air_pressure", self._value])
            for consumer in self._queue:
                consumer(tmp_json)
                self._logging_daemon.info(
                    'Tinkerforge ... Barometer-Bricklet UID "%s" , neuer Wert %f -> SocketServer Warteschlange ' % (
                        self.uid, self._value))

    air_pressure = property(read)
    rising = property(read_rising)
    falling = property(read_falling)
Esempio n. 4
0
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 __init__(self, parent=None):
        QMainWindow.__init__(self, parent)

        self.initialized = False
        self.altitude_error_i = 0
        self.acc_scale = 0.0
        self.start_time = time.time()
        self.altitude_error = 0
        self.inst_acceleration = 0.0
        self.delta = 0
        self.estimated_velocity = 0.0
        self.estimated_altitude = 0.0
        self.last_time = time.time()

        self.last_orig_altitude = 0
        self.last_estimated_altitude = 0

        ipcon = IPConnection()
        self.imu = IMU(UID_IMU, ipcon)
        self.barometer = Barometer(UID_BAROMETER, ipcon)
        ipcon.connect(HOST, PORT)

        # Turn leds and orientation calculation off, to save calculation time
        # for the IMU Brick. This makes sure that the measurements are taken
        # in equidistant 2ms intervals
        self.imu.leds_off()
        self.imu.orientation_calculation_off()

        # Turn averaging of in the Barometer Bricklet to make sure that
        # the data is without delay
        self.barometer.set_averaging(0, 0, 0)

        red_pen = QPen(Qt.red)
        red_pen.setWidth(5)

        plot_list = [  #['', Qt.blue, self.get_orig_value],
            ['', red_pen, self.get_estimated_value]
        ]
        self.plot_widget = PlotWidget('Height [m]', plot_list)
        self.plot_widget.stop = False
        self.setCentralWidget(self.plot_widget)

        self.timer = QTimer()
        self.timer.timeout.connect(self.update)
        self.timer.start(6)
Esempio n. 6
0
 def __init__(self,
              uid,
              connection,
              logging_daemon,
              queue,
              value=0.0,
              trigger_difference=0.5):
     self.bricklet = Barometer(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 ... Barometer-Bricklet UID "%s" initialisiert' % uid)
Esempio n. 7
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 == LCD20x4.DEVICE_IDENTIFIER:
             try:
                 self.lcd = LCD20x4(uid, self.ipcon)
                 self.lcd.clear_display()
                 self.lcd.backlight_on()
                 log.info('LCD 20x4 initialized')
             except Error as e:
                 log.error('LCD 20x4 init failed: ' + str(e.description))
                 self.lcd = None
         elif 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_configuration(AmbientLightV2.ILLUMINANCE_RANGE_64000LUX,
                                              AmbientLightV2.INTEGRATION_TIME_200MS)
                 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 == Humidity.DEVICE_IDENTIFIER:
             try:
                 self.hum = Humidity(uid, self.ipcon)
                 self.hum.set_humidity_callback_period(1000)
                 self.hum.register_callback(self.hum.CALLBACK_HUMIDITY,
                                            self.cb_humidity)
                 log.info('Humidity initialized')
             except Error as e:
                 log.error('Humidity init failed: ' + str(e.description))
                 self.hum = None
         elif device_identifier == Barometer.DEVICE_IDENTIFIER:
             try:
                 self.baro = Barometer(uid, self.ipcon)
                 self.baro.set_air_pressure_callback_period(1000)
                 self.baro.register_callback(self.baro.CALLBACK_AIR_PRESSURE,
                                             self.cb_air_pressure)
                 log.info('Barometer initialized')
             except Error as e:
                 log.error('Barometer init failed: ' + str(e.description))
                 self.baro = None
Esempio n. 8
0
 def __init__(self, uid, connection, logging_daemon, queue, value=0.0, trigger_difference=0.5):
     self.bricklet = Barometer(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 ... Barometer-Bricklet UID "%s" initialisiert' % uid)
Esempio n. 9
0
def get_airpressure(id):
    
    cfg = configparser.ConfigParser()
    
    cfg.read(cfg_filename) # open config file to read from
    
    if cfg.has_section("Barometer") == True:
    
        port = cfg.getint('Connection', 'Port') # get port entry from config file
        
        host = cfg.get('Connection', 'Host') # get host entry from config file
        
        uid = cfg.get('Barometer', 'bricklet_uid') # uid port entry from config file
        
        ipcon = IPConnection() # Create IP connection
        
        ipcon.connect(host, port) # Connect to brickd
        
        b = Barometer(uid, ipcon) # Create device object
        
        air_pressure = b.get_air_pressure()/1000.0 # Get current air pressure (unit is mbar/1000)
        
        altitude = b.get_altitude()/100.0
        
        db = sqlite3.connect(local_db) # build connection to local database
        
        c = db.cursor() # create cursor
        
        c.execute(wd_table) # create weatherdata table
        
        c.execute('''INSERT INTO weatherdata(uid , value, keyword, date_id, device_name) VALUES(?,?,?,?,?)''', (uid,air_pressure,'air_pressure',id,'barometer',))
        # insert the uid, device name the id from the date table an die humdity value into the weather table
        
        c.execute('''INSERT INTO weatherdata(uid , value, keyword, date_id, device_name) VALUES(?,?,?,?,?)''', (uid,altitude,'altitude',id,'barometer',))
        
        db.commit() # save creates and inserts permanent  

        ipcon.disconnect()
    
        return({"air_pressure": air_pressure, "altitude": altitude})
Esempio n. 10
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
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)

        self.initialized = False
        self.altitude_error_i = 0
        self.acc_scale  = 0.0
        self.start_time = time.time()
        self.altitude_error = 0
        self.inst_acceleration = 0.0
        self.delta = 0
        self.estimated_velocity = 0.0
        self.estimated_altitude = 0.0
        self.last_time = time.time()

        self.last_orig_altitude = 0
        self.last_estimated_altitude = 0

        ipcon = IPConnection() 
        self.imu = IMU(UID_IMU, ipcon) 
        self.barometer = Barometer(UID_BAROMETER, ipcon)
        ipcon.connect(HOST, PORT) 

        # Turn leds and orientation calculation off, to save calculation time
        # for the IMU Brick. This makes sure that the measurements are taken
        # in equidistant 2ms intervals
        self.imu.leds_off()
        self.imu.orientation_calculation_off()

        # Turn averaging of in the Barometer Bricklet to make sure that
        # the data is without delay
        self.barometer.set_averaging(0, 0, 0)

        red_pen = QPen(Qt.red)
        red_pen.setWidth(5)

        plot_list = [#['', Qt.blue, self.get_orig_value],
                     ['', red_pen, self.get_estimated_value]
                    ]
        self.plot_widget = PlotWidget('Height [m]', plot_list)
        self.plot_widget.stop = False
        self.setCentralWidget(self.plot_widget)

        self.timer = QTimer()
        self.timer.timeout.connect(self.update)
        self.timer.start(6)
Esempio n. 12
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 == LCD20x4.DEVICE_IDENTIFIER:
                try:
                    self.lcd = LCD20x4(uid, self.ipcon)
                    self.lcd.clear_display()
                    self.lcd.backlight_on()
                    self.lcd.register_callback(self.lcd.CALLBACK_BUTTON_PRESSED, self.cb_button_pressed)
                    self.configure_custom_chars()

                except Error as e:
                    self.error_msg.showMessage('LCD 20x4 init failed: ' + str(e.description))
                    self.lcd = None
            elif 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)
                except Error as e:
                    self.error_msg.showMessage('Ambient Light init failed: ' + str(e.description))
                    self.al = None
            elif device_identifier == Humidity.DEVICE_IDENTIFIER:
                try:
                    self.hum = Humidity(uid, self.ipcon)
                    self.hum.set_humidity_callback_period(1000)
                    self.hum.register_callback(self.hum.CALLBACK_HUMIDITY,
                                               self.cb_humidity)
                except Error as e:
                    self.error_msg.showMessage('Humidity init failed: ' + str(e.description))
                    self.hum = None
            elif device_identifier == Barometer.DEVICE_IDENTIFIER:
                try:
                    self.baro = Barometer(uid, self.ipcon)
                    self.baro.set_air_pressure_callback_period(1000)
                    self.baro.register_callback(self.baro.CALLBACK_AIR_PRESSURE,
                                                self.cb_air_pressure)
                except Error as e:
                    self.error_msg.showMessage('Barometer init failed: ' + str(e.description))
                    self.baro = None
Esempio n. 13
0
class WeatherStation:
    HOST = "localhost"
    PORT = 4223

    ipcon = None
    lcd = None
    lcd_clear = False
    al = None
    hum = None
    baro = None

    def __init__(self):
        self.ipcon = IPConnection()
        while True:
            try:
                self.ipcon.connect(WeatherStation.HOST, WeatherStation.PORT)
                break
            except Error as e:
                log.error('Connection Error: ' + str(e.description))
                timer.sleep(1)
            except socket.error as e:
                log.error('Socket error: ' + str(e))
                timer.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))
                timer.sleep(1)  

    def start(self):
        t = 10
        extended_timer = 10      
        try:
            while True:
                if self.lcd:
                    self.write_date(0, 0)
                    self.write_time(1, 0)
                    t = t + 1
                    if t >= extended_timer:
                        if self.baro:
                            self.write_temperatur(2, 0)
                        if self.hum:
                            self.write_humidity(3, 0)
                        t = 0
                timer.sleep(1)
        except KeyboardInterrupt:    
            if weather_station.ipcon != None:
                weather_station.ipcon.disconnect()
            return

    def init_lcd(self, uid):
        try:
            self.lcd = LCD20x4(uid, self.ipcon)
            self.lcd.clear_display()
            self.lcd.backlight_on()
            log.info('LCD 20x4 initialized')
        except Error as e:
            log.error('LCD 20x4 init failed: ' + str(e.description))
            self.lcd = None
            
    def init_ambientlight(self, uid):
        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)
        except Error as e:
            log.error('Ambient Light init failed: ' + str(e.description))
            self.al = None
    
      
    def init_barometer(self, uid):
        try:
            self.baro = Barometer(uid, self.ipcon)
        except Error as e:
            log.error('Barometer init failed: ' + str(e.description))
            self.baro = None
    
    def init_humidity(self, uid):
        try:
            self.hum = Humidity(uid, self.ipcon)
        except Error as e:
            log.error('Humidity init failed: ' + str(e.description))
            self.hum = None
    
    def write_time(self, line, start_position):
        lt = localtime()
        hour, minute, second = lt[3:6]
        self.lcd.write_line(line, start_position, "Time:       %02i:%02i:%02i" % (hour, minute, second))

    def write_date(self, line, start_position):
        lt = localtime()
        year, month, day = lt[0:3]
        self.lcd.write_line(line, start_position, "Date:     %02i.%02i.%04i" % (day, month, year))

    def write_temperatur(self, line, start_position):
        try:
            temperature = self.baro.get_chip_temperature()
            text = 'Temp:       %5.2f \xDFC' % (temperature / 100.0)
            self.lcd.write_line(line, start_position, text)
        except Error as e:
            log.error('Could not get temperature: ' + str(e.description))
            return        
    
    def write_humidity(self, line, start_position):
        try:
            h = self.hum.get_humidity()
            text = 'Humidity:   %6.2f %%' % (h / 10.0)
            self.lcd.write_line(line, start_position, text)
        except Error as e:
            log.error('Could not get temperature: ' + str(e.description))
            return 

    def cb_illuminance(self, illuminance):
        if self.lcd is not None:
            i = illuminance / 10.0 
            if i < 0.5 and self.lcd.is_backlight_on():
                self.lcd.backlight_off()
            elif i >= 0.5 and not self.lcd.is_backlight_on():
                self.lcd.backlight_on()

    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 == LCD20x4.DEVICE_IDENTIFIER:
                self.init_lcd(uid)
            elif device_identifier == AmbientLight.DEVICE_IDENTIFIER:
                self.init_ambientlight(uid)
            elif device_identifier == Humidity.DEVICE_IDENTIFIER:
                self.init_humidity(uid)
            elif device_identifier == Barometer.DEVICE_IDENTIFIER:  
                self.init_barometer(uid)
         

    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))
                    timer.sleep(1)
Esempio n. 14
0
    ## Get voltage and current from stack (in mV / mA)
    #voltage = master.get_stack_voltage()
    #current = master.get_stack_current()

    ##print('Stack Voltage: ' + str(voltage / 1000.0) + ' V')
    ##print('Stack Current: ' + str(current / 1000.0) + ' A')
 
    t = Temperature(UID_TEMPERATURE) # Create temperature object
    ipcon.add_device(t) # Add device to IP connection
    # Don't use device before it is added to connection

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

    b = Barometer(UID_BAROMETER) # Create barometer object
    ipcon.add_device(b) # Add device to IP connection
    # Don't use device before it is added to the connection

    # Get the current air pressure (unit is mbar/1000)
    air_pressure = round(b.get_air_pressure()/1000.0, 1)

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

    lcd = LCD20x4(UID_LCD) # Create LCD object
    ipcon.add_device(lcd)  # Add device to IP connection
    # Don't use device before it is added to a connection

    # Clear display
    lcd.clear_display()
UID = "bAc" # Change to your UID

from tinkerforge.ip_connection import IPConnection
from tinkerforge.bricklet_barometer import Barometer

# Callback function for air pressure callback (parameter has unit mbar/1000)
def cb_air_pressure(air_pressure):
    print('Air Pressure: ' + str(air_pressure/1000.0) + ' mbar')

# Callback function for altitude callback (parameter has unit cm)
def cb_altitude(altitude):
    print('Altitude: ' + str(altitude/100.0) + ' m')

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

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

    # Set Period for air pressure and altitude callbacks to 1s (1000ms)
    # Note: The air pressure and altitude callbacks are only called every second
    #       if the air pressure or altitude has changed since the last call!
    b.set_air_pressure_callback_period(1000)
    b.set_altitude_callback_period(1000)

    # Register air pressure callback to function cb_air_pressure
    b.register_callback(b.CALLBACK_AIR_PRESSURE, cb_air_pressure)

    # Register altitude callback to function cb_altitude
    b.register_callback(b.CALLBACK_ALTITUDE, cb_altitude)
Esempio n. 16
0
class BrickletAirPressure:
    _QUOTIENT = 1000.0

    def __init__(self,
                 uid,
                 connection,
                 logging_daemon,
                 queue,
                 value=0.0,
                 trigger_difference=0.5):
        self.bricklet = Barometer(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 ... Barometer-Bricklet UID "%s" initialisiert' % uid)

    def set_callback(self, timeframe=5000):
        self.bricklet.set_air_pressure_callback_period(timeframe)
        self.bricklet.register_callback(self.bricklet.CALLBACK_AIR_PRESSURE,
                                        self._changed)
        self._logging_daemon.debug(
            'Tinkerforge ... Barometer-Bricklet UID "%s" Callback gesetzt' %
            self.uid)

    def read(self):
        return self.bricklet.get_air_pressure() / 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:
            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 ... Barometer-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", "air_pressure",
                self._value
            ])
            for consumer in self._queue:
                consumer(tmp_json)
                self._logging_daemon.info(
                    'Tinkerforge ... Barometer-Bricklet UID "%s" , neuer Wert %f -> SocketServer Warteschlange '
                    % (self.uid, self._value))

    air_pressure = property(read)
    rising = property(read_rising)
    falling = property(read_falling)
class WeatherStation:
    HOST = "localhost"
    PORT = 4223

    ipcon = None
    lcd = None
    al = None
    hum = None
    baro = None

    def __init__(self):
        self.xively = Xively()
        self.ipcon = IPConnection()
        while True:
            try:
                self.ipcon.connect(WeatherStation.HOST, WeatherStation.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):
        if self.lcd is not None:
            text = 'Illuminanc %6.2f lx' % (illuminance/10.0)
            self.lcd.write_line(0, 0, text)
            self.xively.put('AmbientLight', illuminance/10.0)
            log.info('Write to line 0: ' + text)

    def cb_humidity(self, humidity):
        if self.lcd is not None:
            text = 'Humidity   %6.2f %%' % (humidity/10.0)
            self.lcd.write_line(1, 0, text)
            self.xively.put('Humidity', humidity/10.0)
            log.info('Write to line 1: ' + text)

    def cb_air_pressure(self, air_pressure):
        if self.lcd is not None:
            text = 'Air Press %7.2f mb' % (air_pressure/1000.0)
            self.lcd.write_line(2, 0, text)
            self.xively.put('AirPressure', air_pressure/1000.0)
            log.info('Write to line 2: ' + text)

            temperature = self.baro.get_chip_temperature()/100.0
            # \xDF == ° on LCD 20x4 charset
            text = 'Temperature %5.2f \xDFC' % temperature
            self.lcd.write_line(3, 0, text)
            self.xively.put('Temperature', temperature)
            log.info('Write to line 3: ' + text.replace('\xDF', '°'))

    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 == LCD20x4.DEVICE_IDENTIFIER:
                try:
                    self.lcd = LCD20x4(uid, self.ipcon)
                    self.lcd.clear_display()
                    self.lcd.backlight_on()
                    log.info('LCD20x4 initialized')
                except Error as e:
                    log.error('LCD20x4 init failed: ' + str(e.description))
                    self.lcd = None
            elif 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('AmbientLight initialized')
                except Error as e:
                    log.error('AmbientLight init failed: ' + str(e.description))
                    self.al = None
            elif device_identifier == Humidity.DEVICE_IDENTIFIER:
                try:
                    self.hum = Humidity(uid, self.ipcon)
                    self.hum.set_humidity_callback_period(1000)
                    self.hum.register_callback(self.hum.CALLBACK_HUMIDITY,
                                               self.cb_humidity)
                    log.info('Humidity initialized')
                except Error as e:
                    log.error('Humidity init failed: ' + str(e.description))
                    self.hum = None
            elif device_identifier == Barometer.DEVICE_IDENTIFIER:
                try:
                    self.baro = Barometer(uid, self.ipcon)
                    self.baro.set_air_pressure_callback_period(1000)
                    self.baro.register_callback(self.baro.CALLBACK_AIR_PRESSURE,
                                                self.cb_air_pressure)
                    log.info('Barometer initialized')
                except Error as e:
                    log.error('Barometer init failed: ' + str(e.description))
                    self.baro = 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)
#!/usr/bin/env python
# -*- coding: utf-8 -*-

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

from tinkerforge.ip_connection import IPConnection
from tinkerforge.bricklet_barometer import Barometer

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

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

    # Get current air pressure (unit is mbar/1000)
    air_pressure = b.get_air_pressure()/1000.0

    print('Air Pressure: ' + str(air_pressure) + ' mbar')

    # Get current altitude (unit is cm)
    altitude = b.get_altitude()/100.0

    print('Altitude: ' + str(altitude) + ' m')

    raw_input('Press key to exit\n') # Use input() in Python 3
    ipcon.disconnect()
class IMUBarometerFusion(QMainWindow):
    FACTOR = 1
    KP1 = 0.55*FACTOR # PI observer velocity gain 
    KP2 = 1.0*FACTOR  # PI observer position gain
    KI = 0.001/FACTOR # PI observer integral gain (bias cancellation)

    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)

        self.initialized = False
        self.altitude_error_i = 0
        self.acc_scale  = 0.0
        self.start_time = time.time()
        self.altitude_error = 0
        self.inst_acceleration = 0.0
        self.delta = 0
        self.estimated_velocity = 0.0
        self.estimated_altitude = 0.0
        self.last_time = time.time()

        self.last_orig_altitude = 0
        self.last_estimated_altitude = 0

        ipcon = IPConnection() 
        self.imu = IMU(UID_IMU, ipcon) 
        self.barometer = Barometer(UID_BAROMETER, ipcon)
        ipcon.connect(HOST, PORT) 

        # Turn leds and orientation calculation off, to save calculation time
        # for the IMU Brick. This makes sure that the measurements are taken
        # in equidistant 2ms intervals
        self.imu.leds_off()
        self.imu.orientation_calculation_off()

        # Turn averaging of in the Barometer Bricklet to make sure that
        # the data is without delay
        self.barometer.set_averaging(0, 0, 0)

        red_pen = QPen(Qt.red)
        red_pen.setWidth(5)

        plot_list = [#['', Qt.blue, self.get_orig_value],
                     ['', red_pen, self.get_estimated_value]
                    ]
        self.plot_widget = PlotWidget('Height [m]', plot_list)
        self.plot_widget.stop = False
        self.setCentralWidget(self.plot_widget)

        self.timer = QTimer()
        self.timer.timeout.connect(self.update)
        self.timer.start(6)

    def get_orig_value(self):
        return self.last_orig_altitude

    def get_estimated_value(self):
        return self.last_estimated_altitude

    # Update measurements and compute new altitude every 6ms.
    def update(self):
        q = self.imu.get_quaternion()
        acc = self.imu.get_acceleration()
        alt = self.barometer.get_altitude()/100.0

        compensated_acc_q = self.compute_compensated_acc(q, acc)
        compensated_acc_q_earth = self.compute_dynamic_acceleration_vector(q, compensated_acc_q)

        self.last_orig_altitude = alt
        self.last_estimated_altitude = self.compute_altitude(compensated_acc_q_earth[2], alt)

    # Remove gravity from accelerometer measurements
    def compute_compensated_acc(self, q, a):
        g = (2*(q.x*q.z - q.w*q.y),
             2*(q.w*q.x + q.y*q.z),
             q.w*q.w - q.x*q.x - q.y*q.y + q.z*q.z)

        return (a[0]/1000.0 - g[0], 
                a[1]/1000.0 - g[1], 
                a[2]/1000.0 - g[2],
                0.0)

    # Rotate dynamic acceleration vector from sensor frame to earth frame
    def compute_dynamic_acceleration_vector(self, q, compensated_acc_q):
        def q_conj(q):
            return -q[0], -q[1], -q[2], q[3]

        def q_mult(q1, q2):
            x1, y1, z1, w1 = q1
            x2, y2, z2, w2 = q2
            w = w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2
            x = w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2
            y = w1 * y2 + y1 * w2 + z1 * x2 - x1 * z2
            z = w1 * z2 + z1 * w2 + x1 * y2 - y1 * x2

            return x, y, z, w

        tmp = q_mult(q, compensated_acc_q)
        return q_mult(tmp, q_conj(q))


    # Computes estimation of altitude based on barometer and accelerometer measurements
    # Code is based on blog post from Fabio Varesano: http://www.varesano.net/blog/fabio/complementary-filtering-high-res-barometer-and-accelerometer-reliable-altitude-estimation
    # He seems to have got the idea from the MultiWii project
    def compute_altitude(self, compensated_acceleration, altitude):
        self.current_time = time.time()
    
        # Initialization
        if not self.initialized:
            self.initialized = True
            self.estimated_altitude = altitude 
            self.estimated_velocity = 0
            self.altitude_error_i = 0

        # Estimation Error
        self.altitude_error = altitude - self.estimated_altitude
        self.altitude_error_i = self.altitude_error_i + self.altitude_error
        self.altitude_error_i = min(2500.0, max(-2500.0, self.altitude_error_i))

        self.inst_acceleration = compensated_acceleration * 9.80665 + self.altitude_error_i * self.KI
        dt = self.current_time - self.last_time

        # Integrators
        self.delta = self.inst_acceleration * dt + (self.KP1 * dt) * self.altitude_error
        self.estimated_altitude += (self.estimated_velocity/5.0 + self.delta) * (dt / 2) + (self.KP2 * dt) * self.altitude_error
        self.estimated_velocity += self.delta*10.0 
    
        self.last_time = self.current_time
    
        return self.estimated_altitude
Esempio n. 20
0
class WeatherStation:
    HOST = "localhost"
    PORT = 4223

    ipcon = None
    lcd = None
    al = None
    hum = None
    baro = None

    def __init__(self):
        self.ipcon = IPConnection()
        while True:
            try:
                self.ipcon.connect(WeatherStation.HOST, WeatherStation.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):
        if self.lcd is not None:
            text = 'Illuminanc %6.2f lx' % (illuminance / 10.0)
            self.lcd.write_line(0, 0, text)
            log.info('Write to line 0: ' + text)

    def cb_humidity(self, humidity):
        if self.lcd is not None:
            text = 'Humidity   %6.2f %%' % (humidity / 10.0)
            self.lcd.write_line(1, 0, text)
            log.info('Write to line 1: ' + text)

    def cb_air_pressure(self, air_pressure):
        if self.lcd is not None:
            text = 'Air Press %7.2f mb' % (air_pressure / 1000.0)
            self.lcd.write_line(2, 0, text)
            log.info('Write to line 2: ' + text)

            try:
                temperature = self.baro.get_chip_temperature()
            except Error as e:
                log.error('Could not get temperature: ' + str(e.description))
                return

            # \xDF == ° on LCD 20x4 charset
            text = 'Temperature %5.2f \xDFC' % (temperature / 100.0)
            self.lcd.write_line(3, 0, text)
            log.info('Write to line 3: ' + text.replace('\xDF', '°'))

    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 == LCD20x4.DEVICE_IDENTIFIER:
                try:
                    self.lcd = LCD20x4(uid, self.ipcon)
                    self.lcd.clear_display()
                    self.lcd.backlight_on()
                    log.info('LCD 20x4 initialized')
                except Error as e:
                    log.error('LCD 20x4 init failed: ' + str(e.description))
                    self.lcd = None
            elif 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 == Humidity.DEVICE_IDENTIFIER:
                try:
                    self.hum = Humidity(uid, self.ipcon)
                    self.hum.set_humidity_callback_period(1000)
                    self.hum.register_callback(self.hum.CALLBACK_HUMIDITY,
                                               self.cb_humidity)
                    log.info('Humidity initialized')
                except Error as e:
                    log.error('Humidity init failed: ' + str(e.description))
                    self.hum = None
            elif device_identifier == Barometer.DEVICE_IDENTIFIER:
                try:
                    self.baro = Barometer(uid, self.ipcon)
                    self.baro.set_air_pressure_callback_period(1000)
                    self.baro.register_callback(
                        self.baro.CALLBACK_AIR_PRESSURE, self.cb_air_pressure)
                    log.info('Barometer initialized')
                except Error as e:
                    log.error('Barometer init failed: ' + str(e.description))
                    self.baro = 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)
Esempio n. 21
0
 def init_barometer(self, uid):
     try:
         self.baro = Barometer(uid, self.ipcon)
     except Error as e:
         log.error('Barometer init failed: ' + str(e.description))
         self.baro = None
class IMUBarometerFusion(QMainWindow):
    FACTOR = 1
    KP1 = 0.55 * FACTOR  # PI observer velocity gain
    KP2 = 1.0 * FACTOR  # PI observer position gain
    KI = 0.001 / FACTOR  # PI observer integral gain (bias cancellation)

    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)

        self.initialized = False
        self.altitude_error_i = 0
        self.acc_scale = 0.0
        self.start_time = time.time()
        self.altitude_error = 0
        self.inst_acceleration = 0.0
        self.delta = 0
        self.estimated_velocity = 0.0
        self.estimated_altitude = 0.0
        self.last_time = time.time()

        self.last_orig_altitude = 0
        self.last_estimated_altitude = 0

        ipcon = IPConnection()
        self.imu = IMU(UID_IMU, ipcon)
        self.barometer = Barometer(UID_BAROMETER, ipcon)
        ipcon.connect(HOST, PORT)

        # Turn leds and orientation calculation off, to save calculation time
        # for the IMU Brick. This makes sure that the measurements are taken
        # in equidistant 2ms intervals
        self.imu.leds_off()
        self.imu.orientation_calculation_off()

        # Turn averaging of in the Barometer Bricklet to make sure that
        # the data is without delay
        self.barometer.set_averaging(0, 0, 0)

        red_pen = QPen(Qt.red)
        red_pen.setWidth(5)

        plot_list = [  #['', Qt.blue, self.get_orig_value],
            ['', red_pen, self.get_estimated_value]
        ]
        self.plot_widget = PlotWidget('Height [m]', plot_list)
        self.plot_widget.stop = False
        self.setCentralWidget(self.plot_widget)

        self.timer = QTimer()
        self.timer.timeout.connect(self.update)
        self.timer.start(6)

    def get_orig_value(self):
        return self.last_orig_altitude

    def get_estimated_value(self):
        return self.last_estimated_altitude

    # Update measurements and compute new altitude every 6ms.
    def update(self):
        q = self.imu.get_quaternion()
        acc = self.imu.get_acceleration()
        alt = self.barometer.get_altitude() / 100.0

        compensated_acc_q = self.compute_compensated_acc(q, acc)
        compensated_acc_q_earth = self.compute_dynamic_acceleration_vector(
            q, compensated_acc_q)

        self.last_orig_altitude = alt
        self.last_estimated_altitude = self.compute_altitude(
            compensated_acc_q_earth[2], alt)

    # Remove gravity from accelerometer measurements
    def compute_compensated_acc(self, q, a):
        g = (2 * (q.x * q.z - q.w * q.y), 2 * (q.w * q.x + q.y * q.z),
             q.w * q.w - q.x * q.x - q.y * q.y + q.z * q.z)

        return (a[0] / 1000.0 - g[0], a[1] / 1000.0 - g[1],
                a[2] / 1000.0 - g[2], 0.0)

    # Rotate dynamic acceleration vector from sensor frame to earth frame
    def compute_dynamic_acceleration_vector(self, q, compensated_acc_q):
        def q_conj(q):
            return -q[0], -q[1], -q[2], q[3]

        def q_mult(q1, q2):
            x1, y1, z1, w1 = q1
            x2, y2, z2, w2 = q2
            w = w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2
            x = w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2
            y = w1 * y2 + y1 * w2 + z1 * x2 - x1 * z2
            z = w1 * z2 + z1 * w2 + x1 * y2 - y1 * x2

            return x, y, z, w

        tmp = q_mult(q, compensated_acc_q)
        return q_mult(tmp, q_conj(q))

    # Computes estimation of altitude based on barometer and accelerometer measurements
    # Code is based on blog post from Fabio Varesano: http://www.varesano.net/blog/fabio/complementary-filtering-high-res-barometer-and-accelerometer-reliable-altitude-estimation
    # He seems to have got the idea from the MultiWii project
    def compute_altitude(self, compensated_acceleration, altitude):
        self.current_time = time.time()

        # Initialization
        if not self.initialized:
            self.initialized = True
            self.estimated_altitude = altitude
            self.estimated_velocity = 0
            self.altitude_error_i = 0

        # Estimation Error
        self.altitude_error = altitude - self.estimated_altitude
        self.altitude_error_i = self.altitude_error_i + self.altitude_error
        self.altitude_error_i = min(2500.0, max(-2500.0,
                                                self.altitude_error_i))

        self.inst_acceleration = compensated_acceleration * 9.80665 + self.altitude_error_i * self.KI
        dt = self.current_time - self.last_time

        # Integrators
        self.delta = self.inst_acceleration * dt + (self.KP1 *
                                                    dt) * self.altitude_error
        self.estimated_altitude += (self.estimated_velocity / 5.0 +
                                    self.delta) * (dt / 2) + (
                                        self.KP2 * dt) * self.altitude_error
        self.estimated_velocity += self.delta * 10.0

        self.last_time = self.current_time

        return self.estimated_altitude
Esempio n. 23
0

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
Esempio n. 24
0
class WeatherStation(QApplication):
    HOST = "localhost"
    PORT = 4223

    ipcon = None
    lcd = None
    al = None
    hum = None
    baro = None

    projects = []
    active_project = None

    error_msg = None

    def __init__(self, args):
        super(QApplication, self).__init__(args)

        self.error_msg = QErrorMessage()
        self.ipcon = IPConnection()

        signal.signal(signal.SIGINT, self.exit_demo)
        signal.signal(signal.SIGTERM, self.exit_demo)

        timer = QTimer(self)
        timer.setSingleShot(True)
        timer.timeout.connect(self.connect)
        timer.start(1)

    def exit_demo(self, signl=None, frme=None):
        try:
            self.ipcon.disconnect()
            self.timer.stop()
            self.tabs.destroy()
        except:
            pass

        sys.exit()

    def open_gui(self):
        self.main = MainWindow(self)
        self.main.setFixedSize(730, 430)
        self.main.setWindowIcon(QIcon(os.path.join(ProgramPath.program_path(), "demo-icon.png")))
        
        self.tabs = QTabWidget()
        
        widget = QWidget()
        layout = QVBoxLayout()
        layout.addWidget(self.tabs)
        widget.setLayout(layout)

        self.main.setCentralWidget(widget)
        
        self.projects.append(ProjectEnvDisplay(self.tabs, self))
        self.projects.append(ProjectStatistics(self.tabs, self))
        self.projects.append(ProjectXively(self.tabs, self))

        self.tabs.addTab(self.projects[0], "Display Environment Measurements")
        self.tabs.addTab(self.projects[1], "Show Statistics with Button Control")
        self.tabs.addTab(self.projects[2], "Connect to Xively")

        self.active_project = self.projects[0]

        self.tabs.currentChanged.connect(self.tabChangedSlot)

        self.main.setWindowTitle("Starter Kit: Weather Station Demo " + config.DEMO_VERSION)
        self.main.show()

    def connect(self):
        try:
            self.ipcon.connect(WeatherStation.HOST, WeatherStation.PORT)
        except Error as e:
            self.error_msg.showMessage('Connection Error: ' + str(e.description) + "\nBrickd installed and running?")
            return
        except socket.error as e:
            self.error_msg.showMessage('Socket error: ' + str(e) + "\nBrickd installed and running?")
            return

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

        try:
            self.ipcon.enumerate()
        except Error as e:
            self.error_msg.showMessage('Enumerate Error: ' + str(e.description))
            return

        self.open_gui()

    def tabChangedSlot(self, tabIndex):

        if self.lcd is not None:
            self.lcd.clear_display()

        self.active_project = self.projects[tabIndex]

    def cb_illuminance(self, illuminance):
        for p in self.projects:
            p.update_illuminance(illuminance)

    def cb_humidity(self, humidity):
        for p in self.projects:
            p.update_humidity(humidity)

    def cb_air_pressure(self, air_pressure):
        for p in self.projects:
            p.update_air_pressure(air_pressure)

        try:
            temperature = self.baro.get_chip_temperature()
        except Error as e:
            print('Could not get temperature: ' + str(e.description))
            return

        for p in self.projects:
            p.update_temperature(temperature)

    def configure_custom_chars(self):
        c = [[0x00 for x in range(8)] for y in range(8)]
	
        c[0] = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff]
        c[1] = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff]
        c[2] = [0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff]
        c[3] = [0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]
        c[4] = [0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff]
        c[5] = [0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]
        c[6] = [0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]
        c[7] = [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]

        for i in range(len(c)):
            self.lcd.set_custom_character(i, c[i]);

    def cb_button_pressed(self, button):
        for p in self.projects:
            p.button_pressed(button)

    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 == LCD20x4.DEVICE_IDENTIFIER:
                try:
                    self.lcd = LCD20x4(uid, self.ipcon)
                    self.lcd.clear_display()
                    self.lcd.backlight_on()
                    self.lcd.register_callback(self.lcd.CALLBACK_BUTTON_PRESSED, self.cb_button_pressed)
                    self.configure_custom_chars()

                except Error as e:
                    self.error_msg.showMessage('LCD 20x4 init failed: ' + str(e.description))
                    self.lcd = None
            elif 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)
                except Error as e:
                    self.error_msg.showMessage('Ambient Light init failed: ' + str(e.description))
                    self.al = None
            elif device_identifier == Humidity.DEVICE_IDENTIFIER:
                try:
                    self.hum = Humidity(uid, self.ipcon)
                    self.hum.set_humidity_callback_period(1000)
                    self.hum.register_callback(self.hum.CALLBACK_HUMIDITY,
                                               self.cb_humidity)
                except Error as e:
                    self.error_msg.showMessage('Humidity init failed: ' + str(e.description))
                    self.hum = None
            elif device_identifier == Barometer.DEVICE_IDENTIFIER:
                try:
                    self.baro = Barometer(uid, self.ipcon)
                    self.baro.set_air_pressure_callback_period(1000)
                    self.baro.register_callback(self.baro.CALLBACK_AIR_PRESSURE,
                                                self.cb_air_pressure)
                except Error as e:
                    self.error_msg.showMessage('Barometer init failed: ' + str(e.description))
                    self.baro = None

    def cb_connected(self, connected_reason):
        if connected_reason == IPConnection.CONNECT_REASON_AUTO_RECONNECT:

            while True:
                try:
                    self.ipcon.enumerate()
                    break
                except Error as e:
                    self.error_msg.showMessage('Enumerate Error: ' + str(e.description))
                    time.sleep(1)
HOST = "localhost"
PORT = 4223
UID = "bAc" # Change to your UID

from tinkerforge.ip_connection import IPConnection
from tinkerforge.bricklet_barometer import Barometer

# Callback for air pressure greater than 1025 mbar
def cb_reached(air_pressure):
    print('We have ' + str(air_pressure/1000.0) + ' mbar.')
    print('Enjoy the potentially good weather!')

if __name__ == "__main__":
    ipcon = IPConnection() # Create IP connection
    b = Barometer(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)
    b.set_debounce_period(10000)

    # Register threshold reached callback to function cb_reached
    b.register_callback(b.CALLBACK_AIR_PRESSURE_REACHED, cb_reached)

    # Configure threshold for "greater than 1025 mbar" (unit is mbar/1000)
    b.set_air_pressure_callback_threshold('>', 1025*1000, 0)

    raw_input('Press key to exit\n') # Use input() in Python 3