コード例 #1
0
class XVCHelper(XVCHelperBase):
    """
    Helper class to abstract and simplify vacuum methods.
    """
    def __init__(self, ip: str, token: str) -> None:
        """
        Initialize a object of class XVCHelper.

        :param ip: IP address of the vacuum cleaner.
        :param token: Token of the vacuum cleaner.
        """
        self.__vacuum = Vacuum(ip=ip, token=token, start_id=1)

        # check connection
        for _ in range(3):
            try:
                self.__vacuum.do_discover()
                break
            except DeviceException:
                continue
        else:
            raise ConnectionError(
                'Cannot establish connection to Vacuum Cleaner at {}'.format(
                    ip))

    def status(self) -> Tuple[bool, str]:
        """
        Gets current status.

        :return: True on success, otherwise False.
        :return: Vacuum status.
        """
        vacuum_status = None
        try:
            vacuum_status = self.__vacuum.status().state
            result = True
        except DeviceException:
            result = False
        return result, vacuum_status

    def pause(self) -> bool:
        """
        Pause vacuum cleaner.

        :return: True on success, otherwise False.
        """
        result = self.__vacuum.pause()
        return result == XVCHelper.RESPONSE_SUCCEEDED

    def home(self) -> bool:
        """
        Stops cleaning and sends vacuum cleaner back to the dock.

        :return: True on success, otherwise False.
        """
        result = self.__vacuum.home()
        return result == XVCHelper.RESPONSE_SUCCEEDED

    def start_zone_cleaning(self, zones: List[XVCListable]) -> bool:
        """
        Start the zone cleanup.

        :param zones: Different zones to clean.
        :return: True on success, otherwise False.
        """
        self.pause()
        zones_list = [zone.get_list() for zone in zones]
        result = self.__vacuum.zoned_clean(zones_list)
        return result == XVCHelper.RESPONSE_SUCCEEDED

    def set_fan_level(self, fan_level: XVCHelperBase.FanLevel) -> bool:
        """
        Sets the fan level.

        :param fan_level: New fan level.
        :return: True on success, otherwise False.
        """
        result = self.__vacuum.set_fan_speed(fan_level.value)
        return result == XVCHelper.RESPONSE_SUCCEEDED
コード例 #2
0
def stop(vac: miio.Vacuum):
    """Stop cleaning."""
    click.echo("Stop cleaning: %s" % vac.stop())
コード例 #3
0
def stop(vac: miio.Vacuum):
    """Deactivate the manual mode."""
    click.echo("Deactivating manual controls")
    return vac.manual_stop()
コード例 #4
0
ファイル: vacuum_cli.py プロジェクト: zianglei/python-miio
def carpet_mode(vac: miio.Vacuum, enabled=None):
    """Query or set the carpet mode."""
    if enabled is None:
        click.echo(vac.carpet_mode())
    else:
        click.echo(vac.set_carpet_mode(enabled))
コード例 #5
0
def spot(vac: miio.Vacuum):
    """Start spot cleaning."""
    click.echo("Starting spot cleaning: %s" % vac.spot())
コード例 #6
0
ファイル: vacuum_cli.py プロジェクト: zianglei/python-miio
def delete(vac: miio.Vacuum, timer_id):
    """Delete a timer."""
    click.echo(vac.delete_timer(timer_id))
コード例 #7
0
ファイル: vacuum_cli.py プロジェクト: zianglei/python-miio
def map(vac: miio.Vacuum):
    """Return the map token."""
    click.echo(vac.map())
コード例 #8
0
async def async_setup_platform(hass,
                               config,
                               async_add_entities,
                               discovery_info=None):
    """Set up the Xiaomi vacuum cleaner robot platform."""
    if DATA_KEY not in hass.data:
        hass.data[DATA_KEY] = {}

    host = config[CONF_HOST]
    token = config[CONF_TOKEN]
    name = config[CONF_NAME]

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

    try:
        miio_device = Device(host, token)
        device_info = await hass.async_add_executor_job(miio_device.info)
        model = device_info.model
        unique_id = f"{model}-{device_info.mac_address}"
        _LOGGER.info(
            "%s %s %s detected",
            model,
            device_info.firmware_version,
            device_info.hardware_version,
        )
    except DeviceException as ex:
        raise PlatformNotReady from ex

    mirobo = MiroboVacuum2(name, vacuum, unique_id)
    hass.data[DATA_KEY][host] = mirobo

    async_add_entities([mirobo], update_before_add=True)

    async def async_service_handler(service):
        """Map services to methods on MiroboVacuum."""
        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:
            target_vacuums = [
                vac for vac in hass.data[DATA_KEY].values()
                if vac.entity_id in entity_ids
            ]
        else:
            target_vacuums = hass.data[DATA_KEY].values()

        update_tasks = []
        for vacuum in target_vacuums:
            await getattr(vacuum, method["method"])(**params)

        for vacuum in target_vacuums:
            update_coro = vacuum.async_update_ha_state(True)
            update_tasks.append(update_coro)

        if update_tasks:
            await asyncio.wait(update_tasks)

    for vacuum_service in SERVICE_TO_METHOD:
        schema = SERVICE_TO_METHOD[vacuum_service].get("schema",
                                                       VACUUM_SERVICE_SCHEMA)
        hass.services.async_register(DOMAIN,
                                     vacuum_service,
                                     async_service_handler,
                                     schema=schema)
コード例 #9
0
ファイル: __init__.py プロジェクト: neotje/core
async def async_create_miio_device_and_coordinator(
        hass: core.HomeAssistant, entry: config_entries.ConfigEntry):
    """Set up a data coordinator and one miio device to service multiple entities."""
    model = entry.data[CONF_MODEL]
    host = entry.data[CONF_HOST]
    token = entry.data[CONF_TOKEN]
    name = entry.title
    device = None
    migrate = False
    update_method = _async_update_data_default
    coordinator_class = DataUpdateCoordinator

    if (model not in MODELS_HUMIDIFIER and model not in MODELS_FAN
            and model not in MODELS_VACUUM):
        return

    _LOGGER.debug("Initializing with host %s (token %s...)", host, token[:5])

    # Humidifiers
    if model in MODELS_HUMIDIFIER_MIOT:
        device = AirHumidifierMiot(host, token)
        migrate = True
    elif model in MODELS_HUMIDIFIER_MJJSQ:
        device = AirHumidifierMjjsq(host, token, model=model)
        migrate = True
    elif model in MODELS_HUMIDIFIER_MIIO:
        device = AirHumidifier(host, token, model=model)
        migrate = True
    # Airpurifiers and Airfresh
    elif model in MODEL_AIRPURIFIER_3C:
        device = AirPurifierMB4(host, token)
    elif model in MODELS_PURIFIER_MIOT:
        device = AirPurifierMiot(host, token)
    elif model.startswith("zhimi.airpurifier."):
        device = AirPurifier(host, token)
    elif model.startswith("zhimi.airfresh."):
        device = AirFresh(host, token)
    elif model in MODELS_VACUUM:
        device = Vacuum(host, token)
        update_method = _async_update_data_vacuum
        coordinator_class = DataUpdateCoordinator[VacuumCoordinatorData]
    # Pedestal fans
    elif model in MODEL_TO_CLASS_MAP:
        device = MODEL_TO_CLASS_MAP[model](host, token)
    elif model in MODELS_FAN_MIIO:
        device = Fan(host, token, model=model)
    else:
        _LOGGER.error(
            "Unsupported device found! Please create an issue at "
            "https://github.com/syssi/xiaomi_airpurifier/issues "
            "and provide the following data: %s",
            model,
        )
        return

    if migrate:
        # Removing fan platform entity for humidifiers and migrate the name to the config entry for migration
        entity_registry = er.async_get(hass)
        entity_id = entity_registry.async_get_entity_id(
            "fan", DOMAIN, entry.unique_id)
        if entity_id:
            # This check is entities that have a platform migration only and should be removed in the future
            if migrate_entity_name := entity_registry.async_get(
                    entity_id).name:
                hass.config_entries.async_update_entry(
                    entry, title=migrate_entity_name)
            entity_registry.async_remove(entity_id)
コード例 #10
0
#MDR 
from miio import Vacuum
import os
import requests
import time
import datetime  

telephone1 = "<ipAppareil1>" #Mon téléphone
telephone2 = "<ipAppareil2>" #Un autre téléphone

isVacuumedToday = 0 #L'aspirateur est-il passé aujourd'hui ?

vac = Vacuum("<ipAspirateur>", "<tokenAspirateur>")

def isConnected():
  telephone1IsConnected = os.system("ping -c 1 " + telephone1)
  telephone2IsConnected = os.system("ping -c 1 " + telephone2)

  if telephone1IsConnected == 0 or telephone2IsConnected == 0:
      return 0
  else:
      return 1
      
def vacuumStart():
  if isConnected() == 1 :
      print("Trying to start the vacuum.")
      print(vac.start())
  else:
      return 0    
    
while 1:
コード例 #11
0
from miio import Vacuum

# Fin IP using Xiaomi App
IP = ''
# Find Token using Xiaomi App
TOKEN = ''


if __name__ == '__main__':
    vac = Vacuum(IP, TOKEN)
    vac.start()
コード例 #12
0
ファイル: vacuum_cli.py プロジェクト: hanang128/python-miio
def sound(vac: miio.Vacuum):
    """Query sound settings."""
    click.echo(vac.sound_info())
コード例 #13
0
ファイル: vacuum_cli.py プロジェクト: hanang128/python-miio
def info(vac: miio.Vacuum):
    """Return device information."""
    res = vac.info()

    click.echo("%s" % res)
    _LOGGER.debug("Full response: %s", pf(res.raw))
コード例 #14
0
async def async_setup_entry(hass, config_entry, async_add_entities):
    """Set up the Xiaomi vacuum cleaner robot from a config entry."""
    entities = []

    if config_entry.data[CONF_FLOW_TYPE] == CONF_DEVICE:
        host = config_entry.data[CONF_HOST]
        token = config_entry.data[CONF_TOKEN]
        name = config_entry.title
        unique_id = config_entry.unique_id

        # Create handler
        _LOGGER.debug("Initializing with host %s (token %s...)", host,
                      token[:5])
        vacuum = Vacuum(host, token)

        mirobo = MiroboVacuum(name, vacuum, config_entry, unique_id)
        entities.append(mirobo)

        platform = entity_platform.current_platform.get()

        platform.async_register_entity_service(
            SERVICE_START_REMOTE_CONTROL,
            {},
            MiroboVacuum.async_remote_control_start.__name__,
        )

        platform.async_register_entity_service(
            SERVICE_STOP_REMOTE_CONTROL,
            {},
            MiroboVacuum.async_remote_control_stop.__name__,
        )

        platform.async_register_entity_service(
            SERVICE_MOVE_REMOTE_CONTROL,
            {
                vol.Optional(ATTR_RC_VELOCITY):
                vol.All(vol.Coerce(float), vol.Clamp(min=-0.29, max=0.29)),
                vol.Optional(ATTR_RC_ROTATION):
                vol.All(vol.Coerce(int), vol.Clamp(min=-179, max=179)),
                vol.Optional(ATTR_RC_DURATION):
                cv.positive_int,
            },
            MiroboVacuum.async_remote_control_move.__name__,
        )

        platform.async_register_entity_service(
            SERVICE_MOVE_REMOTE_CONTROL_STEP,
            {
                vol.Optional(ATTR_RC_VELOCITY):
                vol.All(vol.Coerce(float), vol.Clamp(min=-0.29, max=0.29)),
                vol.Optional(ATTR_RC_ROTATION):
                vol.All(vol.Coerce(int), vol.Clamp(min=-179, max=179)),
                vol.Optional(ATTR_RC_DURATION):
                cv.positive_int,
            },
            MiroboVacuum.async_remote_control_move_step.__name__,
        )

        platform.async_register_entity_service(
            SERVICE_CLEAN_ZONE,
            {
                vol.Required(ATTR_ZONE_ARRAY):
                vol.All(
                    list,
                    [
                        vol.ExactSequence([
                            vol.Coerce(int),
                            vol.Coerce(int),
                            vol.Coerce(int),
                            vol.Coerce(int),
                        ])
                    ],
                ),
                vol.Required(ATTR_ZONE_REPEATER):
                vol.All(vol.Coerce(int), vol.Clamp(min=1, max=3)),
            },
            MiroboVacuum.async_clean_zone.__name__,
        )

        platform.async_register_entity_service(
            SERVICE_GOTO,
            {
                vol.Required("x_coord"): vol.Coerce(int),
                vol.Required("y_coord"): vol.Coerce(int),
            },
            MiroboVacuum.async_goto.__name__,
        )
        platform.async_register_entity_service(
            SERVICE_CLEAN_SEGMENT,
            {
                vol.Required("segments"):
                vol.Any(vol.Coerce(int), [vol.Coerce(int)])
            },
            MiroboVacuum.async_clean_segment.__name__,
        )

    async_add_entities(entities, update_before_add=True)
コード例 #15
0
ファイル: vacuum_cli.py プロジェクト: zianglei/python-miio
def move(vac: miio.Vacuum, rotation: int, velocity: float, duration: int):
    """Pass raw manual values"""
    return vac.manual_control(rotation, velocity, duration)
コード例 #16
0
ファイル: vacuum.py プロジェクト: SLG/xiaomi_miio_custom
async def async_setup_platform(hass,
                               config,
                               async_add_entities,
                               discovery_info=None):
    """Set up the Xiaomi vacuum cleaner robot platform."""
    if DATA_KEY not in hass.data:
        hass.data[DATA_KEY] = {}

    host = config[CONF_HOST]
    token = config[CONF_TOKEN]
    name = config[CONF_NAME]

    # Create handler
    _LOGGER.info("Initializing with host %s (token %s...)", host, token[:5])
    vacuum = Vacuum(host, token)

    mirobo = MiroboVacuum(name, vacuum)
    hass.data[DATA_KEY][host] = mirobo

    async_add_entities([mirobo], update_before_add=True)

    platform = entity_platform.current_platform.get()

    platform.async_register_entity_service(
        SERVICE_START_REMOTE_CONTROL,
        {},
        MiroboVacuum.async_remote_control_start.__name__,
    )

    platform.async_register_entity_service(
        SERVICE_STOP_REMOTE_CONTROL,
        {},
        MiroboVacuum.async_remote_control_stop.__name__,
    )

    platform.async_register_entity_service(
        SERVICE_MOVE_REMOTE_CONTROL,
        {
            vol.Optional(ATTR_RC_VELOCITY):
            vol.All(vol.Coerce(float), vol.Clamp(min=-0.29, max=0.29)),
            vol.Optional(ATTR_RC_ROTATION):
            vol.All(vol.Coerce(int), vol.Clamp(min=-179, max=179)),
            vol.Optional(ATTR_RC_DURATION):
            cv.positive_int,
        },
        MiroboVacuum.async_remote_control_move.__name__,
    )

    platform.async_register_entity_service(
        SERVICE_MOVE_REMOTE_CONTROL_STEP,
        {
            vol.Optional(ATTR_RC_VELOCITY):
            vol.All(vol.Coerce(float), vol.Clamp(min=-0.29, max=0.29)),
            vol.Optional(ATTR_RC_ROTATION):
            vol.All(vol.Coerce(int), vol.Clamp(min=-179, max=179)),
            vol.Optional(ATTR_RC_DURATION):
            cv.positive_int,
        },
        MiroboVacuum.async_remote_control_move_step.__name__,
    )

    platform.async_register_entity_service(
        SERVICE_CLEAN_ZONE,
        {
            vol.Required(ATTR_ZONE_ARRAY):
            vol.All(
                list,
                [
                    vol.ExactSequence([
                        vol.Coerce(int),
                        vol.Coerce(int),
                        vol.Coerce(int),
                        vol.Coerce(int),
                    ])
                ],
            ),
            vol.Required(ATTR_ZONE_REPEATER):
            vol.All(vol.Coerce(int), vol.Clamp(min=1, max=3)),
        },
        MiroboVacuum.async_clean_zone.__name__,
    )

    platform.async_register_entity_service(
        SERVICE_GOTO,
        {
            vol.Required("x_coord"): vol.Coerce(int),
            vol.Required("y_coord"): vol.Coerce(int),
        },
        MiroboVacuum.async_goto.__name__,
    )
コード例 #17
0
ファイル: vacuum_cli.py プロジェクト: zianglei/python-miio
def add(vac: miio.Vacuum, cron, command, params):
    """Add a timer."""
    click.echo(vac.add_timer(cron, command, params))
コード例 #18
0
ファイル: vacuum_cli.py プロジェクト: zianglei/python-miio
def goto(vac: miio.Vacuum, x_coord: int, y_coord: int):
    """Go to specific target."""
    click.echo("Going to target : %s" % vac.goto(x_coord, y_coord))
コード例 #19
0
ファイル: vacuum_cli.py プロジェクト: zianglei/python-miio
def find(vac: miio.Vacuum):
    """Find the robot."""
    click.echo("Sending find the robot calls.")
    click.echo(vac.find())
コード例 #20
0
ファイル: vacuum_cli.py プロジェクト: zianglei/python-miio
def zoned_clean(vac: miio.Vacuum, zones: List):
    """Clean zone."""
    click.echo("Cleaning zone(s) : %s" % vac.zoned_clean(zones))
コード例 #21
0
ファイル: vacuum_cli.py プロジェクト: zianglei/python-miio
def serial_number(vac: miio.Vacuum):
    """Query serial number."""
    click.echo("Serial#: %s" % vac.serial_number())
コード例 #22
0
ファイル: vacuum_cli.py プロジェクト: zianglei/python-miio
def start(vac: miio.Vacuum):  # noqa: F811  # redef of start
    """Activate the manual mode."""
    click.echo("Activating manual controls")
    return vac.manual_start()
コード例 #23
0
def start(vac: miio.Vacuum):
    """Start cleaning."""
    click.echo("Starting cleaning: %s" % vac.start())
コード例 #24
0
ファイル: vacuum_cli.py プロジェクト: zianglei/python-miio
def right(vac: miio.Vacuum, degrees: int):
    """Turn to right."""
    click.echo("Turning right")
    return vac.manual_control(-degrees, 0)
コード例 #25
0
def pause(vac: miio.Vacuum):
    """Pause cleaning."""
    click.echo("Pausing: %s" % vac.pause())
コード例 #26
0
ファイル: vacuum_cli.py プロジェクト: zianglei/python-miio
def forward(vac: miio.Vacuum, amount: float):
    """Run forwards."""
    click.echo("Moving forwards")
    return vac.manual_control(0, amount)
コード例 #27
0
def home(vac: miio.Vacuum):
    """Return home."""
    click.echo("Requesting return to home: %s" % vac.home())
コード例 #28
0
ファイル: vacuum_cli.py プロジェクト: zianglei/python-miio
def backward(vac: miio.Vacuum, amount: float):
    """Run backwards."""
    click.echo("Moving backwards")
    return vac.manual_control(0, -amount)
コード例 #29
0
def left(vac: miio.Vacuum, degrees: int):
    """Turn to left."""
    click.echo("Turning %s degrees left" % degrees)
    return vac.manual_control(degrees, 0)
コード例 #30
0
ファイル: vacuum_cli.py プロジェクト: Zuz666/python-miio
def manual_stop(vac: miio.Vacuum):  # noqa: F811  # redef of stop
    """Deactivate the manual mode."""
    click.echo("Deactivating manual controls")
    return vac.manual_stop()