Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
304 changes: 303 additions & 1 deletion miio/integrations/ijai/vacuum/pro2vacuum.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import json
import logging
from datetime import timedelta
from datetime import time, timedelta
from enum import Enum

import click

from miio.click_common import EnumType, command, format_output
from miio.devicestatus import sensor, setting
from miio.exceptions import DeviceException
from miio.miot_device import DeviceStatus, MiotDevice

_LOGGER = logging.getLogger(__name__)
Expand All @@ -27,6 +29,10 @@
}, # 0 - Global, 1 - Mop, 2 - Edge, 3 - Area, 4 - Point, 5 - Remote, 6 - Explore, 7 - Room, 8 - Floor
"start": {"siid": 2, "aiid": 1},
"stop": {"siid": 2, "aiid": 2},
"start_sweep": {"siid": 2, "aiid": 3}, # Start Only Sweep
"start_sweep_mop": {"siid": 2, "aiid": 5}, # Start Sweep Mop
"start_mop": {"siid": 2, "aiid": 6}, # Start Mop
"start_room_sweep": {"siid": 2, "aiid": 7}, # in: piid 10 (Room IDs, string)
# Battery (siid=3)
"battery": {"siid": 3, "piid": 1}, # [0, 100] step 1
"home": {"siid": 3, "aiid": 1}, # Start Charge
Expand All @@ -48,9 +54,43 @@
"current_language": {"siid": 7, "piid": 21}, # string
"clean_time": {"siid": 7, "piid": 22}, # [0, 120] step 1
"clean_area": {"siid": 7, "piid": 23}, # [0, 1200] step 1
"repeat_state": {"siid": 7, "piid": 1}, # 0 - off, 1 - on (clean twice)
"door_state": {"siid": 7, "piid": 3}, # 0 - none, 1 - dust box, 2 - water tank
"mop_route": {"siid": 7, "piid": 7}, # 0 - bow style, 1 - Y style
"time_zone": {"siid": 7, "piid": 20}, # [-99999, 99999] step 1
"tank_shake": {"siid": 7, "piid": 48}, # 0 - off, 1 - on
"shake_shift": {"siid": 7, "piid": 50}, # 1 - low, 2 - mid, 3 - high
# Alarm (siid=4)
"volume": {"siid": 4, "piid": 2}, # [0, 10] step 1
# Do not disturb (siid=12)
"dnd_enable": {"siid": 12, "piid": 1},
"dnd_start_hour": {"siid": 12, "piid": 2},
"dnd_start_minute": {"siid": 12, "piid": 3},
"dnd_end_hour": {"siid": 12, "piid": 4},
"dnd_end_minute": {"siid": 12, "piid": 5},
# Actions
"reset_consumable": {"siid": 7, "aiid": 1}, # in: piid 17 (consumable-index)
"set_dnd": {"siid": 12, "aiid": 1}, # in: piids 1-6
}
}

# Map service (siid=10), read-only access. Kept out of _MAPPINGS on purpose so
# that status() does not request these properties on every poll.
_MAP_SIID = 10
_MAP_PROPS = {
"current_map_id": {"siid": _MAP_SIID, "piid": 2}, # uint32
"map_count": {"siid": _MAP_SIID, "piid": 3}, # uint8 [0, 5]
"has_new_map": {"siid": _MAP_SIID, "piid": 19}, # uint8 0 - no, 1 - yes
}
_ROOM_IDS_PIID = 10 # Robot Cleaner (siid=2) Room IDs, string
_ALARM_SIID = 4
_ALARM_PLAY_PIID = 1
_SWEEP_SIID = 7
_DIRECTION_PIID = 16
_CONSUMABLE_INDEX_PIID = 17
_MAP_AIID_GET_MAP_LIST = 1
_MAP_OUT_PIID_MAP_LIST = 4

ERROR_CODES: dict[int, str] = {2105: "Fully charged"}


Expand Down Expand Up @@ -113,6 +153,34 @@ class MopRoute(Enum):
YStyle = 1


class Direction(Enum):
"""Manual (remote control) movement, siid=7 piid=16."""

Forward = 1
Left = 2
Right = 3
Backward = 4
Stop = 5
Exit = 10


class Consumable(Enum):
"""Consumable index used by reset_consumable (siid=7 piid=17)."""

MainBrush = 1
SideBrush = 2
Filter = 3
Mop = 4


class TankShake(Enum):
"""Intensity of the water tank vibration (siid=7 piid=50)."""

Low = 1
Medium = 2
High = 3


class Pro2Status(DeviceStatus):
"""Container for status reports from Mi Robot Vacuum-Mop 2 Pro."""

Expand Down Expand Up @@ -264,6 +332,94 @@ def current_language(self) -> str:
"""Current Language."""
return self.data["current_language"]

@property
@sensor("Clean Twice")
def repeat_state(self) -> bool:
"""Whether the area is cleaned twice."""
return bool(self.data["repeat_state"])

@property
@sensor("Door State")
def door_state(self) -> DoorState:
"""Which tank (none, dust box, water tank) is attached."""
return DoorState(self.data["door_state"])

@property
@sensor("Mop Route")
def mop_route(self) -> MopRoute:
"""Mopping route."""
return MopRoute(self.data["mop_route"])

@property
def time_zone(self) -> int:
"""Time zone offset configured on the device (seconds)."""
return self.data["time_zone"]

@property
@sensor("Tank Shake")
def tank_shake(self) -> bool:
"""Whether the water tank vibration is enabled."""
return bool(self.data["tank_shake"])

@property
@sensor("Tank Shake Level")
def shake_shift(self) -> TankShake:
"""Intensity of the water tank vibration."""
return TankShake(self.data["shake_shift"])

@property
@sensor("Volume", unit="%")
def volume(self) -> int:
"""Voice volume [0, 10]."""
return self.data["volume"]

@property
@sensor("Do Not Disturb")
def dnd_enabled(self) -> bool:
"""Whether do-not-disturb is enabled."""
return bool(self.data["dnd_enable"])

@property
def dnd_start(self) -> time:
"""Do-not-disturb start time."""
return time(self.data["dnd_start_hour"], self.data["dnd_start_minute"])

@property
def dnd_end(self) -> time:
"""Do-not-disturb end time."""
return time(self.data["dnd_end_hour"], self.data["dnd_end_minute"])


class Pro2MapStatus(DeviceStatus):
"""Container for the map information of a Mi Robot Vacuum-Mop 2 Pro."""

def __init__(self, data):
"""Response (MIoT format) of the map service (siid=10)

Example::
[
{'did': 'current_map_id', 'siid': 10, 'piid': 2, 'code': 0, 'value': 1700000002},
{'did': 'map_count', 'siid': 10, 'piid': 3, 'code': 0, 'value': 4},
{'did': 'has_new_map', 'siid': 10, 'piid': 19, 'code': 0, 'value': 0},
]
"""
self.data = data

@property
def current_map_id(self) -> int:
"""Id of the currently active map."""
return self.data["current_map_id"]

@property
def map_count(self) -> int:
"""Number of stored maps."""
return self.data["map_count"]

@property
def has_new_map(self) -> bool:
"""True if the device has a map that was not uploaded yet."""
return bool(self.data["has_new_map"])


class Pro2Vacuum(MiotDevice):
"""Support for Mi Robot Vacuum-Mop 2 Pro (ijai.vacuum.v3)."""
Expand All @@ -282,6 +438,31 @@ def status(self) -> Pro2Status:
}
)

@command()
def map_status(self) -> Pro2MapStatus:
"""Return the current map id, the number of maps and the new-map flag."""
props = [{"did": k, **v} for k, v in _MAP_PROPS.items()]
return Pro2MapStatus(
{
prop["did"]: prop["value"] if prop["code"] == 0 else None
for prop in self.get_properties(
props, property_getter="get_properties", max_properties=10
)
}
)

@command()
def get_maps(self) -> list[dict]:
"""Return the stored maps as a list of dicts with name, id and cur keys.

``cur`` is true for the map that is currently active.
"""
res = self.call_action_by(_MAP_SIID, _MAP_AIID_GET_MAP_LIST)
for out in res.get("out", []):
if out.get("piid") == _MAP_OUT_PIID_MAP_LIST:
return json.loads(out["value"])
raise DeviceException(f"Unexpected response to get-map-list: {res}")

@command()
def home(self):
"""Go Home."""
Expand All @@ -297,6 +478,34 @@ def stop(self):
"""Stop Cleaning."""
return self.call_action_from_mapping("stop")

@command()
def start_sweep(self) -> None:
"""Start cleaning in sweep-only mode."""
return self.call_action_from_mapping("start_sweep")

@command()
def start_sweep_mop(self) -> None:
"""Start cleaning in sweep-and-mop mode."""
return self.call_action_from_mapping("start_sweep_mop")

@command()
def start_mop(self) -> None:
"""Start cleaning in mop-only mode."""
return self.call_action_from_mapping("start_mop")

@command(click.argument("room_ids", type=int, nargs=-1, required=True))
def start_rooms(self, room_ids: list[int]) -> None:
"""Start cleaning the given rooms.

Room ids are the ones used by the map of the device (e.g. 10, 11, ...).
"""
if not room_ids:
raise ValueError("At least one room id is required")
rooms = ",".join(str(int(r)) for r in room_ids)
return self.call_action_from_mapping(
"start_room_sweep", [{"piid": _ROOM_IDS_PIID, "value": rooms}]
)

@command(
click.argument("fan_speed", type=EnumType(FanSpeedMode)),
default_output=format_output("Setting fan speed to {fan_speed}"),
Expand All @@ -318,3 +527,96 @@ def set_fan_speed_preset(self, speed_preset: int) -> None:
f"Invalid preset speed {speed_preset}, not in: {self.fan_speed_presets().values()}"
)
return self.set_property("fan_speed", speed_preset)

@command(
click.argument("sweep_mode", type=EnumType(SweepMode)),
default_output=format_output("Setting sweep mode to {sweep_mode}"),
)
def set_sweep_mode(self, sweep_mode: SweepMode):
"""Set the sweep mode (sweep, sweep and mop, mop)."""
return self.set_property("sweep_mode", sweep_mode.value)

@command(
click.argument("water_level", type=EnumType(WaterLevel)),
default_output=format_output("Setting water level to {water_level}"),
)
def set_water_level(self, water_level: WaterLevel):
"""Set the water level used when mopping."""
return self.set_property("water_level", water_level.value)

@command(
click.argument("mop_route", type=EnumType(MopRoute)),
default_output=format_output("Setting mop route to {mop_route}"),
)
def set_mop_route(self, mop_route: MopRoute):
"""Set the mopping route (bow style or Y style)."""
return self.set_property("mop_route", mop_route.value)

@command(click.argument("enable", type=bool))
def set_repeat(self, enable: bool):
"""Enable or disable cleaning the area twice."""
return self.set_property("repeat_state", int(enable))

@command(click.argument("enable", type=bool))
def set_tank_shake(self, enable: bool):
"""Enable or disable the water tank vibration."""
return self.set_property("tank_shake", int(enable))

@command(click.argument("level", type=EnumType(TankShake)))
def set_tank_shake_level(self, level: TankShake):
"""Set the intensity of the water tank vibration."""
return self.set_property("shake_shift", level.value)

@command(click.argument("volume", type=click.IntRange(0, 10)))
def set_volume(self, volume: int):
"""Set the voice volume [0, 10]."""
return self.set_property("volume", volume)

@command()
def locate(self):
"""Play the "I am here" sound (siid=4 piid=1)."""
return self.set_property_by(_ALARM_SIID, _ALARM_PLAY_PIID, 1)

@command(click.argument("consumable", type=EnumType(Consumable)))
def reset_consumable(self, consumable: Consumable):
"""Reset the lifetime counter of a consumable."""
return self.call_action_from_mapping(
"reset_consumable",
[{"piid": _CONSUMABLE_INDEX_PIID, "value": consumable.value}],
)

@command(
click.argument("enable", type=bool),
click.argument("start", type=click.DateTime(["%H:%M"]), required=False),
click.argument("end", type=click.DateTime(["%H:%M"]), required=False),
)
def set_dnd(self, enable: bool, start=None, end=None):
"""Configure do-not-disturb.

``start`` and ``end`` are ``datetime.time`` (or ``HH:MM`` on the CLI). If they
are omitted, the currently configured times are kept.
"""
status = self.status()
start = start.time() if hasattr(start, "time") else start
end = end.time() if hasattr(end, "time") else end
start = start or status.dnd_start
end = end or status.dnd_end
return self.call_action_from_mapping(
"set_dnd",
[
{"piid": 1, "value": int(enable)},
{"piid": 2, "value": start.hour},
{"piid": 3, "value": start.minute},
{"piid": 4, "value": end.hour},
{"piid": 5, "value": end.minute},
{"piid": 6, "value": status.time_zone},
],
)

@command(click.argument("direction", type=EnumType(Direction)))
def manual_control(self, direction: Direction):
"""Move the robot manually (remote control mode).

Send ``Direction.Exit`` to leave the manual mode.
"""
return self.set_property_by(_SWEEP_SIID, _DIRECTION_PIID, direction.value)
Loading
Loading