Coverage for custom_components/appliance_autonotify/watcher.py: 98%

1372 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-28 12:19 +0000

1"""Watch one appliance, and notify as its cycle starts, progresses and ends""" 

2 

3from __future__ import annotations 

4 

5import asyncio 

6import hashlib 

7import logging 

8from datetime import timedelta 

9from functools import partial 

10from typing import TYPE_CHECKING, Any 

11 

12from homeassistant.components.binary_sensor import BinarySensorDeviceClass 

13from homeassistant.components.sensor import SensorDeviceClass 

14from homeassistant.const import ( 

15 ATTR_ENTITY_ID, 

16 ATTR_UNIT_OF_MEASUREMENT, 

17 CONF_DEVICE_ID, 

18 CONF_TYPE, 

19 EVENT_HOMEASSISTANT_STOP, 

20 PERCENTAGE, 

21 STATE_ON, 

22 STATE_UNAVAILABLE, 

23 STATE_UNKNOWN, 

24 UnitOfPower, 

25 UnitOfTime, 

26) 

27from homeassistant.core import CALLBACK_TYPE, Context, Event, EventStateChangedData, HomeAssistant, State, callback 

28from homeassistant.exceptions import ConfigEntryNotReady, HomeAssistantError 

29from homeassistant.helpers import device_registry as dr 

30from homeassistant.helpers import entity_registry as er 

31from homeassistant.helpers.event import async_call_later, async_track_state_change_event, async_track_time_interval 

32from homeassistant.helpers.storage import Store 

33from homeassistant.helpers.translation import async_translate_state 

34from homeassistant.util import dt as dt_util 

35from homeassistant.util.unit_conversion import DurationConverter, PowerConverter 

36 

37from .const import ( 

38 ACTION_FINISHED, 

39 ACTION_MAINTAINED, 

40 ACTION_MAINTENANCE_LATER, 

41 ACTION_REMIND, 

42 ACTION_SWITCH_OFF, 

43 ACTION_TITLES, 

44 ACTION_TRACK_MAINTENANCE, 

45 ANDROID_BUTTONS, 

46 ANDROID_CHANNEL, 

47 CAVITY_TEMPERATURE_KEY, 

48 CONF_CUSTOM_TARGET, 

49 CONF_DASHBOARD, 

50 CONF_DELIVERIES, 

51 CONF_END_MESSAGE, 

52 CONF_END_TITLE, 

53 CONF_GRACE_PERIOD, 

54 CONF_LIVE_SHOW, 

55 CONF_LIVE_TIMER, 

56 CONF_MAINTENANCE, 

57 CONF_MIN_DURATION, 

58 CONF_NOTIFY_END, 

59 CONF_NOTIFY_PHASE, 

60 CONF_NOTIFY_PROGRESS, 

61 CONF_NOTIFY_START, 

62 CONF_OFFLINE_AFTER, 

63 CONF_POWER_ENTITY, 

64 CONF_REMINDER, 

65 CONF_REMINDER_REPEATS, 

66 CONF_START_MESSAGE, 

67 CONF_START_TITLE, 

68 CONF_SWITCH_ENTITY, 

69 CONF_SWITCH_OFF_BUTTON, 

70 CONF_TARGET, 

71 CONF_TARGETS, 

72 CONF_THRESHOLD, 

73 COST_PLACEHOLDER, 

74 CYCLE_KEPT_HOURS, 

75 CYCLE_KEY, 

76 CYCLE_SAVE_DELAY, 

77 CYCLE_SETTLE, 

78 CYCLE_STORE, 

79 CYCLE_STORE_VERSION, 

80 DEFAULT_GRACE_PERIOD, 

81 DEFAULT_ICON, 

82 DEFAULT_MIN_DURATION, 

83 DEFAULT_REMINDER_REPEATS, 

84 DEFAULT_SNOOZE, 

85 DEFAULT_THRESHOLD, 

86 DEFAULT_TITLE, 

87 DOMAIN, 

88 DURATION_PLACEHOLDER, 

89 ELAPSED_TIME_KEY, 

90 ENERGY_PLACEHOLDER, 

91 ENTITY_DOMAINS, 

92 FAST_PREHEAT_KEY, 

93 FINISH_MOVED, 

94 FINISH_TIME_KEY, 

95 LIVE_DEFAULTS, 

96 LIVE_HOLD, 

97 LIVE_HOLD_MAX, 

98 LIVE_SEPARATOR, 

99 LIVE_SETTLE, 

100 LIVE_SHOW_PHASE, 

101 LIVE_SHOW_PROGRAM, 

102 LIVE_SHOW_STATE, 

103 LIVE_TITLE, 

104 LIVE_TITLE_ROOM, 

105 MAINTENANCE_ACTION_TITLES, 

106 MOBILE_ACTION_EVENT, 

107 MOBILE_APP_PLATFORM, 

108 MOBILE_PUSH_TRANSPORT, 

109 NAME_PLACEHOLDER, 

110 NOTIFICATION_TEXTS, 

111 OVEN_MESSAGE, 

112 PHASES_NOTIFIED, 

113 PREHEAT_FINISHED_KEYS, 

114 PREHEAT_SETTLE, 

115 PROGRAM_KEYS, 

116 PROGRAM_PLACEHOLDER, 

117 PROGRESS_CHIP, 

118 PROGRESS_FINAL, 

119 PROGRESS_FINAL_STEP, 

120 PROGRESS_KEY, 

121 PROGRESS_NOTIFY_STEP, 

122 PROGRESS_STEP, 

123 PROGRESS_TICK, 

124 REMAINING_TIME_KEY, 

125 STAGE_KEY, 

126 STAGES_FINISHED, 

127 STAGES_NONE, 

128 START_SETTLE, 

129 START_TIME_PLACEHOLDER, 

130 STATES_ABANDONED, 

131 STATES_ACTIVE, 

132 STATES_EVENT_ON, 

133 STATES_FINISHED, 

134 STATES_RUN, 

135 STATES_SETTLING, 

136 STUCK_MESSAGES, 

137 SUPERNOTIFY_DOMAIN, 

138 TARGET_TEMPERATURE_KEY, 

139 TEMPERATURE_STEP, 

140 TEXT_END, 

141 TEXT_FAST_PREHEAT, 

142 TEXT_OFFLINE, 

143 TEXT_ONLINE, 

144 TEXT_PREHEAT, 

145 TEXT_PREHEATED, 

146 TEXT_PREHEATING, 

147 TEXT_PROGRESS, 

148 TEXT_START, 

149 TOTAL_TIME_KEY, 

150 TYPE_DISCOVERY, 

151 TYPE_ICONS, 

152 TYPE_VACUUM, 

153 VACUUM_BLIP, 

154 VACUUM_BLIP_KIND, 

155 VACUUM_BLIP_SETTLE, 

156 VACUUM_CLEANING, 

157 VACUUM_COMPLETE_KIND, 

158 VACUUM_COMPLETE_SETTLE, 

159 VACUUM_DONE, 

160 VACUUM_ERROR, 

161 VACUUM_HELD_KIND, 

162 VACUUM_HELD_SETTLE, 

163 VACUUM_JOB_LEAD, 

164 VACUUM_MIDWAY_KIND, 

165 VACUUM_MIDWAY_SETTLE, 

166 VACUUM_PAUSED, 

167 VACUUM_PROGRAM_KEYS, 

168 VACUUM_PROGRESS_KEYS, 

169 VACUUM_RETURNING, 

170 VACUUM_SETTLE, 

171 VACUUM_STATUS_KEYS, 

172) 

173from .dashboards import dashboard_url 

174from .discovery import companions, cycle_entities, device_type, integration_name, is_cycle_entity, role_key 

175from .maintenance import DATA_MAINTENANCE, MaintenanceItem, MaintenanceTracker, maintenance_items, translated 

176from .platforms import GENERIC, PlatformProfile, profile_for 

177from .repairs import async_forget_no_targets, async_report_no_targets 

178from .supernotify_api import deliveries_by_transport, supernotify_available 

179from .totals import ( 

180 CycleTotals, 

181 counts_program, 

182 energy_entity_id, 

183 energy_price, 

184 energy_reading, 

185 format_cost, 

186 format_duration, 

187 format_energy, 

188 format_time, 

189) 

190from .trace import CycleTrace, async_ask_feedback 

191from .words import name_type 

192 

193if TYPE_CHECKING: 

194 from collections.abc import Callable, Coroutine, Mapping 

195 from datetime import datetime 

196 

197 from homeassistant.config_entries import ConfigEntry 

198 

199_LOGGER = logging.getLogger(__name__) 

200 

201 

202def _later(context: Context) -> Context: 

203 """A context of its own for what a timer sets off, leading back to whatever set the timer""" 

204 return Context(parent_id=context.id) 

205 

206 

207def _time(value: object) -> datetime | None: 

208 """A time as kept, or None where there's none""" 

209 return dt_util.parse_datetime(value) if isinstance(value, str) else None 

210 

211 

212def _iso(value: datetime | None) -> str | None: 

213 return value.isoformat() if value is not None else None 

214 

215 

216def _float(state: State | None) -> float | None: 

217 """A state as a number, or None where it isn't one, as when unavailable""" 

218 try: 

219 return float(state.state) if state is not None else None 

220 except ValueError: 

221 return None 

222 

223 

224def _totals_kept(totals: CycleTotals) -> dict[str, Any]: 

225 """What the last cycle came to, as kept through a restart for its reminders""" 

226 return { 

227 "started": _iso(totals.started), 

228 "duration": totals.duration.total_seconds() if totals.duration is not None else None, 

229 "energy": totals.energy, 

230 "cost": totals.cost, 

231 } 

232 

233 

234def _kept_totals(kept: object) -> CycleTotals: 

235 if not isinstance(kept, dict): 

236 return CycleTotals() 

237 duration = kept.get("duration") 

238 return CycleTotals( 

239 _time(kept.get("started")), 

240 timedelta(seconds=duration) if isinstance(duration, (int, float)) else None, 

241 kept.get("energy") if isinstance(kept.get("energy"), (int, float)) else None, 

242 kept.get("cost") if isinstance(kept.get("cost"), (int, float)) else None, 

243 ) 

244 

245 

246def _seconds_to(due: datetime) -> float: 

247 """Seconds till a time, none if it's already past""" 

248 return max(0.0, (due - dt_util.utcnow()).total_seconds()) 

249 

250 

251class ApplianceWatcher: 

252 """The notifications of a cycle, for subclasses that know when one starts and ends""" 

253 

254 def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None: 

255 self.hass = hass 

256 self.entry = entry 

257 self.name: str = entry.title 

258 self.tag: str = f"appliance_{entry.entry_id}" 

259 # the end has a tag of its own, so it can be cleared or told again without touching a Live Activity 

260 self.end_tag: str = f"{self.tag}_end" 

261 # the type of appliance, such as `washer`, from its name until the appliance itself says 

262 self.appliance_type: str | None = name_type(hass, self.name) 

263 self.icon: str = self._name_icon() 

264 self.cycle_entity_id: str | None = None 

265 # by translation key, whichever of those made use of the appliance has 

266 self.entity_ids: dict[str, str] = {} 

267 # the same, of the same appliance through another integration, for while the first can't be heard from 

268 self.fallback_cycle_entity_id: str | None = None 

269 self.fallback_ids: dict[str, str] = {} 

270 self.notify_start: bool = entry.options.get(CONF_NOTIFY_START, False) 

271 self.notify_end: bool = entry.options.get(CONF_NOTIFY_END, True) 

272 self.notify_progress: bool = entry.options.get(CONF_NOTIFY_PROGRESS, False) 

273 self.live_timer: bool = entry.options.get(CONF_LIVE_TIMER, LIVE_DEFAULTS[CONF_LIVE_TIMER]) 

274 self.live_show: list[str] = list(entry.options.get(CONF_LIVE_SHOW, LIVE_DEFAULTS[CONF_LIVE_SHOW])) 

275 # the state last shown on the Live Activity, so it's brought up to date as the appliance pauses and carries on 

276 self.state_shown: str | None = None 

277 # the program last known, since an appliance may no longer report one by the time its end is told 

278 self.last_program: str = "" 

279 # the program of the cycle just over, kept for its reminders, since an appliance may by then have gone back 

280 # to the program it starts on, as a Samsung dryer does 

281 self.program_kept: bool = False 

282 # whether phases are notified unless chosen otherwise, None for an appliance that reports none 

283 self.phase_default: bool | None = None 

284 self.notify_phase: bool = False 

285 self.running: bool = False 

286 # the progress last sent, rounded down to the step it was sent for 

287 self.last_progress_mark: int = 0 

288 # the finish last sent to the Live Activity, which the appliance may put back as it goes, as a dryer does 

289 self.last_finish: datetime | None = None 

290 # one notification at a time, so a progress update can't overtake the end and reopen the Live Activity 

291 self._sending: asyncio.Lock = asyncio.Lock() 

292 # the quiet Live Activity update waiting to be sent, the latest asked for, since when one has been waiting, 

293 # and till when none is sent at all, while the Live Activity opens 

294 self._live_pending: tuple[str, Context] | None = None 

295 self._live_waiting: datetime | None = None 

296 self._live_opening: datetime | None = None 

297 self._cancel_live: CALLBACK_TYPE | None = None 

298 # what the Live Activity was last sent quietly, so the same isn't sent again, Supernotify's own duplicate 

299 # check being off for these 

300 self._live_sent: tuple[str, str, dict[str, Any]] | None = None 

301 entry.async_on_unload(self._stop_live) 

302 self.reminder: float = entry.options.get(CONF_REMINDER, 0) 

303 self.reminder_repeats: int = int(entry.options.get(CONF_REMINDER_REPEATS, DEFAULT_REMINDER_REPEATS)) 

304 # the smart plug to switch off from the end notification, which only a power monitored appliance has 

305 self.switch_entity_id: str | None = None 

306 self._reminders_sent: int = 0 

307 self._cancel_reminder: CALLBACK_TYPE | None = None 

308 # the end of the cycle, waiting to see that the appliance doesn't carry on 

309 self._cancel_end: CALLBACK_TYPE | None = None 

310 # when the cycle under way started, not known of one already under way when first watched 

311 self.started_at: datetime | None = None 

312 # when the cycle under way began, which for an appliance on a smart plug is when it first drew power rather 

313 # than once it had for long enough to count, and when it stopped, if it has, while waiting to see it doesn't 

314 # carry on 

315 self.cycle_started: datetime | None = None 

316 self.cycle_stopped: datetime | None = None 

317 # the energy meter of the appliance, where it has one, and its reading as the cycle began 

318 self._energy_entity_id: str | None = None 

319 self._energy_start: float | None = None 

320 # it stopped while Home Assistant was off, at a time there's no knowing 

321 self._stop_unseen: bool = False 

322 # what the last cycle came to, for its end and its reminders 

323 self.totals: CycleTotals = CycleTotals() 

324 # when the end waited for is due, and the next reminder of it, kept so neither is lost to a restart 

325 self._end_due: datetime | None = None 

326 self._reminder_due: datetime | None = None 

327 # the cycle as kept through a restart of Home Assistant: what was found from before it, what was last kept, 

328 # and what is to be written, None till anything has changed 

329 self._store: Store[dict[str, Any]] = Store(hass, CYCLE_STORE_VERSION, CYCLE_STORE.format(entry_id=entry.entry_id)) 

330 self._restored: dict[str, Any] = {} 

331 # minutes the appliance must be unavailable before it's told of as offline, none unless chosen, and since when 

332 # it has been, and whether that's been told, to tell it's back 

333 self.offline_after: float = float(entry.options.get(CONF_OFFLINE_AFTER) or 0) 

334 self.offline_since: datetime | None = None 

335 self.offline_told: bool = False 

336 self._cancel_offline: CALLBACK_TYPE | None = None 

337 self.offline_tag: str = f"{self.tag}_offline" 

338 self._kept: dict[str, Any] = {} 

339 self._written: dict[str, Any] | None = None 

340 # whether maintenance is tracked, None until it's been asked for or turned down 

341 self.maintenance: bool | None = entry.options.get(CONF_MAINTENANCE) 

342 # the items there are to track, whether or not they are, so tracking is only offered where there's something 

343 self.maintenance_items: list[MaintenanceItem] = [] 

344 # tracking offered on the end notification of the cycle just over 

345 self._offering: bool = False 

346 # the integration the appliance comes through, and what it does, kept while that's yet to be tried 

347 self.profile: PlatformProfile = GENERIC 

348 # and that of each cycle state entity, from either integration for the same appliance 

349 self._cycle_profiles: dict[str, PlatformProfile] = {} 

350 self.trace: CycleTrace | None = None 

351 

352 async def async_load(self) -> None: 

353 """What was kept of the cycle before Home Assistant restarted, unless too old to carry on from, as when it 

354 has been off for a day""" 

355 kept = await self._store.async_load() or {} 

356 saved_at = _time(kept.get("saved_at")) 

357 if saved_at is not None and (dt_util.utcnow() - saved_at).total_seconds() < CYCLE_KEPT_HOURS * 3600: 

358 self._restored = kept 

359 self._kept = {key: value for key, value in kept.items() if key != "saved_at"} 

360 # written straight away, rather than a moment later, as the appliance is unloaded or Home Assistant stops 

361 self.entry.async_on_unload(self._flush) 

362 self.entry.async_on_unload(self.hass.bus.async_listen(EVENT_HOMEASSISTANT_STOP, self._stopping)) 

363 

364 @callback 

365 def _restore(self) -> bool: 

366 """Carry on from what was kept before a restart, saying whether a cycle was under way""" 

367 kept = self._restored 

368 self.last_program = kept.get("program") or "" 

369 self.program_kept = bool(kept.get("program_kept")) 

370 self.started_at = _time(kept.get("started_at")) 

371 # what the totals of the cycle are reckoned from 

372 totals = kept.get("totals") 

373 if not isinstance(totals, dict): 

374 # kept by a version that didn't keep them, so timed from when it was said to start, with nothing metered 

375 totals = {"started": kept.get("started_at")} 

376 self.cycle_started = _time(totals.get("started")) 

377 self.cycle_stopped = _time(totals.get("stopped")) 

378 energy_entity = totals.get("energy_entity") 

379 self._energy_entity_id = energy_entity if isinstance(energy_entity, str) else None 

380 energy_start = totals.get("energy_start") 

381 self._energy_start = float(energy_start) if isinstance(energy_start, (int, float)) else None 

382 self._stop_unseen = bool(totals.get("stop_unseen")) 

383 # and what the cycle just over came to, for its reminders 

384 self.totals = _kept_totals(totals.get("last")) 

385 self._reminders_sent = int(kept.get("reminders_sent") or 0) 

386 self._offering = bool(kept.get("offering")) and self.maintenance is None 

387 if (due := _time(kept.get("reminder_due"))) is not None: 

388 # told straight away if it fell due while Home Assistant was off, once however long that was 

389 self._remind_at(due, Context()) 

390 return bool(kept.get("running")) 

391 

392 def _phase_data(self) -> dict[str, Any]: 

393 """How far the cycle has got, as only some kinds of appliance know""" 

394 return {} 

395 

396 def _worth_keeping(self) -> bool: 

397 return self.running or self._end_due is not None or self._reminder_due is not None 

398 

399 @callback 

400 def _save(self) -> None: 

401 """Keep the cycle through a restart, written a moment later so that changes close together are written once""" 

402 data: dict[str, Any] = {} 

403 if self._worth_keeping(): 

404 data = { 

405 "running": self.running, 

406 "started_at": _iso(self.started_at), 

407 "program": self.last_program, 

408 "program_kept": self.program_kept, 

409 "end_due": _iso(self._end_due), 

410 "reminder_due": _iso(self._reminder_due), 

411 "reminders_sent": self._reminders_sent, 

412 # the offer to track maintenance, still made by the reminders of the end it was made on 

413 "offering": self._offering, 

414 "phase": self._phase_data(), 

415 "totals": { 

416 "started": _iso(self.cycle_started), 

417 "stopped": _iso(self.cycle_stopped), 

418 "energy_entity": self._energy_entity_id, 

419 "energy_start": self._energy_start, 

420 "stop_unseen": self._stop_unseen, 

421 "last": _totals_kept(self.totals), 

422 }, 

423 } 

424 if self.offline_since is not None: 

425 # kept whether or not a cycle is, to tell it's back however long it's been 

426 data["offline"] = {"since": _iso(self.offline_since), "told": self.offline_told} 

427 if data == self._kept: 

428 return 

429 self._kept = data 

430 # with when it was kept, to know whether it's too old to carry on from 

431 written = data | {"saved_at": dt_util.utcnow().isoformat()} if data else {} 

432 self._written = written 

433 self._store.async_delay_save(lambda: written, CYCLE_SAVE_DELAY) 

434 

435 async def _flush(self) -> None: 

436 if self._written is not None: 

437 await self._store.async_save(self._written) 

438 

439 async def _stopping(self, event: Event) -> None: 

440 await self._flush() 

441 

442 @callback 

443 def async_start(self) -> None: 

444 raise NotImplementedError 

445 

446 def _health_entity_ids(self) -> list[str]: 

447 """What says whether the appliance can be reached: its cycle state, through either integration""" 

448 return [e for e in (self.cycle_entity_id, self.fallback_cycle_entity_id) if e] 

449 

450 @callback 

451 def _unreachable(self) -> bool: 

452 """Unavailable through every integration it's known by, as when it has lost its network or been switched 

453 off at the wall""" 

454 states = [state for e in self._health_entity_ids() if (state := self.hass.states.get(e)) is not None] 

455 return bool(states) and all(state.state == STATE_UNAVAILABLE for state in states) 

456 

457 @callback 

458 def async_watch_health(self) -> None: 

459 """Tell when the appliance has been unavailable for longer than chosen, and when it's back, if chosen""" 

460 kept: dict[str, Any] = self._restored.get("offline") or {} 

461 if not self.offline_after or not (entity_ids := self._health_entity_ids()): 

462 return 

463 self.offline_since = _time(kept.get("since")) 

464 self.offline_told = bool(kept.get("told")) 

465 self.entry.async_on_unload(async_track_state_change_event(self.hass, entity_ids, self._availability_changed)) 

466 self.entry.async_on_unload(self._stop_offline_wait) 

467 self.entry.async_create_background_task( 

468 self.hass, self._availability_now(Context()), f"{DOMAIN} availability {self.name}" 

469 ) 

470 

471 async def _availability_changed(self, event: Event[EventStateChangedData]) -> None: 

472 await self._availability_now(event.context) 

473 

474 async def _availability_now(self, context: Context) -> None: 

475 if self._unreachable(): 

476 if self.offline_since is None: 

477 states = [state for e in self._health_entity_ids() if (state := self.hass.states.get(e)) is not None] 

478 self.offline_since = max(state.last_changed for state in states) 

479 self._save() 

480 if not self.offline_told and self._cancel_offline is None: 

481 due = self.offline_since + timedelta(minutes=self.offline_after) 

482 self._cancel_offline = async_call_later(self.hass, _seconds_to(due), self._offline_due) 

483 return 

484 self._stop_offline_wait() 

485 since, told = self.offline_since, self.offline_told 

486 if since is None: 

487 return 

488 self.offline_since, self.offline_told = None, False 

489 self._save() 

490 if told: 

491 took = format_duration(self.hass, dt_util.utcnow() - since) 

492 await self._tell_health(self._texts[TEXT_ONLINE].format(name=self.name, duration=took), context) 

493 

494 async def _offline_due(self, now: datetime) -> None: 

495 self._cancel_offline = None 

496 if self.offline_told or self.offline_since is None or not self._unreachable(): 

497 return 

498 self.offline_told = True 

499 self._save() 

500 since = format_time(self.offline_since) 

501 await self._tell_health(self._texts[TEXT_OFFLINE].format(name=self.name, since=since), Context()) 

502 

503 @callback 

504 def _stop_offline_wait(self) -> None: 

505 if self._cancel_offline is not None: 

506 self._cancel_offline() 

507 self._cancel_offline = None 

508 

509 async def _tell_health(self, message: str, context: Context) -> None: 

510 """Offline, or back, with a tag of its own, so being back takes the place of being offline""" 

511 title = self._text(CONF_START_TITLE, DEFAULT_TITLE) 

512 _LOGGER.info("APPLIANCES %s", message) 

513 async with self._sending: 

514 if supernotify_available(self.hass): 

515 await self._supernotify( 

516 message, 

517 title, 

518 context, 

519 resend=True, 

520 extra_data={"notification_icon": self.icon, "mobile_push_notification_tag": self.offline_tag}, 

521 actions=self._tap_actions(), 

522 ) 

523 else: 

524 await self._send_message(message, title, context) 

525 

526 @property 

527 def beta(self) -> bool: 

528 """Whether its type of appliance is yet to be seen to work through its integration""" 

529 return self.profile.beta_for(self.appliance_type) 

530 

531 async def async_start_trace(self) -> None: 

532 """Keep what an appliance of a type yet to be seen to work through its integration does through its first 

533 cycles""" 

534 if not self.beta: 

535 return 

536 trace = CycleTrace(self.hass, self.entry.entry_id) 

537 await trace.async_load() 

538 self.trace = trace 

539 if (unsubscribe := trace.async_start(self._traced_roles())) is not None: 

540 self.entry.async_on_unload(unsubscribe) 

541 

542 def _traced_roles(self) -> dict[str, str]: 

543 """The entities made use of, by entity id, with what each is made use of for""" 

544 return {} 

545 

546 @property 

547 def _tracker(self) -> MaintenanceTracker | None: 

548 return self.hass.data.get(DATA_MAINTENANCE) 

549 

550 @callback 

551 def async_start_maintenance(self) -> None: 

552 """The items for the type of appliance, and those its integration reports the life of, tracked once asked for""" 

553 self.maintenance_items = maintenance_items( 

554 self.hass, self.appliance_type, self.entry.data.get(CONF_DEVICE_ID), self.entry.options 

555 ) 

556 if self.maintenance: 

557 self._track_maintenance() 

558 

559 @callback 

560 def _track_maintenance(self) -> None: 

561 tracker = self._tracker 

562 if tracker is None or not self.maintenance_items: 

563 return 

564 tracker.async_register(self.entry.entry_id, self.name, self.maintenance_items, self._part_due) 

565 self.entry.async_on_unload(partial(tracker.async_unregister, self.entry.entry_id)) 

566 if not any( 

567 entry.data.get(CONF_TYPE) == TYPE_DISCOVERY and not entry.disabled_by 

568 for entry in self.hass.config_entries.async_entries(DOMAIN) 

569 ): 

570 _LOGGER.warning( 

571 "APPLIANCES Maintenance of %s is tracked, but without the Automatic discovery entry there's no list of it", 

572 self.name, 

573 ) 

574 

575 @callback 

576 def _part_due(self, item: MaintenanceItem) -> None: 

577 """A part fallen due between cycles, told of straight away""" 

578 if (tracker := self._tracker) is not None: 

579 self.entry.async_create_task(self.hass, self._tell_maintenance(tracker, item, Context())) 

580 

581 @callback 

582 def async_listen_for_actions(self) -> None: 

583 """Answer the buttons on the end notification""" 

584 self.entry.async_on_unload(self.hass.bus.async_listen(MOBILE_ACTION_EVENT, self._action_pressed)) 

585 self.entry.async_on_unload(self._stop_reminding) 

586 

587 def _keep_running(self) -> None: 

588 self.cycle_stopped = None 

589 self._end_due = None 

590 if self._cancel_end is not None: 

591 self._cancel_end() 

592 self._cancel_end = None 

593 

594 def _totals_device_id(self) -> str | None: 

595 """The device whose energy meter tells what a cycle used""" 

596 return self.entry.data.get(CONF_DEVICE_ID) 

597 

598 @callback 

599 def _cycle_began(self) -> None: 

600 """Note when the cycle began, and the energy meter's reading, to tell what it came to once it's over""" 

601 if self.cycle_started is not None: 

602 return 

603 self.cycle_started = dt_util.utcnow() 

604 self.cycle_stopped = None 

605 self._energy_entity_id = energy_entity_id(self.hass, self._totals_device_id()) 

606 self._energy_start = energy_reading(self.hass, self._energy_entity_id) 

607 

608 @callback 

609 def _cycle_forgotten(self) -> None: 

610 """Not a cycle after all, or one over and summed up""" 

611 self.cycle_started = None 

612 self.cycle_stopped = None 

613 self._stop_unseen = False 

614 

615 async def _sum_up(self) -> None: 

616 """What the cycle just over came to, nothing being known of one already under way as Home Assistant started""" 

617 totals = CycleTotals() 

618 if (started := self.cycle_started) is not None: 

619 # up to when it stopped, not when that was believed, and not known if that was while Home Assistant was off 

620 duration = None if self._stop_unseen else (self.cycle_stopped or dt_util.utcnow()) - started 

621 used = cost = None 

622 end = energy_reading(self.hass, self._energy_entity_id) 

623 if end is not None and counts_program(self.hass, self._energy_entity_id): 

624 # what the program used, whatever it said as it began, which may have been the program before 

625 used = end 

626 elif self._energy_start is not None and end is not None and end >= self._energy_start: 

627 # and nothing to tell if the meter was reset part way through 

628 used = end - self._energy_start 

629 if used is not None and (price := await energy_price(self.hass)) is not None: 

630 cost = used * price 

631 totals = CycleTotals(started, duration, used, cost) 

632 self.totals = totals 

633 self._cycle_forgotten() 

634 

635 @callback 

636 def _end_at(self, due: datetime, then: Callable[[Context, datetime], Coroutine[Any, Any, None]], context: Context) -> None: 

637 """Wait to see that the appliance doesn't carry on, till a time kept through a restart""" 

638 self._end_due = due 

639 self._cancel_end = async_call_later(self.hass, _seconds_to(due), partial(then, context)) 

640 

641 @callback 

642 def _end_waited(self) -> None: 

643 self._cancel_end = None 

644 self._end_due = None 

645 

646 def _name_icon(self) -> str: 

647 return TYPE_ICONS.get(name_type(self.hass, self.name) or "", DEFAULT_ICON) 

648 

649 @staticmethod 

650 def _mark(progress: int) -> int: 

651 """The progress rounded down to the step it's sent for""" 

652 return progress - progress % (PROGRESS_FINAL_STEP if progress >= PROGRESS_FINAL else PROGRESS_STEP) 

653 

654 async def _progress_changed(self, event: Event[EventStateChangedData]) -> None: 

655 await self._progress_now(event.context) 

656 

657 async def _progress_tick(self, now: datetime) -> None: 

658 await self._progress_now(Context()) 

659 

660 def _finish_moved(self) -> bool: 

661 """Whether the appliance has put its finish back or forward since the Live Activity was told it, which would 

662 otherwise count down to a time gone by, a finish only now known coming soon enough with what's next to tell""" 

663 finish_time = self._finish_time() 

664 if finish_time is None or self.last_finish is None: 

665 return False 

666 return abs((finish_time - self.last_finish).total_seconds()) >= FINISH_MOVED 

667 

668 async def _progress_now(self, context: Context) -> None: 

669 if not self.running: 

670 return 

671 progress = self._progress() 

672 mark = None if progress is None else self._mark(progress) 

673 moved = self._finish_moved() 

674 if not moved and (mark is None or mark <= self.last_progress_mark): 

675 return 

676 # the first reading only fills in the Live Activity, coming straight after the start notification, as do 

677 # the steps between those notified and the smaller ones towards the end, and a finish put back, which may 

678 # take the bar back with it, to climb again from there 

679 step = PROGRESS_NOTIFY_STEP 

680 ordinary = mark is not None and self.notify_progress and mark // step > max(self.last_progress_mark, 0) // step 

681 if mark is not None: 

682 self.last_progress_mark = mark 

683 live = supernotify_available(self.hass) 

684 if not live and not ordinary: 

685 return 

686 async with self._sending: 

687 if not self.running: 

688 # the cycle ended while this waited its turn 

689 return 

690 message = ( 

691 self._progress_message(progress) 

692 if progress is not None 

693 else self._text(CONF_START_MESSAGE, self._texts[TEXT_START]) 

694 ) 

695 if live and not ordinary: 

696 # the bar already shows how far along it is, so there's room to say what it's doing 

697 message = self._phase() or message 

698 await self._tell(message, ordinary, context, resend=True) 

699 

700 async def _started(self, context: Context) -> None: 

701 self.program_kept = False 

702 self._cycle_began() 

703 # nothing yet to tell of this one 

704 self.totals = CycleTotals() 

705 self.started_at = dt_util.utcnow() 

706 # the last cycle's reminders are no use once the next one is under way 

707 self._stop_reminding() 

708 self._save() 

709 async with self._sending: 

710 self._stop_live() 

711 self._live_sent = None 

712 self._live_opening = None 

713 # resent, since to Supernotify a second cycle soon after the first is a repeat to be dropped 

714 await self._tell( 

715 self._text(CONF_START_MESSAGE, self._texts[TEXT_START]), self.notify_start, context, resend=True, at_once=True 

716 ) 

717 # whatever comes next waits, the first progress being only moments behind the start 

718 self._live_opening = dt_util.utcnow() + timedelta(seconds=LIVE_SETTLE) 

719 

720 async def _tell(self, message: str, ordinary: bool, context: Context, resend: bool = False, at_once: bool = False) -> None: 

721 """Notify of a cycle under way, either everywhere or with no more than its Live Activity brought up to date, 

722 which waits to send only the latest unless it's the start""" 

723 # a Live Activity keeps the title it started with 

724 title = self._text(CONF_START_TITLE, DEFAULT_TITLE) 

725 self.state_shown = self._state_shown() 

726 if not supernotify_available(self.hass): 

727 if ordinary: 

728 await self._send_message(message, title, context) 

729 return 

730 self.last_finish = self._finish_time() 

731 if ordinary: 

732 # everywhere, opening or updating the Live Activity on phones as it goes, and not what was sent quietly 

733 self._live_sent = None 

734 await self._supernotify( 

735 message, title, context, resend=resend, extra_data=self._live_data(), actions=self._tap_actions() 

736 ) 

737 return 

738 self._live_pending = (message, context) 

739 now = dt_util.utcnow() 

740 if at_once: 

741 due = now 

742 else: 

743 self._live_waiting = self._live_waiting or now 

744 due = min(now + timedelta(seconds=LIVE_HOLD), self._live_waiting + timedelta(seconds=LIVE_HOLD_MAX)) 

745 if self._live_opening is not None: 

746 due = max(due, self._live_opening) 

747 self._stop_live(forget=False) 

748 if due <= now: 

749 await self._tell_live() 

750 else: 

751 self._cancel_live = async_call_later(self.hass, (due - now).total_seconds(), self._live_due) 

752 

753 async def _live_due(self, now: datetime) -> None: 

754 self._cancel_live = None 

755 async with self._sending: 

756 if self.running: 

757 await self._tell_live() 

758 

759 async def _tell_live(self) -> None: 

760 """The latest quiet update of the Live Activity, as things are now, unless it's what was sent last""" 

761 pending, self._live_pending, self._live_waiting = self._live_pending, None, None 

762 if pending is None: 

763 return 

764 message, context = pending 

765 data = self._live_data() 

766 title, message = self._live_title(self._text(CONF_START_TITLE, DEFAULT_TITLE), message, timer="when" in data) 

767 if (title, message, data) == self._live_sent: 

768 return 

769 self._live_sent = (title, message, data) 

770 # with nothing to hear, and nothing sent anywhere but to phones 

771 await self._supernotify( 

772 message, 

773 title, 

774 context, 

775 mobile_only=True, 

776 extra_data=data | {"silent": True, "alert_once": True}, 

777 # iOS forgets where a tap goes unless told again on every update 

778 actions=self._tap_actions(), 

779 ) 

780 

781 @callback 

782 def _stop_live(self, forget: bool = True) -> None: 

783 """No quiet update sent later, and none left to send unless only put off""" 

784 if self._cancel_live is not None: 

785 self._cancel_live() 

786 self._cancel_live = None 

787 if forget: 

788 self._live_pending = None 

789 self._live_waiting = None 

790 

791 def _live_title(self, title: str, message: str, timer: bool) -> tuple[str, str]: 

792 """The title of a quiet Live Activity update, and its message. With a timer there's no message on the iOS Lock 

793 Screen, so what's shown goes in the title, as much as there's room for, leaving out the program first and then 

794 the phase, and the message has the progress in its place. With no timer the message has it all""" 

795 if not timer: 

796 return title, message 

797 details = [detail for detail in self._details() if detail not in title] 

798 while len(details) > 1 and len(LIVE_TITLE.format(title=title, phase=LIVE_SEPARATOR.join(details))) > LIVE_TITLE_ROOM: 

799 details.pop(0) 

800 if not details: 

801 return title, message 

802 if message == self._phase() and (progress := self._progress()) is not None: 

803 message = self._progress_message(progress) 

804 return LIVE_TITLE.format(title=title, phase=LIVE_SEPARATOR.join(details)), message 

805 

806 async def _ended(self, finished: bool, context: Context) -> None: 

807 self.last_program = self._program() or self.last_program 

808 self.program_kept = True 

809 await self._sum_up() 

810 title = self._text(CONF_END_TITLE, DEFAULT_TITLE) 

811 message = self._text(CONF_END_MESSAGE, self._texts[TEXT_END]) 

812 notify = finished and self.notify_end 

813 self._save() 

814 if self.trace is not None and self.trace.async_cycle_ended(finished): 

815 async_ask_feedback( 

816 self.hass, 

817 self.entry.entry_id, 

818 self.name, 

819 integration_name(self.hass, self.profile.platform), 

820 self.profile.issue_url, 

821 ) 

822 await self._tell_ended(notify, title, message, context) 

823 if finished: 

824 await self._maintenance_due(context) 

825 

826 async def _tell_ended(self, notify: bool, title: str, message: str, context: Context) -> None: 

827 async with self._sending: 

828 # an update sent after the end would open the Live Activity again 

829 self._stop_live() 

830 self._live_opening = None 

831 if not supernotify_available(self.hass): 

832 if notify: 

833 await self._send_message(message, title, context) 

834 return 

835 # closing the Live Activity is not a notification in itself, so the end is told separately 

836 await self._supernotify( 

837 message, 

838 title, 

839 context, 

840 mobile_only=True, 

841 extra_data={"mobile_push_notification_tag": self.tag, "mobile_push_clear_notification": True}, 

842 ) 

843 if notify: 

844 tracker = self._tracker 

845 # offered once, so anyone who'd want it needn't go looking, and nobody's bothered who wouldn't 

846 self._offering = ( 

847 tracker is not None 

848 and self.maintenance is None 

849 and bool(self.maintenance_items) 

850 and not tracker.offered(self.entry.entry_id) 

851 ) 

852 # the same end message as the last cycle would otherwise be dropped as a duplicate 

853 await self._tell_end(context, resend=True) 

854 if tracker is not None and self._offering: 

855 tracker.async_mark_offered(self.entry.entry_id) 

856 self._reminders_sent = 0 

857 if self.reminder: 

858 self._remind_in(self.reminder, context) 

859 

860 async def _maintenance_due(self, context: Context) -> None: 

861 """Another cycle counted, and each item it has made due told of, the once""" 

862 tracker = self._tracker 

863 if tracker is None or not tracker.tracked(self.entry.entry_id): 

864 return 

865 for item in tracker.async_cycle_ended(self.entry.entry_id): 

866 await self._tell_maintenance(tracker, item, context) 

867 

868 def _maintenance_tag(self, item: MaintenanceItem) -> str: 

869 # short, a part's key being its entity id, and iOS keeping only 64 bytes of a tag 

870 return f"{self.tag}_maintenance_{hashlib.sha256(item.key.encode()).hexdigest()[:8]}" 

871 

872 async def _tell_maintenance(self, tracker: MaintenanceTracker, item: MaintenanceItem, context: Context) -> None: 

873 message = tracker.message(self.entry.entry_id, item) 

874 if not supernotify_available(self.hass): 

875 await self._send_message(message, self.name, context) 

876 return 

877 titles = translated(self.hass, MAINTENANCE_ACTION_TITLES) 

878 actions = [ 

879 {"action": f"{button}{self.entry.entry_id}_{item.key}", "title": titles[button]} 

880 for button in (ACTION_MAINTAINED, ACTION_MAINTENANCE_LATER) 

881 ] 

882 async with self._sending: 

883 await self._supernotify( 

884 message, 

885 self.name, 

886 context, 

887 resend=True, 

888 actions=actions + self._tap_actions(), 

889 extra_data={ 

890 "notification_icon": "mdi:wrench-clock", 

891 "mobile_push_notification_tag": self._maintenance_tag(item), 

892 }, 

893 ) 

894 

895 async def _maintenance_pressed(self, action: str, context: Context) -> bool: 

896 """The buttons of the notification of an item due, and the one offering to track maintenance at all""" 

897 if action == f"{ACTION_TRACK_MAINTENANCE}{self.entry.entry_id}": 

898 # once only, a press left on an old notification not undoing it being turned off since 

899 if self.entry.options.get(CONF_MAINTENANCE) is None: 

900 self.maintenance = True 

901 # nor offered again by its reminders 

902 self._offering = False 

903 # tracked from now without a reload, which would drop the reminders of the end just told 

904 self._track_maintenance() 

905 self.hass.config_entries.async_update_entry( 

906 self.entry, options=dict(self.entry.options) | {CONF_MAINTENANCE: True} 

907 ) 

908 return True 

909 tracker = self._tracker 

910 for button in (ACTION_MAINTAINED, ACTION_MAINTENANCE_LATER): 

911 prefix = f"{button}{self.entry.entry_id}_" 

912 if tracker is None or not action.startswith(prefix): 

913 continue 

914 item = tracker.item(self.entry.entry_id, action.removeprefix(prefix)) 

915 if item is None: 

916 return True 

917 if button == ACTION_MAINTAINED: 

918 await tracker.async_done(self.entry.entry_id, item.key, context) 

919 else: 

920 tracker.async_snooze(self.entry.entry_id, item.key) 

921 await self._supernotify( 

922 self.name, 

923 self.name, 

924 context, 

925 mobile_only=True, 

926 extra_data={ 

927 "mobile_push_notification_tag": self._maintenance_tag(item), 

928 "mobile_push_clear_notification": True, 

929 }, 

930 ) 

931 return True 

932 return False 

933 

934 async def _tell_end(self, context: Context, resend: bool = False) -> None: 

935 """The end, with buttons to say the appliance has been seen to, to be reminded later, or to switch it off""" 

936 await self._supernotify( 

937 self._text(CONF_END_MESSAGE, self._texts[TEXT_END]), 

938 self._text(CONF_END_TITLE, DEFAULT_TITLE), 

939 context, 

940 resend=resend, 

941 actions=self._end_actions() + self._tap_actions(), 

942 extra_data={"notification_icon": self.icon, "mobile_push_notification_tag": self.end_tag}, 

943 ) 

944 

945 def _end_actions(self) -> list[dict[str, str]]: 

946 titles = ACTION_TITLES.get(self.hass.config.language.split("-")[0], ACTION_TITLES["en"]) 

947 buttons = [ACTION_FINISHED, ACTION_REMIND] + ([ACTION_SWITCH_OFF] if self._switchable() else []) 

948 if self._offering and len(buttons) >= ANDROID_BUTTONS: 

949 # Android shows only 3, so in place of Remind Later on the one notification it's offered on 

950 buttons.remove(ACTION_REMIND) 

951 actions = [{"action": f"{button}{self.entry.entry_id}", "title": titles[button]} for button in buttons] 

952 if self._offering: 

953 track = translated(self.hass, MAINTENANCE_ACTION_TITLES)[ACTION_TRACK_MAINTENANCE] 

954 actions.append({"action": f"{ACTION_TRACK_MAINTENANCE}{self.entry.entry_id}", "title": track}) 

955 return actions 

956 

957 def _switchable(self) -> bool: 

958 """Whether there's a smart plug to switch off, one chosen and since removed not being offered""" 

959 return self.switch_entity_id is not None and self.hass.states.get(self.switch_entity_id) is not None 

960 

961 def _snooze_minutes(self) -> int: 

962 return int(self.reminder or DEFAULT_SNOOZE) 

963 

964 @callback 

965 def _remind_in(self, minutes: float, context: Context) -> None: 

966 self._remind_at(dt_util.utcnow() + timedelta(minutes=minutes), context) 

967 

968 @callback 

969 def _remind_at(self, due: datetime, context: Context) -> None: 

970 self._stop_reminding() 

971 self._reminder_due = due 

972 self._cancel_reminder = async_call_later(self.hass, _seconds_to(due), partial(self._remind, context)) 

973 self._save() 

974 

975 @callback 

976 def _stop_reminding(self) -> None: 

977 self._reminder_due = None 

978 if self._cancel_reminder is not None: 

979 self._cancel_reminder() 

980 self._cancel_reminder = None 

981 

982 async def _remind(self, context: Context, now: datetime) -> None: 

983 self._cancel_reminder = None 

984 self._reminder_due = None 

985 self._reminders_sent += 1 

986 # Supernotify would drop the same message again as a duplicate 

987 await self._tell_end(_later(context), resend=True) 

988 if self.reminder and self._reminders_sent < self.reminder_repeats: 

989 self._remind_in(self.reminder, context) 

990 self._save() 

991 

992 async def _action_pressed(self, event: Event) -> None: 

993 action = str(event.data.get("action") or "") 

994 if await self._maintenance_pressed(action, event.context): 

995 return 

996 if action == f"{ACTION_FINISHED}{self.entry.entry_id}": 

997 self._stop_reminding() 

998 self._save() 

999 await self._supernotify( 

1000 self._text(CONF_END_MESSAGE, self._texts[TEXT_END]), 

1001 self._text(CONF_END_TITLE, DEFAULT_TITLE), 

1002 event.context, 

1003 mobile_only=True, 

1004 extra_data={"mobile_push_notification_tag": self.end_tag, "mobile_push_clear_notification": True}, 

1005 ) 

1006 elif action == f"{ACTION_REMIND}{self.entry.entry_id}": 

1007 self._remind_in(self._snooze_minutes(), event.context) 

1008 elif action == f"{ACTION_SWITCH_OFF}{self.entry.entry_id}" and self._switchable(): 

1009 if self.running: 

1010 # a button left from the last cycle, pressed once the next one has started 

1011 _LOGGER.warning("APPLIANCES %s is running again, so it was left switched on", self.name) 

1012 return 

1013 try: 

1014 await self.hass.services.async_call( 

1015 "switch", "turn_off", {ATTR_ENTITY_ID: self.switch_entity_id}, blocking=True, context=event.context 

1016 ) 

1017 except HomeAssistantError: 

1018 _LOGGER.exception("APPLIANCES Switching off %s failed", self.name) 

1019 

1020 @property 

1021 def _texts(self) -> Mapping[str, str]: 

1022 """The texts of notifications in the language of Home Assistant""" 

1023 return translated(self.hass, NOTIFICATION_TEXTS) 

1024 

1025 def _text(self, key: str, default: str) -> str: 

1026 """The text chosen for a notification, filled in""" 

1027 text = str(self.entry.options.get(key) or default).replace(NAME_PLACEHOLDER, self.name) 

1028 values: dict[str, str] = {} 

1029 totals = self.totals 

1030 if START_TIME_PLACEHOLDER in text: 

1031 # the cycle under way, else the last one 

1032 started = self.cycle_started or totals.started 

1033 values[START_TIME_PLACEHOLDER] = format_time(started) if started else "" 

1034 if DURATION_PLACEHOLDER in text: 

1035 values[DURATION_PLACEHOLDER] = "" if totals.duration is None else format_duration(self.hass, totals.duration) 

1036 for placeholder, amount, written in ( 

1037 (ENERGY_PLACEHOLDER, totals.energy, format_energy), 

1038 (COST_PLACEHOLDER, totals.cost, format_cost), 

1039 ): 

1040 if placeholder in text: 

1041 # nothing to say of less than a meter can count, rather than none used, or nothing to pay 

1042 counted = amount is not None and round(amount, 2) > 0 

1043 values[placeholder] = written(self.hass, amount or 0) if counted else "" 

1044 if PROGRAM_PLACEHOLDER in text: 

1045 if not self.program_kept: 

1046 self.last_program = self._program() or self.last_program 

1047 values[PROGRAM_PLACEHOLDER] = self.last_program 

1048 if not values: 

1049 return text 

1050 lines = text.split("\n") 

1051 filled = lines 

1052 for placeholder, value in values.items(): 

1053 filled = [line.replace(placeholder, value) for line in filled] 

1054 # a line of nothing but a placeholder left empty and its emoji goes, rather than the emoji alone 

1055 kept = [ 

1056 line 

1057 for line, before in zip(filled, lines, strict=True) 

1058 if any(c.isalnum() for c in line) or not any(p in before for p in values) 

1059 ] 

1060 # closing up the gaps left where there's nothing to say, line by line 

1061 return "\n".join(" ".join(line.split()) for line in "\n".join(kept).strip().split("\n")) 

1062 

1063 def _state(self, key: str) -> State | None: 

1064 """The state of one of the appliance's entities, where it has the entity and its state is known, or failing 

1065 that the same entity through another integration""" 

1066 for ids in (self.entity_ids, self.fallback_ids): 

1067 if (state := self._known(ids.get(key))) is not None: 

1068 return state 

1069 return None 

1070 

1071 def _known(self, entity_id: str | None) -> State | None: 

1072 state = self.hass.states.get(entity_id) if entity_id else None 

1073 return None if state is None or state.state in (STATE_UNKNOWN, STATE_UNAVAILABLE) else state 

1074 

1075 def _cycle_value(self, state: State | None) -> str | None: 

1076 """A state of the cycle as every integration has it, by the integration whose state it is""" 

1077 if state is None: 

1078 return None 

1079 return self._cycle_profiles.get(state.entity_id, self.profile).cycle_state(state.state) 

1080 

1081 def _cycle_state(self) -> State | None: 

1082 """The state of the cycle, from another integration for the same appliance while the first doesn't know it""" 

1083 return self._known(self.cycle_entity_id) or self._known(self.fallback_cycle_entity_id) 

1084 

1085 def _number(self, key: str) -> float | None: 

1086 state = self._state(key) 

1087 try: 

1088 return float(state.state) if state is not None else None 

1089 except ValueError: 

1090 return None 

1091 

1092 def _progress(self) -> int | None: 

1093 progress = self._number(PROGRESS_KEY) 

1094 return self._timed_progress() if progress is None else int(progress) 

1095 

1096 def _progress_message(self, progress: int) -> str: 

1097 return self._texts[TEXT_PROGRESS].format(progress=progress) 

1098 

1099 def _phase(self) -> str | None: 

1100 """What the appliance is doing, to say alongside a bar that already shows how far along it is""" 

1101 return LIVE_SEPARATOR.join(self._details()) or None 

1102 

1103 def _details(self) -> list[str]: 

1104 """Whichever of the program, the phase and the state are chosen to be shown and are reported, leaving out any 

1105 that says no more than one before it, as a vacuum's status of returning home does after its returning""" 

1106 shown: list[str] = [] 

1107 for key, detail in ( 

1108 (LIVE_SHOW_PROGRAM, self._program()), 

1109 (LIVE_SHOW_PHASE, self._stage()), 

1110 (LIVE_SHOW_STATE, self._state_shown()), 

1111 ): 

1112 if key not in self.live_show or not detail: 

1113 continue 

1114 if any(detail.casefold() in other.casefold() or other.casefold() in detail.casefold() for other in shown): 

1115 continue 

1116 shown.append(detail) 

1117 return shown 

1118 

1119 def _stage(self) -> str | None: 

1120 """The phase of the cycle the appliance is in, where its integration tells, for a subclass to work out where 

1121 its integration tells it some other way""" 

1122 stage = self._state(STAGE_KEY) 

1123 return self._translated(stage) if stage is not None and stage.state not in STAGES_NONE else None 

1124 

1125 def _state_shown(self) -> str | None: 

1126 """The state of the cycle, where it says more than that it's running, such as paused""" 

1127 state = self._cycle_state() 

1128 value = self._cycle_value(state) 

1129 if state is None or value in STATES_RUN or value not in STATES_ACTIVE: 

1130 return None 

1131 return self._translated(state) 

1132 

1133 async def _tell_state(self, context: Context) -> None: 

1134 """Bring the Live Activity up to date with the state, as it pauses or carries on, if it's shown""" 

1135 if LIVE_SHOW_STATE not in self.live_show or self._state_shown() == self.state_shown: 

1136 return 

1137 if not supernotify_available(self.hass): 

1138 return 

1139 async with self._sending: 

1140 if self.running: 

1141 # as a progress update would say it, so the state it no longer has isn't left showing 

1142 progress = self._progress() 

1143 message = self._phase() or ( 

1144 self._progress_message(progress) 

1145 if progress is not None 

1146 else self._text(CONF_START_MESSAGE, self._texts[TEXT_START]) 

1147 ) 

1148 await self._tell(message, False, context, resend=True) 

1149 

1150 def _program_state(self) -> State | None: 

1151 """The program under way, or failing that the one chosen, where the appliance reports either""" 

1152 return next((state for key in PROGRAM_KEYS if (state := self._state(key)) is not None), None) 

1153 

1154 def _program(self) -> str | None: 

1155 """The program as Home Assistant shows it""" 

1156 state = self._program_state() 

1157 return self._translated(state) if state is not None else None 

1158 

1159 def _seconds(self, key: str) -> float | None: 

1160 """A duration the appliance reports, in whatever unit of time, in seconds""" 

1161 state = self._state(key) 

1162 value = self._number(key) 

1163 unit = state.attributes.get(ATTR_UNIT_OF_MEASUREMENT, UnitOfTime.SECONDS) if state is not None else None 

1164 if value is None or unit not in DurationConverter.VALID_UNITS: 

1165 return None 

1166 return DurationConverter.convert(value, unit, UnitOfTime.SECONDS) 

1167 

1168 def _timed_progress(self) -> int | None: 

1169 """How far along the cycle is by the time it has left of the time it takes, or of the time it has taken and 

1170 has left, for an appliance that reports those but not its progress""" 

1171 finish_time = self._finish_time() 

1172 if finish_time is None: 

1173 return None 

1174 now = dt_util.utcnow() 

1175 left = (finish_time - now).total_seconds() 

1176 total = self._seconds(TOTAL_TIME_KEY) 

1177 if total is None and (elapsed := self._seconds(ELAPSED_TIME_KEY)) is not None: 

1178 total = elapsed + max(left, 0) 

1179 elif total is not None and self.started_at is not None: 

1180 # the time it said it would take, unless it's since put its finish back and will take longer, as a dryer 

1181 # does that finds its load still damp, and keeps the total it first said 

1182 total = max(total, (now - self.started_at).total_seconds() + max(left, 0)) 

1183 if not total or total <= 0: 

1184 return None 

1185 return int(min(max(100 * (1 - left / total), 0), 100)) 

1186 

1187 def _finish_time(self) -> datetime | None: 

1188 """When the cycle will finish, as the appliance says, or as long from now as it says is left""" 

1189 state = self._state(FINISH_TIME_KEY) 

1190 if state is not None and (finish_time := dt_util.parse_datetime(state.state)) is not None: 

1191 return finish_time 

1192 seconds = self._seconds(REMAINING_TIME_KEY) 

1193 if seconds is None or seconds <= 0: 

1194 return None 

1195 # to the nearest minute, so the countdown stays put from one update to the next unless the appliance has 

1196 # changed its mind 

1197 finish = (dt_util.utcnow() + timedelta(seconds=seconds)).timestamp() 

1198 return dt_util.utc_from_timestamp(round(finish / 60) * 60) 

1199 

1200 def _translated(self, state: State) -> str: 

1201 """A state as Home Assistant shows it, in its language""" 

1202 entity = er.async_get(self.hass).async_get(state.entity_id) 

1203 if entity is None: 

1204 return state.state 

1205 return async_translate_state(self.hass, state.state, state.domain, entity.platform, entity.translation_key, None) 

1206 

1207 def _tap_actions(self) -> list[dict[str, str]]: 

1208 """Where a tap on the notification goes, if a dashboard has been chosen, as a notification level action 

1209 that Supernotify sends as `url` to iOS and `clickAction` to Android""" 

1210 url = dashboard_url(self.hass, self.entry.options.get(CONF_DASHBOARD)) 

1211 return [{"level": "notification", "uri": url}] if url else [] 

1212 

1213 def _live_data(self) -> dict[str, Any]: 

1214 """Live Activity fields for the mobile app, leaving out whatever the appliance isn't reporting""" 

1215 data: dict[str, Any] = { 

1216 "mobile_push_notification_tag": self.tag, 

1217 "live_update": True, 

1218 "notification_icon": self.icon, 

1219 # Android only, iOS ignores them: a channel of its own so the start sounds, and kept when tapped as 

1220 # a Live Activity is, since otherwise the next update brings it back as a new, sounding, notification 

1221 "channel": ANDROID_CHANNEL, 

1222 "importance": "high", 

1223 "sticky": True, 

1224 } 

1225 progress = self._progress() 

1226 if progress is not None: 

1227 data["progress"] = progress 

1228 data["progress_max"] = 100 

1229 finish_time = self._finish_time() 

1230 if finish_time is not None and self.live_timer: 

1231 data["chronometer"] = True 

1232 data["when"] = int(finish_time.timestamp()) 

1233 elif progress is not None: 

1234 # the Android status bar chip shows this in place of the time left, so only with no time to show, and 

1235 # short, since a longer text leaves the chip with only its icon 

1236 data["critical_text"] = PROGRESS_CHIP.format(progress=progress) 

1237 return data 

1238 

1239 async def _supernotify( 

1240 self, 

1241 message: str, 

1242 title: str, 

1243 context: Context, 

1244 mobile_only: bool = False, 

1245 resend: bool = False, 

1246 extra_data: dict[str, Any] | None = None, 

1247 actions: list[dict[str, str]] | None = None, 

1248 ) -> None: 

1249 data: dict[str, Any] = {"message": message, "title": title} 

1250 if actions: 

1251 data["actions"] = actions 

1252 if resend: 

1253 # Supernotify's duplicate check ignores digits, so would drop progress updates as repeats 

1254 data["force_resend"] = True 

1255 deliveries: list[str] = list(self.entry.options.get(CONF_DELIVERIES) or []) 

1256 try: 

1257 if mobile_only: 

1258 mobile = (await deliveries_by_transport(self.hass, context)).get(MOBILE_PUSH_TRANSPORT, []) 

1259 deliveries = [d for d in mobile if not deliveries or d in deliveries] 

1260 if not deliveries: 

1261 _LOGGER.warning("APPLIANCES No mobile push delivery found for %s, Live Activity not updated", self.name) 

1262 return 

1263 data["delivery_selection"] = "fixed" 

1264 data["force_resend"] = True 

1265 elif deliveries: 

1266 data["delivery_selection"] = "explicit" 

1267 if deliveries: 

1268 data["delivery"] = deliveries 

1269 for key in (CONF_TARGET, CONF_CUSTOM_TARGET): 

1270 if value := self.entry.options.get(key): 

1271 data[key] = value 

1272 if extra_data: 

1273 data["extra_data"] = extra_data 

1274 await self.hass.services.async_call(SUPERNOTIFY_DOMAIN, "notify", data, blocking=True, context=context) 

1275 except HomeAssistantError: 

1276 _LOGGER.exception("APPLIANCES Supernotify notification failed for %s", self.name) 

1277 

1278 async def _send_message(self, message: str, title: str, context: Context) -> None: 

1279 # with none chosen, every phone with the mobile app is told 

1280 targets: list[str] = self.entry.options.get(CONF_TARGETS) or [ 

1281 entity.entity_id 

1282 for entity in er.async_get(self.hass).entities.values() 

1283 if entity.domain == "notify" and entity.platform == MOBILE_APP_PLATFORM and not entity.disabled 

1284 ] 

1285 if not targets: 

1286 _LOGGER.warning("APPLIANCES Nothing to notify for %s, choose targets in its settings", self.name) 

1287 async_report_no_targets(self.hass, self.name) 

1288 return 

1289 async_forget_no_targets(self.hass) 

1290 try: 

1291 await self.hass.services.async_call( 

1292 "notify", 

1293 "send_message", 

1294 {ATTR_ENTITY_ID: targets, "message": message, "title": title}, 

1295 blocking=True, 

1296 context=context, 

1297 ) 

1298 except HomeAssistantError: 

1299 _LOGGER.exception("APPLIANCES Notification failed for %s", self.name) 

1300 

1301 

1302class HomeConnectWatcher(ApplianceWatcher): 

1303 """An appliance whose integration reports the state of its cycle""" 

1304 

1305 def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None: 

1306 super().__init__(hass, entry) 

1307 # an oven on its way up to heat, and one that has been there since it was last switched on 

1308 self.preheating: bool = False 

1309 self.preheated: bool = False 

1310 # the temperature the Live Activity last showed, of an oven up to heat 

1311 self.shown_temperature: float | None = None 

1312 # the oven saying it's up to heat, waiting to see that it wasn't being switched off 

1313 self._cancel_preheated: CALLBACK_TYPE | None = None 

1314 # over by its stage while its cycle state still says it's running, so not a new cycle till that says it's over 

1315 self.over_by_stage: bool = False 

1316 # started, and waiting a moment for the program and stage to be reported before that's told 

1317 self.starting: bool = False 

1318 

1319 @callback 

1320 def async_start(self) -> None: 

1321 device_id: str = self.entry.data[CONF_DEVICE_ID] 

1322 device = dr.async_get(self.hass).async_get(device_id) 

1323 if device is not None: 

1324 self.name = device.name_by_user or device.name or self.name 

1325 entity_registry = er.async_get(self.hass) 

1326 for entity in er.async_entries_for_device(entity_registry, device_id): 

1327 key = role_key(entity) 

1328 if key is None or entity.disabled: 

1329 continue 

1330 if is_cycle_entity(entity): 

1331 self.cycle_entity_id = entity.entity_id 

1332 elif entity.domain in ENTITY_DOMAINS.get(key, ()): 

1333 self.entity_ids[key] = entity.entity_id 

1334 if self.cycle_entity_id is None: 

1335 raise ConfigEntryNotReady( 

1336 translation_domain=DOMAIN, translation_key="no_cycle_entity", translation_placeholders={"name": self.name} 

1337 ) 

1338 # the same appliance through another integration, heard from only while this one can't be 

1339 cycles = cycle_entities(self.hass) 

1340 for companion in companions(self.hass, device_id, cycles): 

1341 self.fallback_cycle_entity_id = self.fallback_cycle_entity_id or cycles[companion].entity_id 

1342 for entity in er.async_entries_for_device(entity_registry, companion): 

1343 key = role_key(entity) 

1344 if key is not None and not entity.disabled and entity.domain in ENTITY_DOMAINS.get(key, ()): 

1345 self.fallback_ids.setdefault(key, entity.entity_id) 

1346 cycle = entity_registry.async_get(self.cycle_entity_id) 

1347 self.profile = profile_for(cycle.platform if cycle else None) 

1348 for entity_id in (self.cycle_entity_id, self.fallback_cycle_entity_id): 

1349 if entity_id and (registered := entity_registry.async_get(entity_id)) is not None: 

1350 self._cycle_profiles[entity_id] = profile_for(registered.platform) 

1351 if self.profile.stage_from_cycle: 

1352 self.entity_ids.setdefault(STAGE_KEY, self.cycle_entity_id) 

1353 # the type of appliance isn't kept anywhere to be read, but its programs, entities or model are named for it 

1354 appliance_type = device_type(self.hass, device_id, self.profile) 

1355 self.appliance_type = appliance_type or name_type(self.hass, self.name) 

1356 self.icon = TYPE_ICONS.get(appliance_type or "", self._name_icon()) 

1357 # the one phase there is to know of is an oven warming up, Home Connect reporting none for anything else 

1358 if CAVITY_TEMPERATURE_KEY in self.entity_ids and TARGET_TEMPERATURE_KEY in self.entity_ids: 

1359 self.phase_default = appliance_type in PHASES_NOTIFIED 

1360 self.notify_phase = self.entry.options.get(CONF_NOTIFY_PHASE, self.phase_default) 

1361 

1362 # a cycle under way at startup still has its Live Activity closed when it ends 

1363 state = self._cycle_state() 

1364 self.running = self._cycle_value(state) in STATES_ACTIVE 

1365 # and with no knowing whether its oven has been up to heat, it isn't taken to be warming up 

1366 self.preheated = self.running 

1367 phase: dict[str, Any] = self._restored.get("phase") or {} 

1368 if self._restore(): 

1369 # still the cycle under way before Home Assistant restarted, whatever it has done since, so not started again 

1370 self.running = True 

1371 self.preheated = bool(phase.get("preheated", True)) 

1372 if (due := _time(self._restored.get("end_due"))) is not None: 

1373 self._end_at(due, self._settled, Context()) 

1374 elif phase.get("over_by_stage") or phase.get("starting"): 

1375 # over by its stage while still running, or yet to be told of as started 

1376 self.running = False 

1377 self.over_by_stage = bool(phase.get("over_by_stage")) 

1378 

1379 cycle_entity_ids = [e for e in (self.cycle_entity_id, self.fallback_cycle_entity_id) if e] 

1380 self.entry.async_on_unload(async_track_state_change_event(self.hass, cycle_entity_ids, self._cycle_changed)) 

1381 self.entry.async_on_unload(self._keep_running) 

1382 self.entry.async_on_unload(self._forget_preheated) 

1383 for keys, listener in ( 

1384 # and its finish, which an appliance may put back, as a dryer does, with no change of its progress 

1385 ((PROGRESS_KEY, FINISH_TIME_KEY, REMAINING_TIME_KEY), self._progress_changed), 

1386 ((STAGE_KEY,), self._stage_changed), 

1387 ((CAVITY_TEMPERATURE_KEY, TARGET_TEMPERATURE_KEY), self._temperature_changed), 

1388 (PREHEAT_FINISHED_KEYS, self._preheat_finished), 

1389 ): 

1390 if entity_ids := [ids[key] for ids in (self.entity_ids, self.fallback_ids) for key in keys if key in ids]: 

1391 self.entry.async_on_unload(async_track_state_change_event(self.hass, entity_ids, listener)) 

1392 if ( 

1393 PROGRESS_KEY not in self.entity_ids 

1394 and PROGRESS_KEY not in self.fallback_ids 

1395 and (TOTAL_TIME_KEY in self.entity_ids or ELAPSED_TIME_KEY in self.entity_ids) 

1396 ): 

1397 # progress worked out from the time, which moves on with no change of the appliance's to say so 

1398 self.entry.async_on_unload( 

1399 async_track_time_interval(self.hass, self._progress_tick, timedelta(seconds=PROGRESS_TICK)) 

1400 ) 

1401 if self._restored and state is not None: 

1402 # whatever it has done while Home Assistant was off, such as finishing, as if it were happening now 

1403 value = self._cycle_value(state) or state.state 

1404 self.entry.async_create_task(self.hass, self._cycle_is(value, Context()), eager_start=False) 

1405 self._save() 

1406 

1407 def _phase_data(self) -> dict[str, Any]: 

1408 return {"preheated": self.preheated, "over_by_stage": self.over_by_stage, "starting": self.starting} 

1409 

1410 def _traced_roles(self) -> dict[str, str]: 

1411 roles = {entity_id: f"fallback_{key}" for key, entity_id in self.fallback_ids.items()} 

1412 roles |= {entity_id: key for key, entity_id in self.entity_ids.items()} 

1413 if self.fallback_cycle_entity_id: 

1414 roles[self.fallback_cycle_entity_id] = f"fallback_{CYCLE_KEY}" 

1415 if self.cycle_entity_id: 

1416 roles[self.cycle_entity_id] = CYCLE_KEY 

1417 return roles 

1418 

1419 def _worth_keeping(self) -> bool: 

1420 return super()._worth_keeping() or self.over_by_stage or self.starting 

1421 

1422 def _temperatures(self) -> tuple[float, float] | None: 

1423 """How hot the oven is and how hot it's to be, where both are known""" 

1424 current, target = self._number(CAVITY_TEMPERATURE_KEY), self._number(TARGET_TEMPERATURE_KEY) 

1425 return None if current is None or target is None or target <= 0 else (current, target) 

1426 

1427 def _preheating(self) -> tuple[float, float] | None: 

1428 """The temperatures of an oven still on its way up to heat, whatever program it's on""" 

1429 temperatures = None if self.preheated or not self.running else self._temperatures() 

1430 return None if temperatures is None or temperatures[0] >= temperatures[1] else temperatures 

1431 

1432 def _progress(self) -> int | None: 

1433 temperatures = self._preheating() 

1434 if temperatures is None: 

1435 return super()._progress() 

1436 # an oven without a timer set has no progress to speak of, so the bar is how near it is to its temperature 

1437 return max(0, int(temperatures[0] * 100 / temperatures[1])) 

1438 

1439 def _preheat_message(self) -> str | None: 

1440 temperatures = self._preheating() 

1441 if temperatures is None: 

1442 return None 

1443 # a button on the oven for more of its elements to be used, which goes off by itself 

1444 fast = self._state(FAST_PREHEAT_KEY) 

1445 texts = self._texts 

1446 phase = texts[TEXT_FAST_PREHEAT] if fast is not None and fast.state == STATE_ON else texts[TEXT_PREHEAT] 

1447 return texts[TEXT_PREHEATING].format( 

1448 phase=phase, current=f"{temperatures[0]:g}", target=f"{temperatures[1]:g}", unit=self._temperature_unit() 

1449 ) 

1450 

1451 def _temperature_unit(self) -> str: 

1452 cavity = self._state(CAVITY_TEMPERATURE_KEY) 

1453 return cavity.attributes.get(ATTR_UNIT_OF_MEASUREMENT, "°") if cavity is not None else "°" 

1454 

1455 def _progress_message(self, progress: int) -> str: 

1456 return self._preheat_message() or super()._progress_message(progress) 

1457 

1458 def _stage(self) -> str | None: 

1459 """Warming up, as the phase, Home Connect reporting none of its own""" 

1460 return self._preheat_message() or super()._stage() 

1461 

1462 def _details(self) -> list[str]: 

1463 """With how hot it is once it's up to heat, after the last of what's shown""" 

1464 details, current = super()._details(), self._number(CAVITY_TEMPERATURE_KEY) 

1465 if not details or current is None or self._preheat_message() is not None: 

1466 return details 

1467 details[-1] = OVEN_MESSAGE.format(program=details[-1], current=f"{current:g}", unit=self._temperature_unit()) 

1468 return details 

1469 

1470 async def _temperature_changed(self, event: Event[EventStateChangedData]) -> None: 

1471 if not self.running: 

1472 return 

1473 if self.preheated: 

1474 await self._temperature_shown(event.context) 

1475 return 

1476 temperatures = self._temperatures() 

1477 if temperatures is None: 

1478 return 

1479 if temperatures[0] < temperatures[1]: 

1480 if not self.preheating: 

1481 # whatever progress has been shown till now wasn't of this 

1482 self.preheating = True 

1483 self.last_progress_mark = -1 

1484 await self._progress_changed(event) 

1485 elif self.preheating: 

1486 await self._preheated(event.context) 

1487 else: 

1488 # already hot when it was switched on 

1489 self.preheated = True 

1490 self._save() 

1491 

1492 async def _preheat_finished(self, event: Event[EventStateChangedData]) -> None: 

1493 new_state = event.data["new_state"] 

1494 # only as it happens, since the sensor may still be telling of the last time the oven was heated 

1495 if self.running and not self.preheated and new_state is not None and new_state.state in STATES_EVENT_ON: 

1496 self._forget_preheated() 

1497 self._cancel_preheated = async_call_later(self.hass, PREHEAT_SETTLE, partial(self._preheat_settled, event.context)) 

1498 

1499 async def _preheat_settled(self, context: Context, now: datetime) -> None: 

1500 self._cancel_preheated = None 

1501 if self.running and not self.preheated and self._cancel_end is None: 

1502 await self._preheated(_later(context)) 

1503 

1504 @callback 

1505 def _forget_preheated(self) -> None: 

1506 if self._cancel_preheated is not None: 

1507 self._cancel_preheated() 

1508 self._cancel_preheated = None 

1509 

1510 async def _temperature_shown(self, context: Context, always: bool = False) -> None: 

1511 """Keep the Live Activity of an oven up to heat to its temperature, give or take a few degrees""" 

1512 current = self._number(CAVITY_TEMPERATURE_KEY) 

1513 shown = self.shown_temperature 

1514 if not always and (current is None or (shown is not None and abs(current - shown) < TEMPERATURE_STEP)): 

1515 return 

1516 self.shown_temperature = current 

1517 async with self._sending: 

1518 if self.running and (message := self._phase()): 

1519 await self._tell(message, False, context) 

1520 

1521 async def _preheated(self, context: Context) -> None: 

1522 """The oven is up to heat, and however its temperature then wanders isn't warming up again till it's been off""" 

1523 self.preheated = True 

1524 self.preheating = False 

1525 self._save() 

1526 # back to the progress of the program, for an oven with a timer set 

1527 progress = self._progress() 

1528 self.last_progress_mark = -1 if progress is None else self._mark(progress) 

1529 message = self._texts[TEXT_PREHEATED].replace(NAME_PLACEHOLDER, self.name) 

1530 title = self._text(CONF_START_TITLE, DEFAULT_TITLE) 

1531 async with self._sending: 

1532 if not self.running or not self.notify_phase: 

1533 pass 

1534 elif supernotify_available(self.hass): 

1535 # a notification of its own, so that it isn't lost as the Live Activity moves on 

1536 await self._supernotify( 

1537 message, 

1538 title, 

1539 context, 

1540 resend=True, 

1541 extra_data={"notification_icon": self.icon}, 

1542 actions=self._tap_actions(), 

1543 ) 

1544 else: 

1545 await self._send_message(message, title, context) 

1546 # which goes straight on to what the oven is now doing 

1547 await self._temperature_shown(context, always=True) 

1548 

1549 async def _cycle_changed(self, event: Event[EventStateChangedData]) -> None: 

1550 new_state = event.data["new_state"] 

1551 if new_state is None: 

1552 return 

1553 if new_state.entity_id != self.cycle_entity_id and self._known(self.cycle_entity_id): 

1554 # the other integration for the same appliance, while this one can be heard from, is only an echo 

1555 return 

1556 state: str = new_state.state 

1557 _LOGGER.debug("APPLIANCES %s cycle state %s, running: %s", self.name, state, self.running) 

1558 old_state = event.data["old_state"] 

1559 if old_state is not None and old_state.state == state: 

1560 # only its attributes changed, and a cycle over by its stage may still be running till it stops 

1561 return 

1562 if state in (STATE_UNKNOWN, STATE_UNAVAILABLE) and new_state.entity_id == self.cycle_entity_id: 

1563 # can't be heard from, so the other integration for the appliance may already have told of its end 

1564 await self._fallback_over(event.context) 

1565 return 

1566 await self._cycle_is(self._cycle_value(new_state) or state, event.context) 

1567 

1568 async def _cycle_is(self, state: str, context: Context) -> None: 

1569 if state in (*STATES_FINISHED, *STATES_SETTLING, *STATES_ABANDONED) and self.over_by_stage: 

1570 self.over_by_stage = False 

1571 self._save() 

1572 if state in STATES_RUN and self.over_by_stage: 

1573 # still running after its stage said it was over, a dryer carrying on as it is, door opened or not 

1574 return 

1575 if state in STATES_RUN: 

1576 # back on within moments of going off, so the same cycle 

1577 self._keep_running() 

1578 self._save() 

1579 if self.running: 

1580 # carrying on, from paused perhaps 

1581 await self._tell_state(context) 

1582 if self.running or self.starting: 

1583 return 

1584 # a moment for the program and stage, which may come just after, to be what's told 

1585 self.starting = True 

1586 self._save() 

1587 try: 

1588 await asyncio.sleep(START_SETTLE) 

1589 finally: 

1590 self.starting = False 

1591 cycle = self._cycle_state() 

1592 if self.running or self._cycle_value(cycle) not in STATES_ACTIVE: 

1593 # over, or started by another report, while it waited 

1594 self._save() 

1595 return 

1596 self.running = True 

1597 # unless it's hot already, from not long having been off 

1598 temperatures = self._temperatures() 

1599 self.preheated = temperatures is not None and temperatures[0] >= temperatures[1] 

1600 self.preheating = self._preheating() is not None 

1601 self.shown_temperature = None 

1602 # with no progress yet to open the Live Activity with, the first reading is sent whatever it is, and 

1603 # an oven already warm starts part of the way along 

1604 progress = self._progress() 

1605 self.last_progress_mark = -1 if progress is None else self._mark(progress) 

1606 await self._started(context) 

1607 elif not self.running: 

1608 return 

1609 elif state in STATES_ACTIVE: 

1610 # paused, or waiting for something to be done, still the same cycle 

1611 await self._tell_state(context) 

1612 elif state in STATES_SETTLING: 

1613 if self._cancel_end is None: 

1614 self._end_at(dt_util.utcnow() + timedelta(seconds=CYCLE_SETTLE), self._settled, context) 

1615 self._save() 

1616 elif state in STATES_FINISHED: 

1617 await self._cycle_over(True, context) 

1618 elif state in STATES_ABANDONED: 

1619 await self._cycle_over(False, context) 

1620 # anything else, such as `unavailable` while the vendor cloud is away, leaves the cycle as it was 

1621 

1622 async def _fallback_over(self, context: Context) -> None: 

1623 """The end of the cycle, if that's what the other integration for the appliance last said, since it went 

1624 unheard while this one could be heard from. A start isn't taken from it, the cloud often lagging behind""" 

1625 if not self.running: 

1626 return 

1627 stage = self._known(self.fallback_ids.get(STAGE_KEY)) 

1628 if stage is not None and stage.state in STAGES_FINISHED: 

1629 await self._over_by_stage(context) 

1630 return 

1631 cycle = self._known(self.fallback_cycle_entity_id) 

1632 value = self._cycle_value(cycle) 

1633 if value in (*STATES_FINISHED, *STATES_SETTLING, *STATES_ABANDONED): 

1634 await self._cycle_is(value, context) 

1635 

1636 async def _stage_changed(self, event: Event[EventStateChangedData]) -> None: 

1637 """The appliance moving on within its cycle, such as a dryer from drying to cooling""" 

1638 new_state = event.data["new_state"] 

1639 if not self.running or new_state is None or new_state.state in (STATE_UNKNOWN, STATE_UNAVAILABLE): 

1640 return 

1641 if new_state.entity_id != self.entity_ids.get(STAGE_KEY) and self._known(self.cycle_entity_id): 

1642 # the other integration for the same appliance, while this one can be heard from, is only an echo 

1643 return 

1644 if new_state.entity_id in self._cycle_profiles and self._cycle_value(new_state) not in STATES_RUN: 

1645 # a cycle state that's its stage too, which says no more than the cycle state once it isn't running 

1646 return 

1647 if new_state.state in STAGES_FINISHED: 

1648 await self._over_by_stage(event.context) 

1649 return 

1650 if not supernotify_available(self.hass): 

1651 return 

1652 async with self._sending: 

1653 if self.running and (message := self._phase()): 

1654 await self._tell(message, False, event.context) 

1655 

1656 async def _over_by_stage(self, context: Context) -> None: 

1657 # done, though it may carry on as it is a while, a dryer tumbling its load now and then 

1658 cycle = self._cycle_state() 

1659 self.over_by_stage = self._cycle_value(cycle) in STATES_ACTIVE 

1660 await self._cycle_over(True, context) 

1661 

1662 async def _settled(self, context: Context, now: datetime) -> None: 

1663 self._end_waited() 

1664 await self._cycle_over(True, _later(context)) 

1665 

1666 async def _cycle_over(self, finished: bool, context: Context) -> None: 

1667 self._keep_running() 

1668 self._forget_preheated() 

1669 self.running = False 

1670 await self._ended(finished, context) 

1671 

1672 

1673class PowerWatcher(ApplianceWatcher): 

1674 """An appliance known only by the power it draws, running while that is above a threshold""" 

1675 

1676 def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None: 

1677 super().__init__(hass, entry) 

1678 self.power_entity_id: str = entry.options[CONF_POWER_ENTITY] 

1679 self.threshold: float = entry.options.get(CONF_THRESHOLD, DEFAULT_THRESHOLD) 

1680 self.grace_period: float = entry.options.get(CONF_GRACE_PERIOD, DEFAULT_GRACE_PERIOD) 

1681 self.min_duration: float = entry.options.get(CONF_MIN_DURATION, DEFAULT_MIN_DURATION) 

1682 if entry.options.get(CONF_SWITCH_OFF_BUTTON, True): 

1683 self.switch_entity_id = entry.options.get(CONF_SWITCH_ENTITY) 

1684 # power drawn, but not yet for long enough to count as a cycle 

1685 self.pending: bool = False 

1686 self._drawn_for: float = 0 

1687 self._drawing_since: datetime | None = None 

1688 self._cancel_end: CALLBACK_TYPE | None = None 

1689 self._cancel_start: CALLBACK_TYPE | None = None 

1690 

1691 @callback 

1692 def async_start(self) -> None: 

1693 state = self.hass.states.get(self.power_entity_id) 

1694 drawing = self._drawing(state) 

1695 # a cycle under way at startup still has its Live Activity closed when it ends 

1696 self.running = drawing is True 

1697 if state is None and er.async_get(self.hass).async_get(self.power_entity_id) is None: 

1698 # the power monitor is gone, so there's nothing to carry on with 

1699 self._restored = {} 

1700 phase: dict[str, Any] = self._restored.get("phase") or {} 

1701 if self._restore(): 

1702 # still the cycle under way before Home Assistant restarted, though it may have stopped since 

1703 self.running = True 

1704 self._end_due = _time(self._restored.get("end_due")) 

1705 elif phase.get("pending"): 

1706 # not yet long enough to count as a cycle, with the time above the threshold counted through the restart 

1707 # if it was drawing power all along, and otherwise only up to when it was last seen to 

1708 self.pending = True 

1709 self._drawn_for = float(phase.get("drawn_for") or 0) 

1710 self._end_due = _time(self._restored.get("end_due")) 

1711 if drawing is True: 

1712 self._drawing_since = _time(phase.get("drawing_since")) or dt_util.utcnow() 

1713 self.entry.async_on_unload(async_track_state_change_event(self.hass, self.power_entity_id, self._power_changed)) 

1714 self.entry.async_on_unload(self._keep_running) 

1715 self.entry.async_on_unload(self._stop_counting) 

1716 if drawing is True: 

1717 # drawing power again, the same cycle or one not yet long enough to count, so with no end to wait for 

1718 self._end_due = None 

1719 self.cycle_stopped = None 

1720 if self.pending: 

1721 self._count(Context()) 

1722 elif drawing is False and (self.running or self.pending): 

1723 # at rest, so the end waited for before the restart, or one from now if it stopped while Home Assistant 

1724 # was off, is due unless it draws power again first 

1725 if self._end_due is None and self.cycle_stopped is None: 

1726 # stopped while Home Assistant was off, when isn't known, so how long it ran isn't either 

1727 self._stop_unseen = True 

1728 self._end_at(self._end_due or self._grace_end(), self._grace_over, Context()) 

1729 # with the power not yet known, whatever it says first decides, an end waited for being due when it was 

1730 self._save() 

1731 

1732 def _phase_data(self) -> dict[str, Any]: 

1733 return {"pending": self.pending, "drawn_for": self._drawn_for, "drawing_since": _iso(self._drawing_since)} 

1734 

1735 def _worth_keeping(self) -> bool: 

1736 return super()._worth_keeping() or self.pending 

1737 

1738 def _grace_end(self) -> datetime: 

1739 return dt_util.utcnow() + timedelta(seconds=self.grace_period) 

1740 

1741 def _drawing(self, state: State | None) -> bool | None: 

1742 """Whether more power than the threshold is drawn, None if the power isn't known""" 

1743 try: 

1744 power = float(state.state) if state is not None else None 

1745 except ValueError: 

1746 power = None 

1747 if state is None or power is None: 

1748 return None 

1749 unit = state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) 

1750 if unit in PowerConverter.VALID_UNITS: 

1751 power = PowerConverter.convert(power, unit, UnitOfPower.WATT) 

1752 return power > self.threshold 

1753 

1754 async def _power_changed(self, event: Event[EventStateChangedData]) -> None: 

1755 drawing = self._drawing(event.data["new_state"]) 

1756 _LOGGER.debug( 

1757 "APPLIANCES %s drawing power %s, running: %s, pending: %s", self.name, drawing, self.running, self.pending 

1758 ) 

1759 if drawing is None: 

1760 # `unavailable` while the power monitor is away leaves the cycle as it was 

1761 return 

1762 if drawing: 

1763 self._keep_running() 

1764 if not self.running: 

1765 if not self.pending: 

1766 self.pending = True 

1767 self._drawn_for = 0 

1768 # the cycle began as it first drew power, not once it had for long enough to count 

1769 self._cycle_began() 

1770 if self._drawing_since is None: 

1771 # time above the threshold adds up across drop outs, so one in the first minute doesn't start it over 

1772 self._drawing_since = dt_util.utcnow() 

1773 if self.min_duration - self._drawn_for > 0: 

1774 self._count(event.context) 

1775 else: 

1776 await self._confirmed(event.context) 

1777 elif self.running or self.pending: 

1778 self._stop_counting() 

1779 if self._cancel_end is None: 

1780 if self._end_due is None: 

1781 # stopped now, unless it had before a restart, when that was kept 

1782 self.cycle_stopped = dt_util.utcnow() 

1783 # from when it was due before a restart, if it went unseen from then till now 

1784 self._end_at(self._end_due or self._grace_end(), self._grace_over, event.context) 

1785 self._save() 

1786 

1787 @callback 

1788 def _count(self, context: Context) -> None: 

1789 """Wait for the time above the threshold to be long enough for a cycle""" 

1790 drawing_for = (dt_util.utcnow() - self._drawing_since).total_seconds() if self._drawing_since else 0 

1791 remaining = self.min_duration - self._drawn_for - drawing_for 

1792 self._cancel_start = async_call_later(self.hass, max(0.0, remaining), partial(self._long_enough, context)) 

1793 

1794 @callback 

1795 def _keep_running(self) -> None: 

1796 self.cycle_stopped = None 

1797 self._stop_unseen = False 

1798 self._end_due = None 

1799 if self._cancel_end is not None: 

1800 self._cancel_end() 

1801 self._cancel_end = None 

1802 

1803 def _health_entity_ids(self) -> list[str]: 

1804 """Its power sensor, which goes unavailable with the smart plug""" 

1805 return [self.power_entity_id] 

1806 

1807 def _totals_device_id(self) -> str | None: 

1808 """The smart plug's device, whose energy meter tells what a cycle used""" 

1809 entity = er.async_get(self.hass).async_get(self.power_entity_id) 

1810 return entity.device_id if entity is not None else None 

1811 

1812 @callback 

1813 def _stop_counting(self) -> None: 

1814 """Add up the time above the threshold so far, while it isn't yet a cycle""" 

1815 if self._drawing_since is not None: 

1816 self._drawn_for += (dt_util.utcnow() - self._drawing_since).total_seconds() 

1817 self._drawing_since = None 

1818 if self._cancel_start is not None: 

1819 self._cancel_start() 

1820 self._cancel_start = None 

1821 

1822 async def _long_enough(self, context: Context, now: datetime) -> None: 

1823 self._cancel_start = None 

1824 await self._confirmed(_later(context)) 

1825 

1826 async def _confirmed(self, context: Context) -> None: 

1827 self.pending = False 

1828 self._drawing_since = None 

1829 self.running = True 

1830 await self._started(context) 

1831 

1832 async def _grace_over(self, context: Context, now: datetime) -> None: 

1833 self._end_waited() 

1834 if self.pending: 

1835 _LOGGER.debug("APPLIANCES %s drew power for %.0fs, too short for a cycle", self.name, self._drawn_for) 

1836 self.pending = False 

1837 self._drawn_for = 0 

1838 self._cycle_forgotten() 

1839 self._save() 

1840 return 

1841 self.running = False 

1842 await self._ended(True, _later(context)) 

1843 

1844 

1845class VacuumWatcher(ApplianceWatcher): 

1846 """A robot vacuum of any make, whose cleaning is the cycle, from setting off till it's back or stopped by itself""" 

1847 

1848 def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None: 

1849 super().__init__(hass, entry) 

1850 self._cancel_end: CALLBACK_TYPE | None = None 

1851 # what it's waiting to see last, back on its dock or stuck 

1852 self._pending: str | tuple[str, ...] | None = None 

1853 # not yet known whether it was cleaning when Home Assistant started, until it says something telling 

1854 self._unsure = False 

1855 # how long it stays back on its dock before its cleaning is over, where its own progress doesn't say 

1856 self.settle: float = entry.options.get(CONF_GRACE_PERIOD, VACUUM_SETTLE) 

1857 # a percentage on the vacuum, other than its battery, has climbed to 100 during this cleaning, as its progress 

1858 # does where its integration reports one, which a consumable's life left never does, or its own running sensor 

1859 # has gone off 

1860 self._complete = False 

1861 # a running sensor of the vacuum's that came on as it set off and is on still, so its cleaning isn't over 

1862 self._job: str | None = None 

1863 self._runnings: list[str] = [] 

1864 self._set_off: datetime | None = None 

1865 # its progress has dropped below 100 since it set off, so isn't what the cleaning before left 

1866 self._progressing = False 

1867 # the last number each of its percentages gave, to go by when one comes back from being unavailable, as 

1868 # Roborock's do whenever its cloud connection drops, which can be just as the vacuum heads back at 100 

1869 self._percents: dict[str, float] = {} 

1870 

1871 @callback 

1872 def async_start(self) -> None: 

1873 device_id: str = self.entry.data[CONF_DEVICE_ID] 

1874 device = dr.async_get(self.hass).async_get(device_id) 

1875 if device is not None: 

1876 self.name = device.name_by_user or device.name or self.name 

1877 self.cycle_entity_id = next( 

1878 (e.entity_id for e in er.async_entries_for_device(er.async_get(self.hass), device_id) if e.domain == TYPE_VACUUM), 

1879 None, 

1880 ) 

1881 if self.cycle_entity_id is None: 

1882 raise ConfigEntryNotReady( 

1883 translation_domain=DOMAIN, translation_key="no_vacuum_entity", translation_placeholders={"name": self.name} 

1884 ) 

1885 vacuum = er.async_get(self.hass).async_get(self.cycle_entity_id) 

1886 self.profile = profile_for(vacuum.platform if vacuum is not None else None) 

1887 self.appliance_type = "cleaning_robot" 

1888 self.icon = TYPE_ICONS[self.appliance_type] 

1889 # a cleaning under way at startup still has its Live Activity closed when it ends 

1890 state = self.hass.states.get(self.cycle_entity_id) 

1891 self.running = state is not None and state.state not in (*VACUUM_DONE, VACUUM_ERROR, STATE_UNAVAILABLE, STATE_UNKNOWN) 

1892 # with nothing to go by yet, or an error that some integrations report again on reconnecting, whatever it says 

1893 # next tells whether a cleaning was under way 

1894 self._unsure = state is None or state.state in (VACUUM_ERROR, STATE_UNAVAILABLE, STATE_UNKNOWN) 

1895 self.entry.async_on_unload(async_track_state_change_event(self.hass, self.cycle_entity_id, self._activity_changed)) 

1896 entities = er.async_entries_for_device(er.async_get(self.hass), device_id) 

1897 percentages = [ 

1898 e.entity_id 

1899 for e in entities 

1900 if e.domain == "sensor" 

1901 and e.unit_of_measurement == PERCENTAGE 

1902 and (e.device_class or e.original_device_class) != SensorDeviceClass.BATTERY 

1903 ] 

1904 if percentages: 

1905 self.entry.async_on_unload(async_track_state_change_event(self.hass, percentages, self._percentage_changed)) 

1906 self._runnings = [ 

1907 e.entity_id 

1908 for e in entities 

1909 if e.domain == "binary_sensor" and (e.device_class or e.original_device_class) == BinarySensorDeviceClass.RUNNING 

1910 ] 

1911 if self._runnings: 

1912 self.entry.async_on_unload(async_track_state_change_event(self.hass, self._runnings, self._running_changed)) 

1913 if self.running: 

1914 self._job = self._running_now(None) 

1915 # its status, cleaning mode and progress as its integration names them, where it's known to, or else as 

1916 # Roborock does, from any entity the integration isn't known to use for something else, as Miele's status is 

1917 own = self.profile.role_keys 

1918 for entity in entities: 

1919 role = own.get(entity.translation_key or "") 

1920 if ( 

1921 role in (STAGE_KEY, *PROGRAM_KEYS, PROGRESS_KEY) 

1922 and not entity.disabled 

1923 and entity.domain in ENTITY_DOMAINS.get(role or "", ()) 

1924 ): 

1925 self.entity_ids.setdefault(role or "", entity.entity_id) 

1926 for key, domain, keys in ( 

1927 (STAGE_KEY, "sensor", VACUUM_STATUS_KEYS), 

1928 (PROGRAM_KEYS[-1], "select", VACUUM_PROGRAM_KEYS), 

1929 (PROGRESS_KEY, "sensor", VACUUM_PROGRESS_KEYS), 

1930 ): 

1931 if any(k in self.entity_ids for k in (PROGRAM_KEYS if key in PROGRAM_KEYS else (key,))): 

1932 continue 

1933 if found := next( 

1934 ( 

1935 e.entity_id 

1936 for e in entities 

1937 if e.domain == domain and not e.disabled and e.translation_key in keys and e.translation_key not in own 

1938 ), 

1939 None, 

1940 ): 

1941 self.entity_ids[key] = found 

1942 if STAGE_KEY in self.entity_ids: 

1943 self.entry.async_on_unload( 

1944 async_track_state_change_event(self.hass, self.entity_ids[STAGE_KEY], self._status_changed) 

1945 ) 

1946 self.entry.async_on_unload(self._keep_running) 

1947 if self._restore(): 

1948 self._resume(state) 

1949 if self.running: 

1950 # cleaning since before Home Assistant started, with whatever progress it has 

1951 self._progressing = (progress := self._number(PROGRESS_KEY)) is not None and progress < 100 

1952 self._save() 

1953 

1954 @callback 

1955 def _resume(self, state: State | None) -> None: 

1956 """Carry on with the cleaning under way before Home Assistant restarted, without telling of it as started, and 

1957 with whatever end it was waiting for, unless it has set off again since""" 

1958 self.running = True 

1959 self._unsure = False 

1960 phase: dict[str, Any] = self._restored.get("phase") or {} 

1961 self._complete = bool(phase.get("complete")) 

1962 self._set_off = _time(phase.get("set_off")) 

1963 self._job = phase.get("job") if phase.get("job") in self._runnings else None 

1964 job = self._known(self._job) 

1965 if job is not None and job.state != STATE_ON: 

1966 # done by its own account while Home Assistant was off 

1967 self._job = None 

1968 self._complete = True 

1969 waiting = phase.get("waiting") 

1970 kind = tuple(waiting) if isinstance(waiting, list) else waiting 

1971 due = _time(self._restored.get("end_due")) 

1972 activity = state.state if state is not None else None 

1973 context = Context() 

1974 if kind is not None and due is not None and self._still_waiting(kind, activity): 

1975 self._wait_till(self._stuck_for_good if kind == VACUUM_ERROR else self._settled, kind, context, due) 

1976 elif activity == VACUUM_ERROR: 

1977 self._wait(self._stuck_for_good, VACUUM_ERROR, context) 

1978 elif activity in VACUUM_DONE: 

1979 # back on its dock while Home Assistant was off, with no knowing how it went back 

1980 if self._job is not None: 

1981 self._wait(self._settled, VACUUM_HELD_KIND, context, VACUUM_HELD_SETTLE) 

1982 elif self._complete: 

1983 self._wait(self._settled, VACUUM_COMPLETE_KIND, context, VACUUM_COMPLETE_SETTLE) 

1984 else: 

1985 self._wait(self._settled, VACUUM_DONE, context, self.settle) 

1986 # cleaning, paused or on its way back is the same cleaning, with nothing yet to wait for 

1987 kept = _time((self._restored.get("totals") or {}).get("stopped")) 

1988 if self._pending is not None and kept is not None: 

1989 # back from before Home Assistant restarted, not only as it started again 

1990 self.cycle_stopped = kept 

1991 

1992 @staticmethod 

1993 def _still_waiting(kind: str | tuple[str, ...], activity: str | None) -> bool: 

1994 """Whether the vacuum is where it was while waiting for the end, or not yet heard from, as it would be if 

1995 Home Assistant hadn't restarted""" 

1996 if activity in (None, STATE_UNAVAILABLE, STATE_UNKNOWN): 

1997 return True 

1998 if kind == VACUUM_ERROR: 

1999 return activity == VACUUM_ERROR 

2000 # an error back on its dock is for its own app to tell, and paused there isn't setting off again 

2001 return activity in (*VACUUM_DONE, VACUUM_ERROR) or (activity == VACUUM_PAUSED and kind != VACUUM_BLIP_KIND) 

2002 

2003 def _phase_data(self) -> dict[str, Any]: 

2004 return {"waiting": self._pending, "complete": self._complete, "job": self._job, "set_off": _iso(self._set_off)} 

2005 

2006 def _state_shown(self) -> str | None: 

2007 """What it's doing other than cleaning, such as on its way back to its dock, which a vacuum with no status of 

2008 its own has no other way of saying""" 

2009 state = self._cycle_state() 

2010 if state is None or state.state not in (VACUUM_PAUSED, VACUUM_RETURNING): 

2011 return None 

2012 return self._translated(state) 

2013 

2014 async def _status_changed(self, event: Event[EventStateChangedData]) -> None: 

2015 """The vacuum moving on within its cleaning, such as from sweeping to relocating""" 

2016 new_state = event.data["new_state"] 

2017 if not self.running or new_state is None or new_state.state in (STATE_UNKNOWN, STATE_UNAVAILABLE): 

2018 return 

2019 await self._tell_status(event.context) 

2020 

2021 async def _tell_status(self, context: Context) -> None: 

2022 if not supernotify_available(self.hass): 

2023 return 

2024 async with self._sending: 

2025 if self.running and (message := self._phase()): 

2026 # resent, since it often goes back to what it said before, sweeping again after relocating 

2027 await self._tell(message, False, context, resend=True) 

2028 

2029 def _running_now(self, since: datetime | None) -> str | None: 

2030 """Whichever of its running sensors is on as it sets off, having come on with it where that's known""" 

2031 for entity_id in self._runnings: 

2032 state = self.hass.states.get(entity_id) 

2033 if ( 

2034 state is not None 

2035 and state.state == STATE_ON 

2036 and (since is None or (since - state.last_changed).total_seconds() <= VACUUM_JOB_LEAD) 

2037 ): 

2038 return entity_id 

2039 return None 

2040 

2041 async def _running_changed(self, event: Event[EventStateChangedData]) -> None: 

2042 new_state = event.data["new_state"] 

2043 if not self.running or new_state is None or new_state.state in (STATE_UNAVAILABLE, STATE_UNKNOWN): 

2044 return 

2045 entity_id = event.data["entity_id"] 

2046 if new_state.state == STATE_ON: 

2047 if ( 

2048 self._job is None 

2049 and self._set_off is not None 

2050 and (new_state.last_changed - self._set_off).total_seconds() <= VACUUM_JOB_LEAD 

2051 ): 

2052 self._job = entity_id 

2053 self._save() 

2054 return 

2055 if entity_id != self._job: 

2056 return 

2057 _LOGGER.debug("APPLIANCES %s vacuum %s went off", self.name, entity_id) 

2058 self._job = None 

2059 self._complete = True 

2060 activity = self._known(self.cycle_entity_id) 

2061 if activity is not None and activity.state in VACUUM_DONE: 

2062 # already back, and now done by its own account 

2063 self._wait(self._settled, VACUUM_COMPLETE_KIND, event.context, VACUUM_COMPLETE_SETTLE) 

2064 self._save() 

2065 

2066 async def _percentage_changed(self, event: Event[EventStateChangedData]) -> None: 

2067 new_state, old_state = event.data["new_state"], event.data["old_state"] 

2068 entity_id = event.data["entity_id"] 

2069 value = _float(new_state) 

2070 if value is None: 

2071 # unavailable for now, which changes nothing 

2072 return 

2073 # what it was before going unavailable, if it did, so a 100 that comes back with it still counts 

2074 before = _float(old_state) 

2075 before = self._percents.get(entity_id) if before is None else before 

2076 self._percents[entity_id] = value 

2077 if not self.running: 

2078 return 

2079 if value < 100: 

2080 self._complete = False 

2081 if entity_id == self.entity_ids.get(PROGRESS_KEY): 

2082 self._progressing = True 

2083 elif before is not None and before < 100 and not self._complete: 

2084 _LOGGER.debug("APPLIANCES %s vacuum %s reached 100%%", self.name, entity_id) 

2085 self._complete = True 

2086 if self._pending in (VACUUM_DONE, VACUUM_MIDWAY_KIND): 

2087 # already back, and now done by its own account 

2088 self._wait(self._settled, VACUUM_COMPLETE_KIND, event.context, VACUUM_COMPLETE_SETTLE) 

2089 self._save() 

2090 if entity_id == self.entity_ids.get(PROGRESS_KEY): 

2091 await self._progress_changed(event) 

2092 

2093 def _progress(self) -> int | None: 

2094 """Its progress, once it's no longer the 100 the cleaning before left""" 

2095 return super()._progress() if self._progressing else None 

2096 

2097 @callback 

2098 def _keep_running(self) -> None: 

2099 self._pending = None 

2100 self.cycle_stopped = None 

2101 self._end_due = None 

2102 if self._cancel_end is not None: 

2103 self._cancel_end() 

2104 self._cancel_end = None 

2105 

2106 def _traced_roles(self) -> dict[str, str]: 

2107 roles = {entity_id: key for key, entity_id in self.entity_ids.items()} 

2108 roles |= dict.fromkeys(self._runnings, "running") 

2109 if self.cycle_entity_id: 

2110 roles[self.cycle_entity_id] = TYPE_VACUUM 

2111 return roles 

2112 

2113 async def _activity_changed(self, event: Event[EventStateChangedData]) -> None: 

2114 new_state = event.data["new_state"] 

2115 if new_state is None: 

2116 return 

2117 state: str = new_state.state 

2118 _LOGGER.debug("APPLIANCES %s vacuum %s, running: %s", self.name, state, self.running) 

2119 if state in (STATE_UNAVAILABLE, STATE_UNKNOWN): 

2120 # away with the vendor cloud, which changes nothing 

2121 return 

2122 if self._unsure and state != VACUUM_ERROR: 

2123 self._unsure = False 

2124 if not self.running and state in (VACUUM_CLEANING, VACUUM_PAUSED, VACUUM_RETURNING): 

2125 # cleaning since before Home Assistant started, so already told, and its end still to tell 

2126 self.running = True 

2127 self._job = self._running_now(None) 

2128 self._save() 

2129 return 

2130 if not self.running: 

2131 if state == VACUUM_CLEANING: 

2132 self.running = True 

2133 self._complete = False 

2134 self._progressing = False 

2135 self.last_progress_mark = -1 

2136 self._set_off = new_state.last_changed 

2137 self._job = self._running_now(self._set_off) 

2138 await self._started(event.context) 

2139 # already sweeping, most likely, by the time it's said to be cleaning 

2140 await self._tell_status(event.context) 

2141 return 

2142 old_state = event.data["old_state"] 

2143 if state in VACUUM_DONE: 

2144 if self._job is not None: 

2145 # back, but with its cleaning not over by its own account, as when it recharges to carry on 

2146 if self._pending != VACUUM_HELD_KIND: 

2147 self._wait(self._settled, VACUUM_HELD_KIND, event.context, VACUUM_HELD_SETTLE) 

2148 elif self._complete: 

2149 # back with its cleaning done by its own account, so nothing to set off again for 

2150 if self._pending != VACUUM_COMPLETE_KIND: 

2151 self._wait(self._settled, VACUUM_COMPLETE_KIND, event.context, VACUUM_COMPLETE_SETTLE) 

2152 elif old_state is not None and old_state.state == VACUUM_CLEANING: 

2153 if (new_state.last_changed - old_state.last_changed).total_seconds() < VACUUM_BLIP: 

2154 # back within a moment of setting off, which some integrations report as a vacuum leaves its dock 

2155 # and then keep to while it cleans, so only believed if nothing more is heard for a long while 

2156 if self._pending is None: 

2157 self._wait(self._settled, VACUUM_BLIP_KIND, event.context, VACUUM_BLIP_SETTLE) 

2158 elif self._pending not in (VACUUM_DONE, VACUUM_MIDWAY_KIND): 

2159 # straight back from cleaning, without saying it was on its way, as when it washes its mop or 

2160 # fills its tank part way through, so given longer to set off again 

2161 self._wait(self._settled, VACUUM_MIDWAY_KIND, event.context, VACUUM_MIDWAY_SETTLE) 

2162 elif self._pending not in (VACUUM_DONE, VACUUM_MIDWAY_KIND): 

2163 # over only once it has stayed back 

2164 self._wait(self._settled, VACUUM_DONE, event.context, self.settle) 

2165 elif state == VACUUM_ERROR: 

2166 # stuck only if it stays so, since some integrations report a past error again on reconnecting, while 

2167 # the vacuum carries on, and an error once back on its dock is for its own app to tell 

2168 if self._pending is None: 

2169 self._wait(self._stuck_for_good, VACUUM_ERROR, event.context) 

2170 elif state == VACUUM_PAUSED and self._pending in ( 

2171 VACUUM_DONE, 

2172 VACUUM_MIDWAY_KIND, 

2173 VACUUM_COMPLETE_KIND, 

2174 VACUUM_HELD_KIND, 

2175 ): 

2176 # paused on its dock, which some integrations report once one is back, isn't setting off again 

2177 return 

2178 else: 

2179 # cleaning, paused or on its way back is the same cleaning 

2180 self._keep_running() 

2181 self._save() 

2182 await self._tell_state(event.context) 

2183 

2184 @callback 

2185 def _wait( 

2186 self, 

2187 then: Callable[[Context, datetime], Coroutine[Any, Any, None]], 

2188 kind: str | tuple[str, ...], 

2189 context: Context, 

2190 delay: float = VACUUM_SETTLE, 

2191 ) -> None: 

2192 self._wait_till(then, kind, context, dt_util.utcnow() + timedelta(seconds=delay)) 

2193 

2194 @callback 

2195 def _wait_till( 

2196 self, 

2197 then: Callable[[Context, datetime], Coroutine[Any, Any, None]], 

2198 kind: str | tuple[str, ...], 

2199 context: Context, 

2200 due: datetime, 

2201 ) -> None: 

2202 self._keep_running() 

2203 self._pending = kind 

2204 # back, or stuck, from now on unless it carries on 

2205 self.cycle_stopped = dt_util.utcnow() 

2206 self._end_at(due, then, context) 

2207 self._save() 

2208 

2209 async def _settled(self, context: Context, now: datetime) -> None: 

2210 self._end_waited() 

2211 self._pending = None 

2212 self.running = False 

2213 await self._ended(True, _later(context)) 

2214 

2215 async def _stuck_for_good(self, context: Context, now: datetime) -> None: 

2216 # stopped where it is, so no end to tell, only that it can't go on without someone 

2217 self._end_waited() 

2218 self._pending = None 

2219 self.running = False 

2220 await self._ended(False, _later(context)) 

2221 await self._stuck(_later(context)) 

2222 

2223 async def _stuck(self, context: Context) -> None: 

2224 stuck = STUCK_MESSAGES.get(self.hass.config.language.split("-")[0], STUCK_MESSAGES["en"]) 

2225 message = stuck.replace(NAME_PLACEHOLDER, self.name) 

2226 title = self._text(CONF_START_TITLE, DEFAULT_TITLE) 

2227 async with self._sending: 

2228 if supernotify_available(self.hass): 

2229 await self._supernotify( 

2230 message, 

2231 title, 

2232 context, 

2233 resend=True, 

2234 extra_data={"notification_icon": self.icon}, 

2235 actions=self._tap_actions(), 

2236 ) 

2237 else: 

2238 await self._send_message(message, title, context)