def ambient(connection, table):
    ipcon = IPConnection()
    al = AmbientLight(AMBIENT_UID, ipcon)
    ipcon.connect(HOST, PORT)
    value = al.get_illuminance() / 10.0  # Get current illuminance (unit is Lux/10)
    insert(connection, table, time.time(), value)
    ipcon.disconnect()
Exemplo 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
    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
Exemplo n.º 4
0
class BrickletAmbientLight:
    _QUOTIENT = 10.0

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

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

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

    ambient_light = property(read)
    rising = property(read_rising)
    falling = property(read_falling)
Exemplo n.º 5
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
Exemplo n.º 6
0
 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
Exemplo n.º 7
0
 def __init__(self,
              uid,
              connection,
              logging_daemon,
              queue,
              value=0.0,
              trigger_difference=0.1):
     self.bricklet = AmbientLight(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 ... AmbientLight-Bricklet UID "%s" initialisiert' %
         uid)
Exemplo n.º 8
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
Exemplo n.º 9
0
 def __init__(self, uid, connection, logging_daemon, queue, value=0.0, trigger_difference=0.1):
     self.bricklet = AmbientLight(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 ... AmbientLight-Bricklet UID "%s" initialisiert' % uid)
Exemplo n.º 10
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
# -*- coding: utf-8 -*-  

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

from tinkerforge.ip_connection import IPConnection
from tinkerforge.bricklet_ambient_light import AmbientLight

# Callback function for illuminance callback (parameter has unit Lux/10)
def cb_illuminance(illuminance):
    print('Illuminance: ' + str(illuminance/10.0) + ' Lux')

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

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

    # Set Period for illuminance callback to 1s (1000ms)
    # Note: The illuminance callback is only called every second if the 
    #       illuminance has changed since the last call!
    al.set_illuminance_callback_period(1000)

    # Register illuminance callback to function cb_illuminance
    al.register_callback(al.CALLBACK_ILLUMINANCE, cb_illuminance)

    raw_input('Press key to exit\n') # Use input() in Python 3
    ipcon.disconnect()
Exemplo n.º 12
0
class BrickletAmbientLight:
    _QUOTIENT = 10.0

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

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

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

    ambient_light = property(read)
    rising = property(read_rising)
    falling = property(read_falling)
Exemplo n.º 13
0
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))
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)
HOST = "localhost"
PORT = 4223
UID = "XYZ" # Change to your UID

from tinkerforge.ip_connection import IPConnection
from tinkerforge.bricklet_ambient_light import AmbientLight

# Callback for illuminance greater than 200 Lux
def cb_reached(illuminance):
    print('We have ' + str(illuminance/10.0) + ' Lux.')
    print('Too bright, close the curtains!')

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

    # Register threshold reached callback to function cb_reached
    al.register_callback(al.CALLBACK_ILLUMINANCE_REACHED, cb_reached)

    # Configure threshold for "greater than 200 Lux" (unit is Lux/10)
    al.set_illuminance_callback_threshold('>', 200*10, 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_ambient_light import AmbientLight

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

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

    # Get current illuminance (unit is Lux/10)
    illuminance = al.get_illuminance()/10.0

    print('Illuminance: ' + str(illuminance) + ' Lux')

    raw_input('Press key to exit\n') # Use input() in Python 3
    ipcon.disconnect()
Exemplo n.º 17
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)
Exemplo n.º 18
0
    def cb_enumerate(cls, uid, connected_uid, position, hardware_version,
                     firmware_version, device_identifier, enumeration_type):
        #global self.led
        found = False
        if enumeration_type == IPConnection.ENUMERATION_TYPE_CONNECTED or \
           enumeration_type == IPConnection.ENUMERATION_TYPE_AVAILABLE:
            # Enumeration for LED
            if device_identifier == LEDStrip.DEVICE_IDENTIFIER:
                cls.LEDs.append(LEDStrip(uid, cls.ipcon))
                temp_uid = str(cls.LEDs[-1].get_identity()[1]) + "." + str(
                    cls.LEDs[-1].get_identity()[0])
                cls.LEDList.addLED(cls.LEDs[-1], temp_uid)
                cls.LEDs[-1].set_frame_duration(200)
                if settings.LEDs.get(temp_uid) <> None:
                    cls.LEDs[-1].set_chip_type(settings.LEDs.get(temp_uid)[0])
                    cls.LEDs[-1].set_frame_duration(
                        settings.LEDs.get(temp_uid)[1])
                    found = True
                #self.led.register_callback(self.led.CALLBACK_FRAME_RENDERED,
                #                lambda x: __cb_frame_rendered__(self.led, x))
                #self.led.set_rgb_values(0, self.NUM_LEDS, self.r, self.g, self.b)
                #self.led.set_rgb_values(15, self.NUM_LEDS, self.r, self.g, self.b)
                #self.led.set_rgb_values(30, self.NUM_LEDS, self.r, self.g, self.b)

            if device_identifier == IO16.DEVICE_IDENTIFIER:
                cls.io.append(IO16(uid, cls.ipcon))
                temp_uid = str(cls.io[-1].get_identity()[1]) + "." + str(
                    cls.io[-1].get_identity()[0])
                cls.io16list.addIO(cls.io[-1], temp_uid, 16)
                cls.io[-1].set_debounce_period(100)
                if settings.IO16.get(temp_uid) <> None:
                    cls.io[-1].set_port_interrupt(
                        'a',
                        settings.IO16.get(temp_uid)[0])
                    cls.io[-1].set_port_interrupt(
                        'b',
                        settings.IO16.get(temp_uid)[1])
                    cls.io[-1].set_port_configuration(
                        'a',
                        settings.IO16.get(temp_uid)[0], 'i', True)
                    cls.io[-1].set_port_configuration(
                        'b',
                        settings.IO16.get(temp_uid)[1], 'i', True)
                    cls.io[-1].set_port_configuration(
                        'a',
                        settings.IO16.get(temp_uid)[2], 'o', False)
                    cls.io[-1].set_port_configuration(
                        'b',
                        settings.IO16.get(temp_uid)[3], 'o', False)
                    #self.io[-1].set_port_monoflop('a', tifo_config.IO16.get(temp_uid)[4],0,tifo_config.IO16.get(temp_uid)[6])
                    #self.io[-1].set_port_monoflop('b', tifo_config.IO16.get(temp_uid)[5],0,tifo_config.IO16.get(temp_uid)[6])
                    cls.io[-1].register_callback(
                        cls.io[-1].CALLBACK_INTERRUPT,
                        partial(cls.cb_interrupt,
                                device=cls.io[-1],
                                uid=temp_uid))
                    found = True

            if device_identifier == AmbientLight.DEVICE_IDENTIFIER:
                cls.al.append(AmbientLight(uid, cls.ipcon))
                cls.al[-1].set_illuminance_callback_threshold('o', 0, 0)
                cls.al[-1].set_debounce_period(10)
                #self.al.set_illuminance_callback_threshold('<', 30, 30)
                #self.al.set_analog_value_callback_period(10000)
                #self.al.set_illuminance_callback_period(10000)
                #self.al.register_callback(self.al.CALLBACK_ILLUMINANCE, self.cb_ambLight)
                #self.al.register_callback(self.al.CALLBACK_ILLUMINANCE_REACHED, self.cb_ambLight)
                args = cls.al[-1]
                #self.al[-1].register_callback(self.al[-1].CALLBACK_ILLUMINANCE_REACHED, lambda event1, event2, event3, args=args: self.cb_ambLight(event1, event2, event3, args))

                cls.al[-1].register_callback(
                    cls.al[-1].CALLBACK_ILLUMINANCE_REACHED,
                    partial(cls.cb_ambLight, device=args))
                temp_uid = str(cls.al[-1].get_identity()[1]) + "." + str(
                    cls.al[-1].get_identity()[0])

                thread_cb_amb = Timer(60, cls.thread_ambLight, [cls.al[-1]])
                thread_cb_amb.start()

            if device_identifier == BrickletCO2.DEVICE_IDENTIFIER:
                cls.co2.append(BrickletCO2(uid, cls.ipcon))
                temp_uid = str(cls.co2[-1].get_identity()[1]) + "." + str(
                    cls.co2[-1].get_identity()[0])
                thread_co2_ = Timer(5, cls.thread_CO2, [cls.co2[-1]])
                thread_co2_.start()
                cls.threadliste.append(thread_co2_)

            if device_identifier == BrickletDualRelay.DEVICE_IDENTIFIER:
                cls.drb.append(BrickletDualRelay(uid, cls.ipcon))


#
#            if device_identifier == Moisture.DEVICE_IDENTIFIER:
#                self.moist = Moisture(uid, self.ipcon)
#                self.moist.set_moisture_callback_period(10000)
#                self.moist.register_callback(self.moist.CALLBACK_MOISTURE, self.cb_moisture)

            if device_identifier == BrickletMotionDetector.DEVICE_IDENTIFIER:
                cls.md.append(BrickletMotionDetector(uid, cls.ipcon))
                temp_uid = str(cls.md[-1].get_identity()[1]) + "." + str(
                    cls.md[-1].get_identity()[0])
                cls.md[-1].register_callback(
                    cls.md[-1].CALLBACK_MOTION_DETECTED,
                    partial(cls.cb_md, device=cls.md[-1], uid=temp_uid))
                cls.md[-1].register_callback(
                    cls.md[-1].CALLBACK_DETECTION_CYCLE_ENDED,
                    partial(cls.cb_md_end, device=cls.md[-1], uid=temp_uid))

            if device_identifier == BrickletSoundIntensity.DEVICE_IDENTIFIER:
                cls.si.append(BrickletSoundIntensity(uid, cls.ipcon))
                temp_uid = str(cls.si[-1].get_identity()[1]) + "." + str(
                    cls.si[-1].get_identity()[0])

                cls.si[-1].set_debounce_period(1000)
                cls.si[-1].register_callback(
                    cls.si[-1].CALLBACK_INTENSITY_REACHED,
                    partial(cls.cb_si, device=cls.si[-1], uid=temp_uid))
                cls.si[-1].set_intensity_callback_threshold('>', 200, 0)

            if device_identifier == BrickletPTC.DEVICE_IDENTIFIER:
                cls.ptc.append(BrickletPTC(uid, cls.ipcon))
                temp_uid = str(cls.ptc[-1].get_identity()[1]) + "." + str(
                    cls.ptc[-1].get_identity()[0])
                thread_pt_ = Timer(5, cls.thread_pt, [cls.ptc[-1]])
                thread_pt_.start()
                cls.threadliste.append(thread_pt_)

            if device_identifier == BrickletTemperature.DEVICE_IDENTIFIER:
                cls.temp.append(BrickletTemperature(uid, cls.ipcon))
                temp_uid = str(cls.temp[-1].get_identity()[1]) + "." + str(
                    cls.temp[-1].get_identity()[0])
                thread_pt_ = Timer(5, cls.thread_pt, [cls.temp[-1]])
                thread_pt_.start()
                cls.threadliste.append(thread_pt_)

            if device_identifier == BrickMaster.DEVICE_IDENTIFIER:
                cls.master.append(BrickMaster(uid, cls.ipcon))
                thread_rs_error = Timer(60, cls.thread_RSerror, [])
                #thread_rs_error.start()
                if settings.inputs.get(uid) <> None:
                    found = True

            if not found:
                toolbox.log(connected_uid, uid, device_identifier)
                print connected_uid, uid, device_identifier
Exemplo n.º 19
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)
Exemplo n.º 20
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)
Exemplo n.º 21
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)