Exemplo n.º 1
0
 def updateStates(self):
     for id in self.devices:
         device = self.devices[id]
         if not device: continue
         params = json.loads(device['sensor'])
         if (params['class'] == 'AirPurifier'):
             try:
                 dev = AirPurifier(params['ip'], params['token'])
                 state = str(dev.status())
                 sensors = state.split(' ')
                 for sensor in sensors:
                     sensor = sensor.replace(',', '').replace('>',
                                                              '').split('=')
                     if (len(sensor) == 2):
                         type = sensor[0]
                         value = sensor[1].replace('%', '').upper()
                         if type == 'power':
                             if value != device['state']:
                                 self.mySensors.saveSensorState(id, value)
                         elif self.updateSensorByDevice(id, type, value):
                             pass
             except DeviceException as e:
                 self.log('Error getting device state: ' + str(e))
                 self.mySensors.saveSensorState(id, 'ERR')
     self.commit()
Exemplo n.º 2
0
def log_air_purifier_events():
    threading.Timer(60.0 * 10, log_air_purifier_events).start()
    values_keys = [
        "power",
        "aqi",
        "average_aqi",
        "humidity",
        "temperature",
        "illuminance",
        "filter_life_remaining",
        "filter_hours_used",
        "motor_speed",
    ]
    air_purifier = AirPurifier(AIR_PURIFIER_IP, AIR_PURIFIER_TOKEN)
    status = air_purifier.status()
    data = {}
    for key in values_keys:
        data[key] = status.__getattribute__(key)
    data["mode"] = status.mode.value
    print(data)
    device_info = air_purifier.info()
    INFLUXDB_CLIENT.write_points([{
        "measurement": "air_purifier",
        "tags": {
            "model": device_info.model,
            "firmware_version": device_info.firmware_version,
            "hardware_version": device_info.hardware_version,
        },
        "fields": data,
    }])
Exemplo n.º 3
0
class Helper():
    def __init__(self, ip, token):
        self.ap = AirPurifier(ip=ip, token=token)
        self.status = self.ap.status()
        self.units = {}
        self.selectorData = {}
        return

    def createDomoticzDevices(self):
        Domoticz.Log("Creating devices in Domoticz")
        name = "Airpurifier"

        unit = 1
        if unit not in Devices:
            Domoticz.Debug("Creating power switch")
            Domoticz.Device(Name="Power",
                            Unit=unit,
                            Image=7,
                            TypeName="Switch").Create()
        else:
            Domoticz.Debug("Power switch already exists with unit ID: %d" %
                           (unit))
        self.units[unit] = {
            "type": "switch",
            "command": self.powerSwitch,
            "currentValue": self.powerSwitchCurrentValue,
            "dependantSwitch": {
                "unit": 2,
                "ifValue": "off",
                "setValue": 10
            }
        }

        unit = 2
        if unit not in Devices:
            Domoticz.Debug("Creating operation selector switch")
            Options = {
                "LevelActions": "||||",
                "LevelNames": "|Idle|Auto|Silent|Favorite",
                "LevelOffHidden": "true",
                "SelectorStyle": "1"
            }
            Domoticz.Device(Name="Operation selector",
                            Unit=unit,
                            Image=7,
                            TypeName="Selector Switch",
                            Options=Options).Create()
        else:
            Domoticz.Debug(
                "Operation selector switch already exists with unit ID: %d" %
                (unit))
        self.units[unit] = {
            "type": "selector",
            "command": self.operationSelectorSwitch,
            "currentValue": self.operationSelectorSwitchCurrentValue,
            "dependantSwitch": {
                "unit": 1,
                "ifValue": "10",
                "setValue": "off"
            }
        }
        self.selectorData[unit] = {
            "idle": 10,
            "auto": 20,
            "silent": 30,
            "favorite": 40,
            "10": "idle",
            "20": "auto",
            "30": "silent",
            "40": "favorite"
        }

        unit = 3
        if unit not in Devices:
            Domoticz.Debug("Creating led brightness selector switch")
            Options = {
                "LevelActions": "|||",
                "LevelNames": "|Off|Dim|Bright",
                "LevelOffHidden": "true",
                "SelectorStyle": "1"
            }
            Domoticz.Device(Name="Led brightness",
                            Unit=unit,
                            Image=7,
                            TypeName="Selector Switch",
                            Options=Options).Create()
        else:
            Domoticz.Debug(
                "Led brightness switch already exists with unit ID: %d" %
                (unit))
        self.units[unit] = {
            "type": "selector",
            "command": self.ledBrightnessSwitch,
            "currentValue": self.ledBrightnessSwitchCurrentValue
        }
        self.selectorData[unit] = {
            "2": 10,
            "1": 20,
            "0": 30,
            "10": 2,
            "20": 1,
            "30": 0
        }

        unit = 4
        if unit not in Devices:
            Domoticz.Debug("Creating favorite level selector switch")
            Options = {
                "LevelActions": "||||||||||||||||",
                "LevelNames": "|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16",
                "LevelOffHidden": "true",
                "SelectorStyle": "1"
            }
            Domoticz.Device(Name="Favorite level",
                            Unit=unit,
                            Image=7,
                            TypeName="Selector Switch",
                            Options=Options).Create()
        else:
            Domoticz.Debug(
                "Favorite level switch already exists with unit ID: %d" %
                (unit))
        self.units[unit] = {
            "type": "selector",
            "command": self.favoriteLevelSwitch,
            "currentValue": self.favoriteLevelSwitchCurrentValue
        }
        self.selectorData[unit] = {
            "1": 10,
            "2": 20,
            "3": 30,
            "4": 40,
            "5": 50,
            "6": 60,
            "7": 70,
            "8": 80,
            "9": 90,
            "10": 100,
            "11": 110,
            "12": 120,
            "13": 130,
            "14": 140,
            "15": 150,
            "16": 160,
            "10": 1,
            "20": 2,
            "30": 3,
            "40": 4,
            "50": 5,
            "60": 6,
            "70": 7,
            "80": 8,
            "90": 9,
            "100": 10,
            "110": 11,
            "120": 12,
            "130": 13,
            "140": 14,
            "150": 15,
            "160": 16
        }

        unit = 5
        if unit not in Devices:
            Domoticz.Debug("Creating air quality device")
            Options = {"Custom": "1;μg/m³"}
            Domoticz.Device(Name="Air quality",
                            Unit=unit,
                            Type=243,
                            Subtype=31,
                            Image=7,
                            Options=Options).Create()
        else:
            Domoticz.Debug(
                "Air quality device already exists with unit ID: %d" % (unit))
        self.units[unit] = {
            "type": "sensor",
            "currentValue": self.airQualityDeviceCurrentValue
        }

        unit = 6
        if unit not in Devices:
            Domoticz.Debug("Creating temperature + humidity device")
            Domoticz.Device(Name="Temperature + humidity",
                            Unit=unit,
                            Type=82,
                            Image=7).Create()
        else:
            Domoticz.Debug(
                "Temperature + humidity device already exists with unit ID: %d"
                % (unit))
        self.units[unit] = {
            "type": "sensor",
            "currentValue": self.temperatureHumidityDeviceCurrentValue
        }

        unit = 7
        if unit not in Devices:
            Domoticz.Debug("Creating filter life remaining device")
            Domoticz.Device(Name="Filter life remaining",
                            Unit=unit,
                            Type=243,
                            Subtype=6,
                            Image=7).Create()
        else:
            Domoticz.Debug(
                "Filter life remaining device already exists with unit ID: %d"
                % (unit))
        self.units[unit] = {
            "type": "sensor",
            "currentValue": self.filterLifeRemainingDeviceCurrentValue
        }

        unit = 8
        if unit not in Devices:
            Domoticz.Debug("Creating filter hours used device")
            Options = {"Custom": "1;hours"}
            Domoticz.Device(Name="Filter hours used",
                            Unit=unit,
                            Type=243,
                            Subtype=31,
                            Image=7,
                            Options=Options).Create()
        else:
            Domoticz.Debug(
                "Filter hours used device already exists with unit ID: %d" %
                (unit))
        self.units[unit] = {
            "type": "sensor",
            "currentValue": self.filterHoursUsedDeviceCurrentValue
        }

        return

    def runCommand(self, unit, command, level):
        updateValues = self.units[unit]["command"](unit, command, str(level))
        self.updateDomoticzDevice(unit, updateValues["nValue"],
                                  updateValues["sValue"])
        if "dependantSwitch" in self.units[unit] and self.units[unit][
                "dependantSwitch"]["ifValue"] == updateValues["sValue"].lower(
                ):
            self.updateDomoticzDevice(
                self.units[unit]["dependantSwitch"]["unit"],
                updateValues["nValue"],
                self.units[unit]["dependantSwitch"]["setValue"])
        return

    def powerSwitchCurrentValue(self):
        return self.status.power

    def powerSwitch(self, unit, command, level):
        nValue = 0
        sValue = "Off"
        if command.lower() == "on":
            self.ap.on()
            nValue = 1
            sValue = "On"
        else:
            self.ap.off()
        return {"nValue": nValue, "sValue": sValue}

    def operationSelectorSwitchCurrentValue(self):
        return self.status.mode.value

    def operationSelectorSwitch(self, unit, command, level):
        nValue = 0
        sValue = OperationMode(self.selectorData[unit][level])
        if sValue != "idle":
            nValue = 1
        self.ap.set_mode(sValue)
        return {"nValue": nValue, "sValue": level}

    def ledBrightnessSwitchCurrentValue(self):
        return self.status.led_brightness.value

    def ledBrightnessSwitch(self, unit, command, level):
        ps = self.powerSwitchCurrentValue()
        nValue = 0 if ps.lower() == "off" else 1
        sValue = LedBrightness(self.selectorData[unit][level])
        self.ap.set_led_brightness(sValue)
        return {"nValue": nValue, "sValue": level}

    def favoriteLevelSwitchCurrentValue(self):
        return self.status.favorite_level

    def favoriteLevelSwitch(self, unit, command, level):
        ps = self.powerSwitchCurrentValue()
        nValue = 0 if ps.lower() == "off" else 1
        sValue = self.selectorData[unit][level]
        self.ap.set_favorite_level(sValue)
        return {"nValue": nValue, "sValue": level}

    def airQualityDeviceCurrentValue(self):
        return self.status.aqi

    def temperatureHumidityDeviceCurrentValue(self):
        temp = self.status.temperature
        hum = self.status.humidity
        humStatus = 3
        if hum < 25:
            humStatus = 2
        elif hum < 40:
            humStatus = 1
        elif hum < 60:
            humStatus = 0
        return "%f;%f;%d" % (temp, hum, humStatus)

    def filterLifeRemainingDeviceCurrentValue(self):
        return self.status.filter_life_remaining

    def filterHoursUsedDeviceCurrentValue(self):
        return self.status.filter_hours_used

    def updateAirPurifierStatus(self):
        self.status = self.ap.status()

    def updateDomoticzDevice(self, unit, nValue, sValue):
        Domoticz.Debug("Updating Domoticz device %d: (%d,%s)" %
                       (unit, nValue, sValue))
        Devices[unit].Update(nValue=nValue, sValue=str(sValue))

    def updateDomoticzDevices(self):
        self.updateAirPurifierStatus()
        for unit in self.units:
            unitType = self.units[unit]["type"]
            value = self.units[unit]["currentValue"]()
            ps = self.powerSwitchCurrentValue()

            nValue = 0 if ps.lower() == "off" else 1
            sValue = value
            if unitType == "switch":
                nValue = 0 if value.lower() == "off" else 1
                sValue = "On" if sValue else "Off"
            elif unitType == "sensor":
                nValue = 0
            if unit in self.selectorData and (
                    str(sValue)).lower() in self.selectorData[unit]:
                sValue = self.selectorData[unit][(str(sValue)).lower()]

            self.updateDomoticzDevice(unit, nValue, sValue)
        return
Exemplo n.º 4
0
        #Connect to MongoDB
        client = MongoClient(
            "mongodb://<username>:<pw>@XXX.XXX.XXX.XXX:27017/admin"
        )  #<--------------------To config
        db = client['{}'.format('sensors')]
        write = db['{}'.format('xiaomi_AirPurifier')]

        #Conenct to AirPurifier, (IP, token)
        xm_airP = AirPurifier("192.168.0.XXX", "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX")

        #############################
        #Status data
        try:
            while True:
                #Get data
                status = xm_airP.status()

                #Creat JSON object for DB
                writeData = ({
                    'aqi':
                    int(status.aqi),
                    'humidity':
                    int(status.humidity),
                    'illuminance':
                    int(status.illuminance),
                    'os_on':
                    "{}".format(status.is_on),
                    'motor_speed':
                    int(status.motor_speed),
                    'temp':
                    float(status.temperature),