forked from DeebotUniverse/Deebot-4-Home-Assistant
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vacuum.py
305 lines (257 loc) · 10.8 KB
/
vacuum.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
"""Support for Deebot Vaccums."""
import logging
from collections.abc import Mapping
from typing import Any
import voluptuous as vol
from deebot_client.commands.json import (
Charge,
Clean,
PlaySound,
SetFanSpeed,
SetRelocationState,
SetWaterInfo,
)
from deebot_client.commands.json.clean import CleanAction, CleanArea, CleanMode
from deebot_client.commands.json.clean_V2 import MowerAction, CleanV2
from deebot_client.commands.json.custom import CustomCommand
from deebot_client.events import (
BatteryEvent,
CustomCommandEvent,
ErrorEvent,
FanSpeedLevel,
FanSpeedEvent,
ReportStatsEvent,
RoomsEvent,
StateEvent,
StateEventV2,
)
from deebot_client.models import Room, VacuumState
from deebot_client.vacuum_bot import VacuumBot
from homeassistant.components.vacuum import (
StateVacuumEntity,
StateVacuumEntityDescription,
VacuumEntityFeature,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_platform
from homeassistant.helpers.config_validation import make_entity_service_schema
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.util import slugify
from .const import (
DOMAIN,
EVENT_CLEANING_JOB,
EVENT_CUSTOM_COMMAND,
LAST_ERROR,
REFRESH_MAP,
REFRESH_STR_TO_EVENT_DTO,
VACUUMSTATE_TO_STATE,
)
from .entity import DeebotEntity
from .hub import DeebotHub
from .util import dataclass_to_dict
_LOGGER = logging.getLogger(__name__)
# Must be kept in sync with services.yaml
SERVICE_REFRESH = "refresh"
SERVICE_REFRESH_CATEGORY = "category"
SERVICE_REFRESH_SCHEMA = make_entity_service_schema(
{
vol.Required(SERVICE_REFRESH_CATEGORY): vol.In(
[*REFRESH_STR_TO_EVENT_DTO.keys(), REFRESH_MAP]
)
}
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Add entities for passed config_entry in HA."""
hub: DeebotHub = hass.data[DOMAIN][config_entry.entry_id]
new_devices = []
for vacbot in hub.vacuum_bots:
new_devices.append(DeebotVacuum(vacbot))
if new_devices:
async_add_entities(new_devices)
platform = entity_platform.async_get_current_platform()
platform.async_register_entity_service(
SERVICE_REFRESH,
SERVICE_REFRESH_SCHEMA,
"service_refresh",
)
class DeebotVacuum(DeebotEntity, StateVacuumEntity): # type: ignore
"""Deebot Vacuum."""
_attr_supported_features = (
VacuumEntityFeature.PAUSE
| VacuumEntityFeature.STOP
| VacuumEntityFeature.RETURN_HOME
| VacuumEntityFeature.FAN_SPEED
| VacuumEntityFeature.BATTERY
| VacuumEntityFeature.SEND_COMMAND
| VacuumEntityFeature.LOCATE
| VacuumEntityFeature.STATE
| VacuumEntityFeature.START
)
_attr_fan_speed_list = [level.display_name for level in FanSpeedLevel]
_command_start = Clean(CleanAction.START)
_command_stop = Clean(CleanAction.STOP)
_command_pause = Clean(CleanAction.PAUSE)
def __init__(self, vacuum_bot: VacuumBot):
"""Initialize the Deebot Vacuum."""
super().__init__(
vacuum_bot,
StateVacuumEntityDescription(key="", translation_key="bot", name=None),
)
self._rooms: list[Room] = []
self._last_error: ErrorEvent | None = None
if vacuum_bot.is_goat:
self.entity_description.icon = "mdi:robot-mower-outline"
self._attr_supported_features = (
VacuumEntityFeature.PAUSE
| VacuumEntityFeature.STOP
| VacuumEntityFeature.RETURN_HOME
| VacuumEntityFeature.BATTERY
| VacuumEntityFeature.SEND_COMMAND
| VacuumEntityFeature.STATE
| VacuumEntityFeature.START
)
self._command_start = CleanV2(MowerAction.START)
self._command_stop = CleanV2(MowerAction.STOP)
self._command_pause = CleanV2(MowerAction.PAUSE)
async def async_added_to_hass(self) -> None:
"""Set up the event listeners now that hass is ready."""
await super().async_added_to_hass()
async def on_battery(event: BatteryEvent) -> None:
self._attr_battery_level = event.value
self.async_write_ha_state()
async def on_custom_command(event: CustomCommandEvent) -> None:
self.hass.bus.fire(EVENT_CUSTOM_COMMAND, dataclass_to_dict(event))
async def on_error(event: ErrorEvent) -> None:
self._last_error = event
self.async_write_ha_state()
async def on_fan_speed(event: FanSpeedEvent) -> None:
self._attr_fan_speed = event.speed.display_name
self.async_write_ha_state()
async def on_report_stats(event: ReportStatsEvent) -> None:
self.hass.bus.fire(EVENT_CLEANING_JOB, dataclass_to_dict(event))
async def on_rooms(event: RoomsEvent) -> None:
self._rooms = event.rooms
self.async_write_ha_state()
async def on_status(event: StateEvent) -> None:
self._attr_state = VACUUMSTATE_TO_STATE[event.state]
if self._vacuum_bot.is_goat and event.state == VacuumState.CLEANING:
self._attr_state = "Mowing"
self.async_write_ha_state()
async def on_status_v2(event: StateEventV2) -> None:
self._attr_state = VACUUMSTATE_TO_STATE[event.state]
if self._vacuum_bot.is_goat and event.state == VacuumState.CLEANING:
self._attr_state = "Mowing"
self.async_write_ha_state()
subscriptions = [
self._vacuum_bot.events.subscribe(BatteryEvent, on_battery),
self._vacuum_bot.events.subscribe(CustomCommandEvent, on_custom_command),
self._vacuum_bot.events.subscribe(ErrorEvent, on_error),
self._vacuum_bot.events.subscribe(FanSpeedEvent, on_fan_speed),
self._vacuum_bot.events.subscribe(ReportStatsEvent, on_report_stats),
self._vacuum_bot.events.subscribe(RoomsEvent, on_rooms),
]
subscriptions.append(self._vacuum_bot.events.subscribe(StateEvent, on_status))
if self._vacuum_bot.is_goat:
subscriptions.append(self._vacuum_bot.events.subscribe(StateEventV2, on_status_v2))
def unsubscribe() -> None:
for sub in subscriptions:
sub()
self.async_on_remove(unsubscribe)
@property
def extra_state_attributes(self) -> Mapping[str, Any] | None:
"""Return entity specific state attributes.
Implemented by platform classes. Convention for attribute names
is lowercase snake_case.
"""
attributes: dict[str, Any] = {}
rooms: dict[str, Any] = {}
for room in self._rooms:
# convert room name to snake_case to meet the convention
room_name = slugify(room.name)
room_values = rooms.get(room_name)
if room_values is None:
rooms[room_name] = room.id
elif isinstance(room_values, list):
room_values.append(room.id)
else:
# Convert from int to list
rooms[room_name] = [room_values, room.id]
if rooms:
attributes["rooms"] = rooms
if self._last_error:
attributes[
LAST_ERROR
] = f"{self._last_error.description} ({self._last_error.code})"
return attributes
async def async_set_fan_speed(self, fan_speed: str, **kwargs: Any) -> None:
"""Set fan speed."""
await self._vacuum_bot.execute_command(SetFanSpeed(fan_speed))
async def async_return_to_base(self, **kwargs: Any) -> None:
"""Set the vacuum cleaner to return to the dock."""
await self._vacuum_bot.execute_command(Charge())
async def async_stop(self, **kwargs: Any) -> None:
"""Stop the vacuum cleaner."""
await self._vacuum_bot.execute_command(self._command_stop)
async def async_pause(self) -> None:
"""Pause the vacuum cleaner."""
await self._vacuum_bot.execute_command(self._command_pause)
async def async_start(self) -> None:
"""Start the vacuum cleaner."""
await self._vacuum_bot.execute_command(self._command_start)
async def async_locate(self, **kwargs: Any) -> None:
"""Locate the vacuum cleaner."""
await self._vacuum_bot.execute_command(PlaySound())
async def async_send_command(
self, command: str, params: dict[str, Any] | None = None, **kwargs: Any
) -> None:
"""Send a command to a vacuum cleaner."""
_LOGGER.debug("async_send_command %s with %s", command, params)
if command in ["relocate", SetRelocationState.name]:
_LOGGER.warning("DEPRECATED! Please use relocate button entity instead.")
await self._vacuum_bot.execute_command(SetRelocationState())
elif command == "auto_clean":
clean_type = params.get("type", "auto") if params else "auto"
if clean_type == "auto":
_LOGGER.warning('DEPRECATED! Please use "vacuum.start" instead.')
await self.async_start()
elif command in ["spot_area", "custom_area", "set_water"]:
if params is None:
raise RuntimeError("Params are required!")
if command in "spot_area":
await self._vacuum_bot.execute_command(
CleanArea(
mode=CleanMode.SPOT_AREA,
area=str(params["rooms"]),
cleanings=params.get("cleanings", 1),
)
)
elif command == "custom_area":
await self._vacuum_bot.execute_command(
CleanArea(
mode=CleanMode.CUSTOM_AREA,
area=str(params["coordinates"]),
cleanings=params.get("cleanings", 1),
)
)
elif command == "set_water":
_LOGGER.warning("DEPRECATED! Please use water select entity instead.")
await self._vacuum_bot.execute_command(SetWaterInfo(params["amount"]))
else:
await self._vacuum_bot.execute_command(CustomCommand(command, params))
async def service_refresh(self, category: str) -> None:
"""Service to manually refresh."""
_LOGGER.debug("Manually refresh %s", category)
event = REFRESH_STR_TO_EVENT_DTO.get(category, None)
if event:
self._vacuum_bot.events.request_refresh(event)
elif category == REFRESH_MAP:
self._vacuum_bot.map.refresh()
else:
_LOGGER.warning(
'Service "refresh" called with unknown category: %s', category
)