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
def stop(vac: miio.Vacuum): """Stop cleaning.""" click.echo("Stop cleaning: %s" % vac.stop())
def stop(vac: miio.Vacuum): """Deactivate the manual mode.""" click.echo("Deactivating manual controls") return vac.manual_stop()
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))
def spot(vac: miio.Vacuum): """Start spot cleaning.""" click.echo("Starting spot cleaning: %s" % vac.spot())
def delete(vac: miio.Vacuum, timer_id): """Delete a timer.""" click.echo(vac.delete_timer(timer_id))
def map(vac: miio.Vacuum): """Return the map token.""" click.echo(vac.map())
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)
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)
#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:
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()
def sound(vac: miio.Vacuum): """Query sound settings.""" click.echo(vac.sound_info())
def info(vac: miio.Vacuum): """Return device information.""" res = vac.info() click.echo("%s" % res) _LOGGER.debug("Full response: %s", pf(res.raw))
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)
def move(vac: miio.Vacuum, rotation: int, velocity: float, duration: int): """Pass raw manual values""" return vac.manual_control(rotation, velocity, duration)
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__, )
def add(vac: miio.Vacuum, cron, command, params): """Add a timer.""" click.echo(vac.add_timer(cron, command, params))
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))
def find(vac: miio.Vacuum): """Find the robot.""" click.echo("Sending find the robot calls.") click.echo(vac.find())
def zoned_clean(vac: miio.Vacuum, zones: List): """Clean zone.""" click.echo("Cleaning zone(s) : %s" % vac.zoned_clean(zones))
def serial_number(vac: miio.Vacuum): """Query serial number.""" click.echo("Serial#: %s" % vac.serial_number())
def start(vac: miio.Vacuum): # noqa: F811 # redef of start """Activate the manual mode.""" click.echo("Activating manual controls") return vac.manual_start()
def start(vac: miio.Vacuum): """Start cleaning.""" click.echo("Starting cleaning: %s" % vac.start())
def right(vac: miio.Vacuum, degrees: int): """Turn to right.""" click.echo("Turning right") return vac.manual_control(-degrees, 0)
def pause(vac: miio.Vacuum): """Pause cleaning.""" click.echo("Pausing: %s" % vac.pause())
def forward(vac: miio.Vacuum, amount: float): """Run forwards.""" click.echo("Moving forwards") return vac.manual_control(0, amount)
def home(vac: miio.Vacuum): """Return home.""" click.echo("Requesting return to home: %s" % vac.home())
def backward(vac: miio.Vacuum, amount: float): """Run backwards.""" click.echo("Moving backwards") return vac.manual_control(0, -amount)
def left(vac: miio.Vacuum, degrees: int): """Turn to left.""" click.echo("Turning %s degrees left" % degrees) return vac.manual_control(degrees, 0)
def manual_stop(vac: miio.Vacuum): # noqa: F811 # redef of stop """Deactivate the manual mode.""" click.echo("Deactivating manual controls") return vac.manual_stop()