Exemplo n.º 1
0
 def __init__(self, name, host, token):
     self._name = name
     self._device = Device(ip=host, token=token)
     self._available = True
     self._speed = None
     self._state = False
     self._state_attrs = {}
     self._skip_update = False
Exemplo n.º 2
0
 def __init__(self, name, host, token):
     self._name = name
     self._device = Device(ip=host, token=token)
     info = self._device.info()
     self._info = {
         'firmware_version': info.firmware_version,
         'hardware_version': info.hardware_version,
         'mac_address': info.mac_address,
         'model': info.model,
     }
     self._available = True
     self._speed = None
     self._state = False
     self._state_attrs = {}
     self._skip_update = False
Exemplo n.º 3
0
 def __init__(self, name, host, token):
     self._name = name
     self._device = Device(ip=host, token=token)
     info = self._device.info()
     self._info = {
         'firmware_version': info.firmware_version,
         'hardware_version': info.hardware_version,
         'mac_address': info.mac_address,
         'model': info.model,
     }
     self._available = True
     self._speed = SPEED_OFF
     self._percentage = None
     self._speed_list = []
     self._preset_modes = PRESET_MODES
     self._preset_mode = None
     self._state_attrs = {}
     self._skip_update = False
Exemplo n.º 4
0
class MijiaWasher(FanEntity):
    def __init__(self, name, host, token):
        self._name = name
        self._device = Device(ip=host, token=token)
        info = self._device.info()
        self._info = {
            'firmware_version': info.firmware_version,
            'hardware_version': info.hardware_version,
            'mac_address': info.mac_address,
            'model': info.model,
        }
        self._available = True
        self._speed = SPEED_OFF
        self._percentage = None
        self._speed_list = []
        self._preset_modes = PRESET_MODES
        self._preset_mode = None
        self._state_attrs = {}
        self._skip_update = False

    @property
    def supported_features(self):
        """Flag supported features."""
        return SUPPORT_PRESET_MODE

    @property
    def should_poll(self):
        """Poll the device."""
        return True

    @property
    def name(self):
        """Return the name of the device if any."""
        return self._name

    @property
    def icon(self):
        """Return the icon for device by its type."""
        return ICON

    @property
    def available(self):
        """Return true when state is known."""
        return self._available

    @property
    def device_state_attributes(self):
        """Return the state attributes of the device."""
        return self._state_attrs

    @property
    def percentage(self) -> int:
        """Return the current speed."""
        return self._percentage

    @property
    def speed_count(self) -> int:
        """Return the number of speeds the fan supports."""
        return len(PRESET_MODES)

    async def async_set_percentage(self, percentage: int) -> None:
        """Set the speed of the fan, as a percentage."""
        self._percentage = percentage
        self._preset_mode = None
        self.async_write_ha_state()

    @property
    def preset_mode(self) -> str:
        """Return the current preset mode, e.g., auto, smart, interval, favorite."""
        return self._preset_mode

    @property
    def preset_modes(self) -> list:
        """Return a list of available preset modes."""
        return self._preset_modes

    async def async_set_preset_mode(self, preset_mode: str) -> None:
        """Set new preset mode."""
        _LOGGER.debug("Setting the operation mode to: %s", preset_mode)
        if preset_mode not in self.preset_modes:
            return
        if preset_mode == 'pause':
            self.pause()
        elif preset_mode == 'start':
            self.start()
        else:
            self._device.raw_command("set_cycle", [preset_mode])
        self._preset_mode = preset_mode
        self._percentage = None
        self.async_write_ha_state()

    async def async_turn_on(
        self,
        speed: str = None,
        percentage: int = None,
        preset_mode: str = None,
        **kwargs,
    ) -> None:
        """Turn on the entity."""
        if not self._state:
            result = self._device.raw_command("set_power", ["on"])
            _LOGGER.debug("Turn on with result: %s" % result)
        self._preset_mode = PRESET_MODES[2]
        self.async_write_ha_state()

    async def async_turn_off(self, **kwargs) -> None:
        """Turn off the entity."""
        result = self._device.raw_command("set_power", ["off"])
        await self.async_set_percentage(0)
        _LOGGER.debug("Turn off with result: %s" % result)

    def start(self):
        if self._state_attrs != 'run':
            self._device.raw_command("set_startpause", ['true'])

    def pause(self):
        if self._state_attrs != 'pause':
            self._device.raw_command("set_startpause", ['false'])

    def update(self):
        try:
            values = {}
            for prop in AVAILABLE_PROPERTIES:
                values[prop] = self._device.get_properties(
                    properties=[prop])[0]
            return values
        except Exception:
            _LOGGER.error('Update seating state error.', exc_info=True)

    async def async_update(self):
        """Fetch state from the device."""
        # On state change the device doesn't provide the new state immediately.
        if self._skip_update:
            self._skip_update = False
            return
        try:
            values = await self.hass.async_add_executor_job(self.update)
            _LOGGER.debug("Got new values: %s", values)

            self._available = True
            self._speed = values['cycle']
            self._state = values['state'] != 'off'
            # split process
            process = values['process'].split(';')
            options = process[0].split(':')[1].split(',')
            processing = process[1].split(':')[1]
            values['options'] = [
                PROCESS_VALUE[x] if x in PROCESS_VALUE else x for x in options
            ]
            values['process'] = PROCESS_VALUE[processing]
            values.update(self._info)
            self._state_attrs = values

        except DeviceException as ex:
            self._available = False
            _LOGGER.error("Got exception while fetching the state: %s", ex)
Exemplo n.º 5
0
#!/usr/bin/env python3

from miio.device import Device

device = Device('Washer', '1f63e0afaa20d062223b24c98eca7c11')
info = device.info()
print('%s' % info)

device.send("set_wash_program", ['goldenwash'])

#device.send("set_wash_action", [0]) # 0=Pause/1=Wash/2=PowerOff
#device.send("SetDryMode", ['17922']) # 0
# print('set_appoint_time=0: %s' % device.send("set_appoint_time", [0]))
# print('set_appoint_time: %s' % device.send("set_appoint_time", [20]))

properties = [
    "program",  # dry=黄金烘/weak_dry=低温烘/refresh=空气洗/wool=羊毛/down=羽绒服/drumclean=筒清洁/goldenwash=黄金洗/super_quick=超快洗/cottons=棉织物/antibacterial=除菌洗/rinse_spin=漂+脱/spin单脱水/quick=快洗/shirt=衬衣/jeans=牛仔/underwears=内衣
    "wash_process",  # 0=Idle/1=Prepare/1=Pause/.../7=Stop/预约等待=0
    "wash_status",  # 1=Idle/1=Prepare/0=Pause/1=Stop/预约等待=1
    "water_temp",
    "rinse_status",
    "spin_level",
    "remain_time",
    "appoint_time",
    "be_status",
    "run_status",
    "DryMode",  # 0=NA/33282=智能/半小时=7681/15361=一小时/30721=两小时
    "child_lock"
]

# Limited to a single property per request
Exemplo n.º 6
0
class MijiaWasher(FanEntity):
    def __init__(self, name, host, token):
        self._name = name
        self._device = Device(ip=host, token=token)
        self._available = True
        self._speed = None
        self._state = False
        self._state_attrs = {}
        self._skip_update = False

    @property
    def supported_features(self):
        """Flag supported features."""
        return SUPPORT_SET_SPEED

    @property
    def should_poll(self):
        """Poll the device."""
        return True

    @property
    def name(self):
        """Return the name of the device if any."""
        return self._name

    @property
    def icon(self):
        """Return the icon for device by its type."""
        return ICON

    @property
    def available(self):
        """Return true when state is known."""
        return self._available

    @property
    def device_state_attributes(self):
        """Return the state attributes of the device."""
        return self._state_attrs

    @property
    def is_on(self):
        """Return true if device is on."""
        return self._state

    def start(self):
        if self._state_attrs != 'run':
            self._device.raw_command("set_startpause", ['true'])

    def pause(self):
        if self._state_attrs != 'pause':
            self._device.raw_command("set_startpause", ['false'])

    def update(self):
        try:
            values = {}
            for prop in AVAILABLE_PROPERTIES:
                values[prop] = self._device.get_properties(
                    properties=[prop])[0]
            return values
        except Exception:
            _LOGGER.error('Update seating state error.', exc_info=True)

    async def async_update(self):
        """Fetch state from the device."""
        # On state change the device doesn't provide the new state immediately.
        if self._skip_update:
            self._skip_update = False
            return

        try:
            values = await self.hass.async_add_executor_job(self.update)
            _LOGGER.debug("Got new values: %s", values)

            self._available = True
            self._speed = values['cycle']
            self._state = values['state'] != 'off'
            self._state_attrs = values

        except DeviceException as ex:
            self._available = False
            _LOGGER.error("Got exception while fetching the state: %s", ex)

    @asyncio.coroutine
    def async_turn_on(self, speed: str = None) -> None:
        """Turn on the entity."""
        if not self._state:
            result = self._device.raw_command("set_power", ["on"])
            _LOGGER.debug("Turn on with result: %s" % result)
        self.set_speed(speed)

    @asyncio.coroutine
    def async_turn_off(self) -> None:
        """Turn off the entity."""
        result = self._device.raw_command("set_power", ["off"])
        _LOGGER.debug("Turn off with result: %s" % result)
        # yield from self.async_set_speed(STATE_OFF)

    def set_speed(self, speed: str) -> None:
        """Set the speed of the fan."""
        if self.supported_features & SUPPORT_SET_SPEED == 0:
            return
        _LOGGER.debug("Setting the operation mode to: %s", speed)
        if speed == 'pause':
            self.pause()
        elif speed == 'start':
            self.start()
        else:
            self._device.raw_command("set_cycle", [speed])

    @property
    def speed_list(self) -> list:
        """Get the list of available speeds."""
        return SPEED_LIST

    @property
    def speed(self):
        """Return the current speed."""
        if self._state:
            return self._speed

        return None
Exemplo n.º 7
0
async def async_setup_platform(hass,
                               config,
                               async_add_devices,
                               discovery_info=None):
    """Set up the miio fan device from config."""
    from miio import Device, DeviceException
    if DATA_KEY not in hass.data:
        hass.data[DATA_KEY] = {}

    host = config.get(CONF_HOST)
    name = config.get(CONF_NAME)
    token = config.get(CONF_TOKEN)
    model = config.get(CONF_MODEL)

    _LOGGER.info("Initializing with host %s (token %s...)", host, token[:5])
    unique_id = None

    if model is None:
        try:
            miio_device = Device(host, token)
            device_info = miio_device.info()
            model = device_info.model
            unique_id = "{}-{}".format(model, device_info.mac_address)
            _LOGGER.info("%s %s %s detected", model,
                         device_info.firmware_version,
                         device_info.hardware_version)
        except DeviceException:
            raise PlatformNotReady

    if model.startswith('zhimi.airfresh.'):
        air_fresh = AirFresh(host, token)
        device = XiaomiAirFresh(name, air_fresh, model, unique_id)
    else:
        _LOGGER.error(
            'Unsupported device found! Please create an issue at '
            'https://github.com/Yonsm/HAExtra/issues '
            'and provide the following data: %s', model)
        return False

    hass.data[DATA_KEY][host] = device
    async_add_devices([device], update_before_add=True)

    async def async_service_handler(service):
        """Map services to methods on XiaomiAirPurifier."""
        method = SERVICE_TO_METHOD.get(service.service)
        params = {
            key: value
            for key, value in service.data.items() if key != ATTR_ENTITY_ID
        }
        entity_ids = service.data.get(ATTR_ENTITY_ID)
        if entity_ids:
            devices = [
                device for device in hass.data[DATA_KEY].values()
                if device.entity_id in entity_ids
            ]
        else:
            devices = hass.data[DATA_KEY].values()

        update_tasks = []
        for device in devices:
            if not hasattr(device, method['method']):
                continue
            await getattr(device, method['method'])(**params)
            update_tasks.append(device.async_update_ha_state(True))

        if update_tasks:
            await asyncio.wait(update_tasks, loop=hass.loop)

    for air_fresh_service in SERVICE_TO_METHOD:
        schema = SERVICE_TO_METHOD[air_fresh_service].get(
            'schema', AIRPURIFIER_SERVICE_SCHEMA)
        hass.services.async_register(DOMAIN,
                                     air_fresh_service,
                                     async_service_handler,
                                     schema=schema)
Exemplo n.º 8
0
#!/usr/bin/env python3

from miio.device import Device

device = Device('Airer', 'fe5a1e19a1fd91ca4138646a494a6f19')
#device_info = device.info()
#device.send("set_led", [0])
#print('%s' % device_info)

for prop in ["dry","led","motor","drytime","airer_location"]:
	try:
		ret = device.send("get_prop", [prop])
	except Exception as exc:
		ret = exc
	print('%s=%s' % (prop, ret))

#device.send("set_motor", [1]) # 1-Up/0=Pause/2=Down
Exemplo n.º 9
0
#!/usr/bin/env python3

from miio.device import Device

device = Device('Airer', 'fe5a1e19a1fd91ca4138646a494a6f19')
#device_info = device.info()
#device.send("set_led", [0])
#print('%s' % device_info)
ret = device.send("get_prop", [
            # "dry",
            "led",
            # "motor",
            # "drytime",
            # "airer_location",
        ])
print('%s' % ret)
Exemplo n.º 10
0
from miio.device import Device

device = Device('Airer', 'fe5a1e19a1fd91ca4138646a494a6f19')
device_info = device.info()
device.send("set_led", [0])
print('%s' % device_info)