コード例 #1
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 == BrickletLCD128x64.DEVICE_IDENTIFIER:
             try:
                 # Initialize newly enumerated LCD128x64 Bricklet
                 self.lcd = BrickletLCD128x64(uid, self.ipcon)
                 self.lcd.clear_display()
                 self.lcd.write_line(0, 0, "   Weather Station")
                 log.info('LCD 128x64 initialized')
             except Error as e:
                 log.error('LCD 128x64 init failed: ' + str(e.description))
                 self.lcd = None
         elif device_identifier == BrickletAirQuality.DEVICE_IDENTIFIER:
             try:
                 # Initialize newly enumaratedy Air Quality Bricklet and configure callbacks
                 self.air_quality = BrickletAirQuality(uid, self.ipcon)
                 self.air_quality.set_all_values_callback_configuration(
                     1000, False)
                 self.air_quality.register_callback(
                     self.air_quality.CALLBACK_ALL_VALUES,
                     self.cb_all_values)
                 log.info('Air Quality initialized')
             except Error as e:
                 log.error('Air Quality init failed: ' + str(e.description))
                 self.air_quality = None
コード例 #2
0
def ConfigAirQuality(self):
    Domoticz.Debug("ConfigAirQuality - UID:" +
                   self.UIDList[UIDINDEXAIRQUALITY])
    try:
        # Create IP connection
        ipcon = IPConnection()
        # Create device object
        aq = BrickletAirQuality(self.UIDList[UIDINDEXAIRQUALITY], ipcon)
        # Connect to brickd
        ipcon.connect(Parameters["Address"], int(Parameters["Port"]))
        # Don't use device before ipcon is connected

        # Turn off status led
        aq.set_status_led_config(0)
        Domoticz.Log("Air Quality Status LED disabled.")

        # Set temperature offset with resolution 1/100°C. Offset 10 = decrease measured temperature by 0.1°C, 100 = 1°C.
        # offset - int
        # Test with 2°C = 200
        aq.set_temperature_offset(200)

        # The Air Quality Bricklet uses an automatic background calibration mechanism to calculate the IAQ Index.
        # This calibration mechanism considers a history of measured data. Duration history = 4 days (0) or 28 days (1).
        # duration - int 0 | 1
        # Test with 0 = 4 days
        aq.set_background_calibration_duration(0)

        ipcon.disconnect()

        return 1

    except:
        # Error
        Domoticz.Log("[ERROR] Can not set Air Quality Status LED.")
        return 0
コード例 #3
0
    def cb_enumerate(self, uid, connected_uid, position, hardware_version,
                     firmware_version, device_identifier, enumeration_type):
        #print("UID:               " + uid)
        #print("Enumeration Type:  " + str(enumeration_type))

        if enumeration_type == IPConnection.ENUMERATION_TYPE_DISCONNECTED:
            #print("")
            return

        #print("Connected UID:     " + connected_uid)
        #print("Position:          " + position)
        #print("Hardware Version:  " + str(hardware_version))
        #print("Firmware Version:  " + str(firmware_version))
        #print("Device Identifier: " + str(device_identifier))
        #print("")

        if device_identifier == BrickletLoadCellV2.DEVICE_IDENTIFIER:
            self.loadcell = BrickletLoadCellV2(uid, self.ipcon)

        if device_identifier == BrickletAirQuality.DEVICE_IDENTIFIER:
            airquality = BrickletAirQuality(uid, self.ipcon)
            self.hygrometer = airquality
            self.barometer = airquality

        if device_identifier == BrickletVoltageCurrentV2.DEVICE_IDENTIFIER:
            self.voltage = BrickletVoltageCurrentV2(uid, self.ipcon)

        if device_identifier == BrickletPTCV2.DEVICE_IDENTIFIER:
            self.ptc = BrickletPTCV2(uid, self.ipcon)
            if not self.ptc.is_sensor_connected():
                self.ptc = None
                return

            self.ptc.set_wire_mode(BrickletPTCV2.WIRE_MODE_4)
コード例 #4
0
def cb_enumerate(uid, connected_uid, position, hardware_version,
                 firmware_version, device_identifier, enumeration_type):
    global motionDetector
    global airQuality
    global ambientLight
    global barometer
    if enumeration_type == IPConnection.ENUMERATION_TYPE_CONNECTED or \
       enumeration_type == IPConnection.ENUMERATION_TYPE_AVAILABLE:
        if device_identifier == BrickletMotionDetectorV2.DEVICE_IDENTIFIER:
            try:
                motionDetector = BrickletMotionDetectorV2(uid, ipcon)
                log.info("Motion Detector init success")
            except Error as e:
                log.error("Motion Detector init failed")
        elif device_identifier == BrickletAmbientLightV3.DEVICE_IDENTIFIER:
            try:
                ambientLight = BrickletAmbientLightV3(uid, ipcon)
                log.info("AL init success")
            except Error as e:
                log.error("Ambient Light init failed")
        elif device_identifier == BrickletBarometerV2.DEVICE_IDENTIFIER:
            try:
                barometer = BrickletBarometerV2(uid, ipcon)
                log.info("Barometer init success")
                log.info(barometer.get_temperature())
            except Error as e:
                log.error("Barometer init failed")
        elif device_identifier == BrickletAirQuality.DEVICE_IDENTIFIER:
            try:
                airQuality = BrickletAirQuality(uid, ipcon)
                log.info("AQ init success")
            except Error as e:
                log.error("Air Quality init failed")
コード例 #5
0
def SetAirQualityStatusLed(self, state):
    Domoticz.Debug("SetAirQualityStatusLed - UID:" +
                   self.UIDList[UIDINDEXAIRQUALITY])
    try:
        # Create IP connection
        ipcon = IPConnection()
        # Create device object
        aq = BrickletAirQuality(self.UIDList[UIDINDEXAIRQUALITY], ipcon)
        # Connect to brickd
        ipcon.connect(Parameters["Address"], int(Parameters["Port"]))
        # Don't use device before ipcon is connected
        if state == 0:
            aq.set_status_led_config(state)
            Domoticz.Log("Air Quality Status LED disabled.")

        if state == 1:
            aq.set_status_led_config(state)
            Domoticz.Log("Air Quality Status LED enabled.")

        ipcon.disconnect()

        return 1

    except:
        # Error
        Domoticz.Log("[ERROR] Can not set Air Quality Status LED.")
        return 0
コード例 #6
0
            "air_quality": air_quality,
        },
        "tags": {
            "node": "server",
            "location": "salon",
            "sensor": "airquality",
        },
    }]

    client.write_points(json_body)

    ipcon = IPConnection()  # Create IP connection


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

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

    # Register all values callback to function cb_all_values
    aq.register_callback(aq.CALLBACK_ALL_VALUES, cb_all_values)

    # Set period for all values callback to 1s (1000ms)
    aq.set_all_values_callback_configuration(10000, False)
    while loop > 0:

        loop = 10

    ipcon.disconnect()
コード例 #7
0
def InitBricks(self):
    Domoticz.Debug("InitBricks")
    try:
        # Create IP connection
        ipcon = IPConnection()

        # Create device objects
        master = BrickMaster(self.UIDList[UIDINDEXMASTER], ipcon)
        rl = BrickletRGBLEDV2(self.UIDList[UIDINDEXRGBLED], ipcon)
        aq = BrickletAirQuality(self.UIDList[UIDINDEXAIRQUALITY], ipcon)
        lcd = BrickletLCD20x4(self.UIDList[UIDINDEXLCD], ipcon)

        # Connect to brickd
        ipcon.connect(Parameters["Address"], int(Parameters["Port"]))

        # Settings

        ## Master - Turn status led off
        master.disable_status_led()
        Domoticz.Log("Master Status LED disabled.")

        ## RGB LED - Turn status led off
        rl.set_status_led_config(0)
        Domoticz.Log("RGB LED Status LED disabled.")

        ## Air Quality - Config
        ## Turn off status led
        aq.set_status_led_config(0)
        Domoticz.Log("Air Quality Status LED disabled.")
        # Set temperature offset with resolution 1/100°C. Offset 10 = decrease measured temperature by 0.1°C, 100 = 1°C.
        # offset - int
        # Test with 2°C = 200
        aq.set_temperature_offset(200)
        # The Air Quality Bricklet uses an automatic background calibration mechanism to calculate the IAQ Index.
        # This calibration mechanism considers a history of measured data. Duration history = 4 days (0) or 28 days (1).
        # duration - int 0 | 1
        # Test with 0 = 4 days
        aq.set_background_calibration_duration(0)

        ## LCD - Turn backlight ON (ensure to update the domoticz switch device), set initial welcome text.
        lcd.backlight_on()
        Devices[UNITSWITCHBACKLIGHT].Update(nValue=1, sValue=str(0))
        SetLCDText(self, "Indoor Air Quality", "Station " + PLUGINVERSION, "",
                   "2019 by rwbl")

        # Disconnect and return OK
        ipcon.disconnect()

        Domoticz.Debug("InitBricks OK")

        self.isError = 0

        return 1

    except:
        # Error
        self.isError = 1
        Domoticz.Log("[ERROR] Can not init the bricks.")
        return 0

    return
コード例 #8
0
    def onHeartbeat(self):
        self.HeartbeatCounter = self.HeartbeatCounter + 1
        Domoticz.Debug("onHeartbeat called. Counter=" +
                       str(self.HeartbeatCounter * self.HeartbeatInterval) +
                       " (Heartbeat=" + Parameters["Mode5"] + ")")

        # Reset ipconnected flag
        self.ipConnected = 0

        # check the heartbeatcounter against the heartbeatinterval
        if (self.HeartbeatCounter * self.HeartbeatInterval) % int(
                Parameters["Mode5"]) == 0:

            try:

                # Create IP connection
                ipcon = IPConnection()
                Domoticz.Debug("IP Connected created")

                # Create the device objects
                master = BrickMaster(self.UIDList[UIDINDEXMASTER], ipcon)
                aq = BrickletAirQuality(self.UIDList[UIDINDEXAIRQUALITY],
                                        ipcon)
                lcd = BrickletLCD20x4(self.UIDList[UIDINDEXLCD], ipcon)
                rl = BrickletRGBLEDV2(self.UIDList[UIDINDEXRGBLED], ipcon)
                al = BrickletAmbientLightV2(self.UIDList[UIDINDEXAMBIENTLIGHT],
                                            ipcon)
                Domoticz.Debug("Devices created - OK")

                # Connect to brickd using Host and Port
                try:
                    ipcon.connect(Parameters["Address"],
                                  int(Parameters["Port"]))
                    self.ipConnected = 1
                    Domoticz.Debug("IP Connection - OK")
                except:
                    self.isError = 1
                    Domoticz.Debug("[ERROR] IP Connection failed")

                # Don't use device before ipcon is connected

                # Set Alert Indicator to Orange with ERROR text
                if self.ipConnected == 0:
                    ## Alert device (5)nvalue=LEVEL - (0=gray, 1=green, 2=yellow, 3=orange, 4=red),svalue=TEXT
                    # Devices[ALERTDEVICE].Update( nValue=3, sValue="ERROR")
                    #Domoticz.Debug(Devices[ALERTDEVICE].Name + "-nValue=" + str(Devices[ALERTDEVICE].nValue) + ",sValue=" + Devices[ALERTDEVICE].sValue  )
                    Devices[UNITTEXTSTATUS].Update(
                        nValue=0,
                        sValue=
                        "[ERROR] Can not connect to the Master Brick. Check device or settings."
                    )
                    Domoticz.Log(Devices[UNITTEXTSTATUS].sValue)
                    self.isError = 1
                    return

                # If there was an error in the connection,init the bricks again
                if self.isError == 1 and self.ipConnected == 1:
                    InitBricks(self)
                    self.isError = 0

                # AIR QUALITY
                # Get current all values
                iaq_index, iaq_index_accuracy, temperature, humidity, air_pressure = aq.get_all_values(
                )

                ## TESTdata with using the air quality bricklet
                '''
                iaq_index = 69 # 0 -200
                iaq_index_accuracy = 21
                temperature = 2432
                humidity = 6894
                air_pressure = 102412
                '''

                # Update the devices

                # IAQ (Indoor Air Quality) Index
                ## nValue=0
                ## sValue=string value
                Devices[UNITAIRQUALITYIAQINDEX].Update(nValue=0,
                                                       sValue=str(iaq_index))
                # Devices[UNITAIRQUALITYIAQINDEX].Update( nValue=iaq_index, sValue="0")
                Domoticz.Debug(Devices[UNITAIRQUALITYIAQINDEX].Name +
                               "-IAQ Index:" + str(iaq_index))

                # IAQ Index Accuracy
                ## nvalue=LEVEL - (0=gray, 1=green, 2=yellow, 3=orange, 4=red)
                ## svalue=TEXT
                iaqaccuracylevel = 0
                if iaq_index_accuracy == aq.ACCURACY_UNRELIABLE:
                    iaqaccuracylevel = 4
                elif iaq_index_accuracy == aq.ACCURACY_LOW:
                    iaqaccuracylevel = 3
                elif iaq_index_accuracy == aq.ACCURACY_MEDIUM:
                    iaqaccuracylevel = 2
                elif iaq_index_accuracy == aq.ACCURACY_HIGH:
                    iaqaccuracylevel = 1
                iaqaccuracytext = AIRQUALITYACCURACY[iaqaccuracylevel]
                Devices[UNITALERTIAQINDEXACCURACY].Update(
                    nValue=iaqaccuracylevel, sValue=iaqaccuracytext)
                Domoticz.Debug(Devices[UNITALERTIAQINDEXACCURACY].Name +
                               "-IAQ IndexAccuracy:" + str(iaqaccuracylevel) +
                               "," + iaqaccuracytext)

                # Air Quality
                ## nvalue=LEVEL - see xml definition
                ## svalue=TEXT
                airqualitylevel = 0
                if iaq_index >= 0 and iaq_index <= AIRQUALITYLEVELLIMIT[1]:
                    airqualitylevel = 1

                if iaq_index > AIRQUALITYLEVELLIMIT[
                        1] and iaq_index <= AIRQUALITYLEVELLIMIT[2]:
                    airqualitylevel = 2

                if iaq_index > AIRQUALITYLEVELLIMIT[
                        2] and iaq_index <= AIRQUALITYLEVELLIMIT[3]:
                    airqualitylevel = 3

                if iaq_index > AIRQUALITYLEVELLIMIT[
                        3] and iaq_index <= AIRQUALITYLEVELLIMIT[4]:
                    airqualitylevel = 4

                if iaq_index > AIRQUALITYLEVELLIMIT[
                        4] and iaq_index <= AIRQUALITYLEVELLIMIT[5]:
                    airqualitylevel = 5

                if iaq_index > AIRQUALITYLEVELLIMIT[5]:
                    airqualitylevel = 6

                airqualitytext = AIRQUALITYLEVELCONDITION[airqualitylevel]
                Devices[UNITALERTAIRQUALITY].Update(nValue=airqualitylevel,
                                                    sValue=airqualitytext)
                Domoticz.Debug("Air Quality:" + str(airqualitylevel) + "," +
                               airqualitytext)

                # Temperature
                ## nvalue=0
                ## svalue=temperature/100
                ## print("Temperature: " + str(temperature/100.0) + " °C")
                if temperature > 0:
                    temperature = int(round(temperature / 100.0))
                Devices[UNITTEMPERATURE].Update(nValue=0,
                                                sValue=str(temperature))
                Domoticz.Debug(Devices[UNITTEMPERATURE].Name +
                               "-Temperature:" + str(temperature))

                # Humidity
                # nvalue=humidity
                # svalue=humiditystatus - 0=Normal,1=Comfortable,2=Dry,3=Wet
                # print("Humidity: " + str(humidity/100.0) + " %RH")
                if humidity > 0:
                    humidity = int(round(humidity / 100.0))
                humiditystatus = GetHumidityStatus(humidity)
                Devices[UNITHUMIDITY].Update(nValue=humidity,
                                             sValue=str(humiditystatus))
                Domoticz.Debug(Devices[UNITHUMIDITY].Name + "-Humidity:" +
                               str(humidity))

                # Air Pressure
                # nvalue=0
                # svalue=airpressure/100;prediction
                # print("Air Pressure: " + str(air_pressure/100.0) + " mbar")
                if air_pressure > 0:
                    air_pressure = int(round(air_pressure / 100.0))
                Devices[UNITBAROMETER].Update(nValue=0,
                                              sValue=str(air_pressure) + ";0")
                Domoticz.Debug(Devices[UNITBAROMETER].Name + "-Air Pressure:" +
                               str(air_pressure))

                Domoticz.Debug("Air Quality Devices updated")

                # AMBIENT LIGHT
                ## Get current illuminance
                ## nvalue=0
                ## svalue=illuminance/100
                illuminance = al.get_illuminance()
                if illuminance > 0:
                    illuminance = int(round(illuminance / 100.0))
                #print("Illuminance: " + str(illuminance/100.0) + " lx")
                Devices[UNITILLUMINATION].Update(nValue=0,
                                                 sValue=str(illuminance))
                Domoticz.Debug(Devices[UNITILLUMINATION].Name + "-Lux:" +
                               str(illuminance))

                #
                ## Tinkerforge Bricklet Updates
                #
                Domoticz.Debug("Tinkerforge updating...")

                ## LCD Display
                ## Writes text to a specific line (0 to 3) with a specific position (0 to 19). The text can have a maximum of 20 characters.

                ## Turn backlight on NOTE: done in onStart
                ## lcd.backlight_on()
                ## Domoticz.Debug("LCD Backlight ON")

                ## Clear the display
                lcd.clear_display()
                Domoticz.Debug("LCD Display cleared")

                ## Get the values as strings to write on the lcd
                ## AQI
                lcdaqi = str(iaq_index)

                ## TT:HH - TT=Temperature,HH=Humidity
                lcdtemperature = str(temperature)
                lcdhumidity = "HH"
                if humidity < 100:
                    lcdhumidity = str(humidity)

                ## airpressure
                lcdairpressure = str(air_pressure)

                ## illuminance
                lcdilluminance = str(illuminance)

                ## write to the lcd: line (int,0-3),pos(int,0-19),text
                lcd.write_line(0, 0, "Q: " + lcdaqi + " ppm " + airqualitytext)
                lcd.write_line(1, 0, "T: " + lcdtemperature + " C")
                lcd.write_line(1, 14, "H: " + lcdhumidity + "%")
                lcd.write_line(2, 0, "P: " + lcdairpressure + " mbar")
                lcd.write_line(3, 0, "L: " + lcdilluminance + " lx")
                lcd.write_line(3, 14, PLUGINVERSION)
                Domoticz.Debug("LCD Lines written")

                ## rgb led set color depending indoor air quality index
                ## Set the brightness using the value of the parameter Mode2
                lbbrightness = int(Parameters["Mode2"])
                if lbbrightness < RGBBRIGHTNESSMIN:
                    lbbrightness = RGBBRIGHTNESSMIN
                if lbbrightness > RGBBRIGHTNESSMAX:
                    lbbrightness = RGBBRIGHTNESSMAX

                rl.set_rgb_value(
                    SetRGBColor(AIRQUALITYLEVELCOLOR[airqualitylevel][0],
                                lbbrightness),
                    SetRGBColor(AIRQUALITYLEVELCOLOR[airqualitylevel][1],
                                lbbrightness),
                    SetRGBColor(AIRQUALITYLEVELCOLOR[airqualitylevel][2],
                                lbbrightness))
                Domoticz.Debug("RGB LED Color set")

                # Log Message
                Devices[UNITTEXTSTATUS].Update(
                    nValue=0,
                    sValue="OK: " + lcdaqi + "," + lcdtemperature + "," +
                    lcdhumidity + "," + lcdairpressure)
                Domoticz.Log(Devices[UNITTEXTSTATUS].sValue)

                # Disconnect
                ipcon.disconnect()

                # Log Message
                Domoticz.Debug("Update OK.")

            except:
                # Error
                self.isError == 1
                # Important to close the connection - if not, the plugin can not be disabled
                if self.ipConnected == 1:
                    ipcon.disconnect()

                Devices[UNITTEXTSTATUS].Update(
                    nValue=0,
                    sValue=
                    "[ERROR] Check settings, correct and restart Domoticz.")
                Domoticz.Log(Devices[UNITTEXTSTATUS].sValue)
コード例 #9
0
class WeatherStation:
    HOST = "localhost"
    PORT = 4223

    ipcon = None
    lcd = None
    air_quality = None

    def __init__(self):
        self.ipcon = IPConnection()  # Create IP connection

        # Connect to brickd (retry if not possible)
        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)

        # Enumerate Bricks and Bricklets (retry if not possible)
        while True:
            try:
                self.ipcon.enumerate()
                break
            except Error as e:
                log.error('Enumerate Error: ' + str(e.description))
                time.sleep(1)

    def cb_all_values(self, iaq_index, iaq_index_accuracy, temperature,
                      humidity, air_pressure):
        if self.lcd is not None:
            self.lcd.write_line(2, 0, 'IAQ:      {0:6}'.format(iaq_index))
            # 0xF8 == ° on LCD 128x64 charset
            self.lcd.write_line(
                3, 0, 'Temp:     {0:6.2f} {1}C'.format(temperature / 100.0,
                                                       chr(0xF8)))
            self.lcd.write_line(
                4, 0, 'Humidity: {0:6.2f} %RH'.format(humidity / 100.0))
            self.lcd.write_line(
                5, 0, 'Air Pres: {0:6.1f} mbar'.format(air_pressure / 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 == BrickletLCD128x64.DEVICE_IDENTIFIER:
                try:
                    # Initialize newly enumerated LCD128x64 Bricklet
                    self.lcd = BrickletLCD128x64(uid, self.ipcon)
                    self.lcd.clear_display()
                    self.lcd.write_line(0, 0, "   Weather Station")
                    log.info('LCD 128x64 initialized')
                except Error as e:
                    log.error('LCD 128x64 init failed: ' + str(e.description))
                    self.lcd = None
            elif device_identifier == BrickletAirQuality.DEVICE_IDENTIFIER:
                try:
                    # Initialize newly enumaratedy Air Quality Bricklet and configure callbacks
                    self.air_quality = BrickletAirQuality(uid, self.ipcon)
                    self.air_quality.set_all_values_callback_configuration(
                        1000, False)
                    self.air_quality.register_callback(
                        self.air_quality.CALLBACK_ALL_VALUES,
                        self.cb_all_values)
                    log.info('Air Quality initialized')
                except Error as e:
                    log.error('Air Quality init failed: ' + str(e.description))
                    self.air_quality = None

    def cb_connected(self, connected_reason):
        # Eumerate again after auto-reconnect
        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)
コード例 #10
0
def get_bricklet_data():
    # Create the JSON object
    data = {}
    # Connect to the master brick and get the data from the air quality bricklet
    try:
        # Create IP connection
        ipcon = IPConnection()

        # Create device object
        aq = BrickletAirQuality(TFUID, ipcon)

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

        # Get calibration duration
        log.info("Calibration Duration Days [0=4,1=28]:" + str(aq.get_background_calibration_duration()))
        
        # Set status LED
        aq.set_status_led_config(IQA_STATUS_LED)
        log.info("Status LED:" + str(aq.get_status_led_config()))

        # Set temperature offset by 2°C (10=0.1°C, measured against real room temperature)
        # Note: Check from time-to-time if still ok
        aq.set_temperature_offset(200)
        log.info("Temperature Offset:" + str(aq.get_temperature_offset() * 0.01))
        
        # Get all values
        iaq_index, iaq_index_accuracy, temperature, humidity, \
          air_pressure = aq.get_all_values()
          
        # Assign the values to the JSON object
        data['iaqindex'] = iaq_index
        log.info("IAQ Index:" + str(iaq_index))

        # IAQ index range 0-500:0-50(good),51-100(average),101-150(little bad),151-200(bad),201-300(worse),301-500(very bad).
        iaq_quality = IQA_QUALITY_UNKNOWN
        if iaq_index >= 0 and iaq_index < 51:
            iaq_quality = IQA_QUALITY_GOOD
        elif iaq_index > 50 and iaq_index < 101:
            iaq_quality = IQA_QUALITY_AVERAGE
        elif iaq_index > 100 and iaq_index < 150:
            iaq_quality = IQA_QUALITY_LITTLEBAD
        elif iaq_index > 150 and iaq_index < 201:
            iaq_quality = IQA_QUALITY_BAD
        elif iaq_index > 200 and iaq_index < 301:
            iaq_quality = IQA_QUALITY_WORSE
        elif iaq_index > 300 and iaq_index < 501:
            iaq_quality = IQA_QUALITY_VERYBAD
        data['iaqquality'] = iaq_quality
        log.info("IAQ Quality:" + iaq_quality)

        iaq_accuracy = "Unknown"
        if iaq_index_accuracy == aq.ACCURACY_UNRELIABLE:
            iaq_accuracy = "Unreliable"
        elif iaq_index_accuracy == aq.ACCURACY_LOW:
            iaq_accuracy = "Low"
        elif iaq_index_accuracy == aq.ACCURACY_MEDIUM:
            iaq_accuracy = "Medium"
        elif iaq_index_accuracy == aq.ACCURACY_HIGH:
            iaq_accuracy = "High"
        data['iaqaccuracy'] = iaq_accuracy
        log.info("IAQ Index Accuracy:" + iaq_accuracy)

        data['temperature'] = temperature/100.0
        log.info("Temperature:" + str(temperature/100.0) + " °C")

        data['humidity'] = humidity/100.0
        log.info("Humidity:" + str(humidity/100.0) + " %RH")

        data['airpressure'] = air_pressure/100.0
        log.info("Air Pressure:" + str(air_pressure/100.0) + " hPa")

        # Disconnect
        ipcon.disconnect()

        data['status'] = "OK"
        data['title'] = "get_bricklet_data"
        log.info(data['status'] + ","+ data['title'])
    
    # Handle errors
    except OSError as e:
        data['status'] = "ERR"
        data['title'] = "OS Error: " + str(e.strerror)
        log.error(data['status'] + ","+ data['title'])
        time.sleep(1)
        
    # Return the data
    return json.dumps(data)
コード例 #11
0
HOST = "localhost"
PORT = 4223
UID_CO2 = "XYZ1"  # Change XYZ1 to the UID of your CO2 Bricklet 2.0
UID_AQ = "XYZ2"  # Change XYZ2 to the UID of your Air Quality Bricklet

from tinkerforge.ip_connection import IPConnection
from tinkerforge.bricklet_co2_v2 import BrickletCO2V2
from tinkerforge.bricklet_air_quality import BrickletAirQuality

import time

if __name__ == "__main__":
    ipcon = IPConnection()  # Create IP connection
    co2 = BrickletCO2V2(UID_CO2, ipcon)  # Create device object
    aq = BrickletAirQuality(UID_AQ, ipcon)  # Create device object

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

    # Get air pressure in 0.01 hPa
    air_pressure = aq.get_air_pressure()

    # Set air pressure for calibration in hPa
    co2.set_air_pressure(air_pressure // 100)

    # Get current all values
    while True:
        co2_concentration, temperature, humidity = co2.get_all_values()

        print("CO2 Concentration: " + str(co2_concentration) + " ppm")
コード例 #12
0
##Inititalisation
if __name__ == "__main__":
    ipcon = IPConnection()  # Create IP connection
    master = BrickMaster(masterUID, ipcon)  # Create device object

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

    master.disable_status_led()

    ipcon.disconnect()

if __name__ == "__main__":
    ipcon = IPConnection()  # Create IP connection
    air = BrickletAirQuality(airUID, ipcon)  # Create device object

    ipcon.connect(HOST, PORT)  # Connect to brickd
    air.set_temperature_offset(2)
    air.set_status_led_config(0)
    ipcon.disconnect()

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from influxdb import InfluxDBClient
import time
import os

# turn on the green LED
os.system("sudo bash -c \"echo 0 > /sys/class/leds/led0/brightness\"")
os.system("sudo bash -c \"echo 0 > /sys/class/leds/led1/brightness\"")
コード例 #13
0
ファイル: airquality.py プロジェクト: scurth/tf_to_influxdb
import datetime
import time

from tinkerforge.ip_connection import IPConnection
from tinkerforge.bricklet_air_quality import BrickletAirQuality
from influxdb import InfluxDBClient

now = 0
json_body = []
influx_args = ('localhost', 8086, 'root', '', 'tinkerforge')
dbclient = InfluxDBClient(*influx_args)

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

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

    # Get current all values
    iaq_index, iaq_index_accuracy, temperature, humidity, \
      air_pressure = aq.get_all_values()

    print("IAQ Index: " + str(iaq_index))
    iaq = str(iaq_index)

    if iaq_index_accuracy == aq.ACCURACY_UNRELIABLE:
        print("IAQ Index Accuracy: Unreliable"),
        iaq_accuracy = "Unreliable"
    elif iaq_index_accuracy == aq.ACCURACY_LOW: