diff --git a/custom_components/supernotify/config_flow.py b/custom_components/supernotify/config_flow.py index 65e88ef54..6fdf3e521 100644 --- a/custom_components/supernotify/config_flow.py +++ b/custom_components/supernotify/config_flow.py @@ -117,6 +117,7 @@ CONF_PRIORITY, CONF_RECIPIENTS_DISCOVERY, CONF_SELECTION, + CONF_SEND_WHEN_IDLE, CONF_SENTENCE_COMMANDS, CONF_SIZE, CONF_SNAPSHOT_URL_LOCAL, @@ -734,9 +735,17 @@ async def async_step_details(self, user_input: dict[str, Any] | None = None) -> else: self._recipient.pop(key, None) selected = user_input.get(CONF_MOBILE_DEVICES, []) - self._recipient[CONF_MOBILE_DEVICES] = [ - {CONF_MOBILE_APP_ID: d["value"], CONF_ENABLED: d["value"] in selected} for d in devices - ] + send_when_idle = user_input.get(CONF_SEND_WHEN_IDLE, []) + # anything else set for a device in YAML, like its in_use_entity, is kept + configured = {d.get(CONF_MOBILE_APP_ID): d for d in self._recipient.get(CONF_MOBILE_DEVICES, [])} + mobile_devices: list[dict[str, Any]] = [] + for d in devices: + device = {k: v for k, v in configured.get(d["value"], {}).items() if k != CONF_SEND_WHEN_IDLE} + device.update({CONF_MOBILE_APP_ID: d["value"], CONF_ENABLED: d["value"] in selected}) + if d["value"] in send_when_idle: + device[CONF_SEND_WHEN_IDLE] = True + mobile_devices.append(device) + self._recipient[CONF_MOBILE_DEVICES] = mobile_devices return await self.async_step_save() selected_target, custom_target = target_to_fields(self._recipient.get(CONF_TARGET)) @@ -750,6 +759,7 @@ async def async_step_details(self, user_input: dict[str, Any] | None = None) -> vol.Optional(CONF_ENABLED, default=True): cv.boolean, vol.Optional(CONF_MOBILE_DISCOVERY, default=True): cv.boolean, vol.Optional(CONF_MOBILE_DEVICES): SelectSelector(SelectSelectorConfig(options=devices, multiple=True)), + vol.Optional(CONF_SEND_WHEN_IDLE): SelectSelector(SelectSelectorConfig(options=devices, multiple=True)), vol.Optional(CONF_TARGET): TargetSelector(), vol.Optional(ATTR_CUSTOM_TARGET): TextSelector(TextSelectorConfig(multiple=True)), vol.Optional(SECTION_DELIVERY_OVERRIDES): section( @@ -764,6 +774,10 @@ async def async_step_details(self, user_input: dict[str, Any] | None = None) -> CONF_ENABLED: self._recipient.get(CONF_ENABLED, True), CONF_MOBILE_DISCOVERY: self._recipient.get(CONF_MOBILE_DISCOVERY, self._mobile_discovery_default()), CONF_MOBILE_DEVICES: [d["value"] for d in devices if d["value"] not in disabled], + CONF_SEND_WHEN_IDLE: [ + d.get(CONF_MOBILE_APP_ID) for d in self._recipient.get(CONF_MOBILE_DEVICES, []) if d.get(CONF_SEND_WHEN_IDLE) + ] + or None, CONF_TARGET: selected_target or None, ATTR_CUSTOM_TARGET: custom_target or None, SECTION_DELIVERY_OVERRIDES: {CONF_DELIVERY: self._recipient.get(CONF_DELIVERY) or None}, diff --git a/custom_components/supernotify/const.py b/custom_components/supernotify/const.py index 509537369..304b45fb2 100644 --- a/custom_components/supernotify/const.py +++ b/custom_components/supernotify/const.py @@ -120,6 +120,8 @@ ATTR_SCENARIOS_REQUIRE = "require_scenarios" ATTR_SCENARIOS_APPLY = "apply_scenarios" ATTR_FORCE_RESEND: Final[str] = "force_resend" +# a standard action-data field, to send to a person's mobile devices even when not in use +ATTR_INCLUDE_IDLE_DEVICES: Final[str] = "include_idle_devices" # a standard action-data field, same as force_resend/debug - Notification.call_transport() is what # actually skips sending for SIMULATE, so nothing else needs to special-case it. An enum, not a # boolean, so a future mode (e.g. SIMULATE_PLUS_MEDIA, also simulating the camera/media grab) can @@ -264,6 +266,14 @@ ATTR_DUPE_POLICY_MT: Final[str] = "dupe_policy_message_title_same" ATTR_DUPE_POLICY_NONE: Final[str] = "dupe_policy_none" CONF_MOBILE_APP_ID: Final[str] = "mobile_app_id" +# binary_sensor saying whether anyone is using a mobile device, found from the Companion app +# or given in its `mobile_devices` entry, and whether to notify it all the same when it's off +CONF_IN_USE_ENTITY: Final[str] = "in_use_entity" +CONF_SEND_WHEN_IDLE: Final[str] = "send_when_idle" +# Companion app sensors that are off when nobody is using the device: macOS `active` (asleep, +# screensaver, locked) and Wear OS `on_body` (watch not worn). Android's `is_interactive` isn't +# one, as a phone in a pocket has its screen off, but can be given as an `in_use_entity` +IN_USE_SENSOR_IDS: Final[tuple[str, ...]] = ("active", "on_body") CONF_TRANSPORT_DATA: Final[str] = "transport_data" diff --git a/custom_components/supernotify/hass_api.py b/custom_components/supernotify/hass_api.py index 5f1e4517a..26cd52ac9 100644 --- a/custom_components/supernotify/hass_api.py +++ b/custom_components/supernotify/hass_api.py @@ -70,7 +70,7 @@ from . import DOMAIN from .common import spoken_name -from .const import CONF_DEVICE_LABELS, CONF_DEVICE_TRACKER, CONF_MOBILE_APP_ID +from .const import CONF_DEVICE_LABELS, CONF_DEVICE_TRACKER, CONF_IN_USE_ENTITY, CONF_MOBILE_APP_ID, IN_USE_SENSOR_IDS from .model import ConditionVariables, SelectionRule if TYPE_CHECKING: @@ -107,6 +107,7 @@ class TrackedDeviceDetails: os_version: str | None = None app_version: str | None = None identifiers: set[tuple[str, str]] | None = None + in_use_entity: str | None = None def as_dict(self) -> dict[str, str | list[str] | None]: return { @@ -122,6 +123,7 @@ def as_dict(self) -> dict[str, str | list[str] | None]: ATTR_MANUFACTURER: self.manufacturer, ATTR_MODEL: self.model, CONF_DEVICE_LABELS: self.device_labels, + CONF_IN_USE_ENTITY: self.in_use_entity, } def __eq__(self, other: object) -> bool: @@ -143,6 +145,17 @@ def has_missing(self) -> bool: return bool(self.missing_areas or self.missing_floors or self.missing_labels) +def companion_sensor_id(unique_id: str | None) -> str | None: + """The sensor's own id in the Companion app, from a `mobile_app` entity's unique id + + mobile_app registers each sensor as `_`, and a webhook id is + hex, so has no underscore of its own + """ + if not unique_id or "_" not in unique_id: + return None + return unique_id.split("_", 1)[1] + + def ha_device_info(entry_id: str) -> dr.DeviceInfo: """Home Assistant device-registry DeviceInfo for the single 'SuperNotify' device. @@ -1018,10 +1031,18 @@ def build_mobile_app_cache(self) -> None: else: _LOGGER.debug("SUPERNOTIFY No notify action <%s>, so not a notifiable mobile app", mobile_app_id) + in_use_entity: str | None = None registry_entries = entity_registry.entities.get_entries_for_device_id(mobile_app_info.device_id) for reg_entry in registry_entries: if reg_entry.platform == "mobile_app" and reg_entry.domain == "device_tracker": device_tracker = reg_entry.entity_id + elif ( + reg_entry.platform == "mobile_app" + and reg_entry.domain == "binary_sensor" + and not reg_entry.disabled_by + and companion_sensor_id(reg_entry.unique_id) in IN_USE_SENSOR_IDS + ): + in_use_entity = reg_entry.entity_id if device_tracker and notify_action: complete += 1 @@ -1029,6 +1050,7 @@ def build_mobile_app_cache(self) -> None: mobile_app_info.mobile_app_id = mobile_app_id mobile_app_info.device_tracker = device_tracker mobile_app_info.action = notify_action + mobile_app_info.in_use_entity = in_use_entity found += 1 self._mobile_apps_by_app_id[mobile_app_id] = mobile_app_info diff --git a/custom_components/supernotify/notification.py b/custom_components/supernotify/notification.py index db884a141..d7d6a24c6 100644 --- a/custom_components/supernotify/notification.py +++ b/custom_components/supernotify/notification.py @@ -28,11 +28,13 @@ ATTR_DRY_RUN, ATTR_FORCE_RESEND, ATTR_IMAGE, + ATTR_INCLUDE_IDLE_DEVICES, ATTR_MEDIA, ATTR_MEDIA_CAMERA_ENTITY_ID, ATTR_MEDIA_CLIP_URL, ATTR_MEDIA_SNAPSHOT_URL, ATTR_MESSAGE_HTML, + ATTR_MOBILE_APP_ID, ATTR_PERSON_ID, ATTR_PRIORITY, ATTR_RECIPIENTS, @@ -47,6 +49,7 @@ DRY_RUN_LIVE, DRY_RUN_SIMULATE, INCLUSION_DEFAULT, + PRIORITY_CRITICAL, PRIORITY_MEDIUM, PRIORITY_VALUES, TARGET_USE_FIXED, @@ -212,6 +215,7 @@ def __init__( self.message_html: str | None = action_data.get(ATTR_MESSAGE_HTML) self.spoken_message: str | None = action_data.get(ATTR_SPOKEN_MESSAGE) self.force_resend: bool = action_data.get(ATTR_FORCE_RESEND, False) + self.include_idle_devices: bool = action_data.get(ATTR_INCLUDE_IDLE_DEVICES, False) self.dry_run: str = action_data.get(ATTR_DRY_RUN, DRY_RUN_LIVE) self.required_scenario_names: list[str] = ensure_list(action_data.get(ATTR_SCENARIOS_REQUIRE)) self.applied_scenario_names: list[str] = ensure_list(action_data.get(ATTR_SCENARIOS_APPLY)) @@ -1547,6 +1551,7 @@ def resolve_indirect_targets(self, target: Target, delivery: Delivery) -> list[T recipient_target = self.context.snoozer.filter_mobile_app_ids( recipient.target(delivery.name), self.priority, delivery ) + recipient_target = self._without_idle_mobile_devices(recipient, recipient_target, delivery) if recipient_target.target_specific_data: additional.append(recipient_target) else: @@ -1556,6 +1561,23 @@ def resolve_indirect_targets(self, target: Target, delivery: Delivery) -> list[T return [resolved, *additional] + def _without_idle_mobile_devices(self, recipient: Recipient, target: Target, delivery: Delivery) -> Target: + """Drop the person's mobile devices that nobody is using, such as a sleeping Mac or a + watch that isn't worn - unless critical, or asked for with `include_idle_devices` + + Only the person's own devices, as they're resolved: a mobile_app_id given directly in + the action is always notified + """ + if not target.mobile_app_ids or self.include_idle_devices or self.priority == PRIORITY_CRITICAL: + return target + idle: dict[str, str] = recipient.idle_mobile_app_ids(target.mobile_app_ids, self.context.hass_api) + if not idle: + return target + _LOGGER.debug("SUPERNOTIFY Skipping idle mobile devices of %s: %s", recipient.entity_id, idle) + skipped: dict[str, str] = self.debug_trace.delivery_artefacts.get(delivery.name, {}).get("idle_mobile_devices", {}) + self.debug_trace.record_delivery_artefact(delivery.name, "idle_mobile_devices", {**skipped, **idle}) + return target - Target({ATTR_MOBILE_APP_ID: list(idle)}) + def generate_envelopes(self, delivery: Delivery, targets: list[Target]) -> list[Envelope]: # now the list of recipients determined, resolve this to target addresses or entities diff --git a/custom_components/supernotify/people.py b/custom_components/supernotify/people.py index 71a504df5..825df35c6 100644 --- a/custom_components/supernotify/people.py +++ b/custom_components/supernotify/people.py @@ -18,6 +18,7 @@ CONF_TARGET, STATE_HOME, STATE_NOT_HOME, + STATE_OFF, ) from homeassistant.core import callback from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback @@ -35,11 +36,13 @@ ATTR_USER_ID, CONF_DATA, CONF_DELIVERY, + CONF_IN_USE_ENTITY, CONF_MOBILE_APP_ID, CONF_MOBILE_DEVICES, CONF_MOBILE_DISCOVERY, CONF_PERSON, CONF_PHONE_NUMBER, + CONF_SEND_WHEN_IDLE, CONF_USER_ID, OCCUPANCY_ALL, OCCUPANCY_ALL_IN, @@ -332,6 +335,30 @@ def check_mobile_actions(self, hass_api: HomeAssistantAPI) -> None: def enabled_mobile_devices(self) -> dict[str, dict[str, str | list[str] | None]]: return {k: v for k, v in self.mobile_devices.items() if v.get(CONF_ENABLED, True)} + def idle_mobile_app_ids(self, mobile_app_ids: list[str], hass_api: HomeAssistantAPI) -> dict[str, str]: + """Which of these mobile devices nobody is using, each with the sensor that says so + + Only a device whose in-use sensor is plainly `off` counts: no sensor, or one that's + `unknown` or `unavailable`, and the device is notified as before. A device set to + `send_when_idle` is never idle. If every one of them is idle, none is left out, so the + notification still reaches the person somewhere. + """ + idle: dict[str, str] = {} + for mobile_app_id in mobile_app_ids: + device = self.mobile_devices.get(mobile_app_id.removeprefix("notify.")) + if not device or device.get(CONF_SEND_WHEN_IDLE): + continue + in_use_entity = device.get(CONF_IN_USE_ENTITY) + if not isinstance(in_use_entity, str): + continue + state = hass_api.get_state(in_use_entity) + if state is not None and state.state == STATE_OFF: + idle[mobile_app_id] = in_use_entity + if idle and len(idle) == len(mobile_app_ids): + _LOGGER.debug("SUPERNOTIFY All of %s mobile devices idle, so notifying them all", self.entity_id) + return {} + return idle + def enabling_delivery_names(self) -> list[str]: """Explicitly overriding enabled state""" return [ diff --git a/custom_components/supernotify/schema.py b/custom_components/supernotify/schema.py index d77238bae..ff54a40bf 100644 --- a/custom_components/supernotify/schema.py +++ b/custom_components/supernotify/schema.py @@ -56,6 +56,7 @@ ATTR_EMAIL, ATTR_EXTRA_DATA, ATTR_FORCE_RESEND, + ATTR_INCLUDE_IDLE_DEVICES, ATTR_JPEG_OPTS, ATTR_MEDIA, ATTR_MEDIA_CAMERA_DELAY, @@ -116,6 +117,7 @@ CONF_FALLBACK, CONF_HOUSEKEEPING, CONF_HOUSEKEEPING_TIME, + CONF_IN_USE_ENTITY, CONF_INCLUSION, CONF_LEVEL, CONF_LOAD, @@ -148,6 +150,7 @@ CONF_SCENARIOS, CONF_SELECTION, CONF_SELECTION_RANK, + CONF_SEND_WHEN_IDLE, CONF_SIZE, CONF_SNAP_WAIT, CONF_SNAPSHOT_URL_LOCAL, @@ -292,6 +295,8 @@ def validate_scenario_names(scenarios: dict) -> dict: vol.Optional(CONF_MOBILE_APP_ID): cv.string, vol.Optional(CONF_DEVICE_TRACKER): cv.entity_id, vol.Optional(CONF_ENABLED, default=True): cv.boolean, + vol.Optional(CONF_IN_USE_ENTITY): cv.entity_id, + vol.Optional(CONF_SEND_WHEN_IDLE): cv.boolean, }) NOTIFICATION_DUPE_SCHEMA = vol.Schema({ vol.Optional(CONF_TTL, default=120): cv.positive_int, @@ -714,6 +719,7 @@ def _single_notification_level(actions: list[dict[str, Any]]) -> list[dict[str, ), vol.Optional(ATTR_DEBUG, default=False): cv.boolean, vol.Optional(ATTR_FORCE_RESEND, default=False): cv.boolean, + vol.Optional(ATTR_INCLUDE_IDLE_DEVICES, default=False): cv.boolean, vol.Optional(ATTR_DRY_RUN, default=DRY_RUN_LIVE): vol.In(DRY_RUN_VALUES), vol.Optional(ATTR_DATA): vol.Any(None, DATA_SCHEMA), vol.Optional(ATTR_TIMESTAMP): cv.string, diff --git a/custom_components/supernotify/services.yaml b/custom_components/supernotify/services.yaml index c93dc2ac7..22988a66b 100644 --- a/custom_components/supernotify/services.yaml +++ b/custom_components/supernotify/services.yaml @@ -119,6 +119,9 @@ notify: force_resend: selector: boolean: + include_idle_devices: + selector: + boolean: dry_run: required: false default: live diff --git a/custom_components/supernotify/translations/de.json b/custom_components/supernotify/translations/de.json index 9904d9c07..42dead7ac 100644 --- a/custom_components/supernotify/translations/de.json +++ b/custom_components/supernotify/translations/de.json @@ -156,6 +156,10 @@ "name": "Erneutes Senden erzwingen", "description": "Auch senden, wenn die Duplikaterkennung diese Benachrichtigung sonst unterdrücken würde." }, + "include_idle_devices": { + "name": "Inaktive Geräte einbeziehen", + "description": "Auch an die Mobilgeräte der Empfänger senden, die gerade niemand verwendet, etwa ein schlafender Mac oder eine nicht getragene Uhr." + }, "dry_run": { "name": "Testlauf", "description": "Simulieren ermittelt, welche Zustellungen verwendet würden und wen sie erreichen würden, ohne tatsächlich etwas zu senden. Der Live-Modus ist der übliche Betriebsmodus." @@ -853,6 +857,7 @@ "enabled": "Aktiviert", "mobile_discovery": "Mobilgeräte-Erkennung", "mobile_devices": "Mobilgeräte", + "send_when_idle": "Auch ohne Nutzung benachrichtigen", "target": "Ziele", "custom_target": "Benutzerdefinierte Ziele" }, @@ -863,6 +868,7 @@ "enabled": "Ob dieser Empfänger überhaupt benachrichtigt wird", "mobile_discovery": "Neu für diesen Empfänger registrierte Mobile-App-Geräte verwenden", "mobile_devices": "Die zu benachrichtigenden Mobile-App-Geräte - nicht angehakte werden ausgelassen", + "send_when_idle": "Geräte, die auch benachrichtigt werden, wenn ihr Nutzungssensor meldet, dass niemand sie verwendet - ein schlafender Mac, eine nicht getragene Uhr", "target": "Entitäten, Geräte, Bereiche, Etagen oder Labels, die als dieser Empfänger benachrichtigt werden, wie in der Aktion supernotify.notify", "custom_target": "Ziele, die die Auswahl nicht bietet, eines pro Zeile - eine E-Mail-Adresse, eine Telefonnummer oder Kategorie:Wert, etwa telegram_chat_id:12345. Die Kategorien sind: {categories}" }, diff --git a/custom_components/supernotify/translations/en.json b/custom_components/supernotify/translations/en.json index 174aebfee..47d35bc73 100644 --- a/custom_components/supernotify/translations/en.json +++ b/custom_components/supernotify/translations/en.json @@ -191,6 +191,10 @@ "name": "Force Resend", "description": "Send even if duplicate-detection would otherwise suppress this notification." }, + "include_idle_devices": { + "name": "Include idle devices", + "description": "Also send to the recipients' mobile devices that nobody is using, like a sleeping Mac or a watch not worn." + }, "dry_run": { "name": "Simulation", "description": "Simulate mode works out which deliveries would be used and who they would reach, without actually sending anything. Live mode is the usual operating mode." @@ -888,6 +892,7 @@ "enabled": "Enabled", "mobile_discovery": "Mobile Device Discovery", "mobile_devices": "Mobile devices", + "send_when_idle": "Notify even when not in use", "target": "Targets", "custom_target": "Custom targets" }, @@ -898,6 +903,7 @@ "enabled": "Whether this recipient is notified at all", "mobile_discovery": "Use mobile app devices newly registered to this recipient", "mobile_devices": "The mobile app devices to notify - unticked ones are left out", + "send_when_idle": "Devices to notify even when their in-use sensor says nobody is using them - a sleeping Mac, a watch not worn", "target": "Entities, devices, areas, floors or labels to notify as this recipient, as in the supernotify.notify action", "custom_target": "Targets the selector can't pick, one per line - an e-mail address, a phone number, or category:value, such as telegram_chat_id:12345. The categories are: {categories}" }, diff --git a/custom_components/supernotify/translations/es.json b/custom_components/supernotify/translations/es.json index 0d0fcb7ab..a5c986edd 100644 --- a/custom_components/supernotify/translations/es.json +++ b/custom_components/supernotify/translations/es.json @@ -156,6 +156,10 @@ "name": "Forzar reenvío", "description": "Envía incluso si la detección de duplicados suprimiría esta notificación." }, + "include_idle_devices": { + "name": "Incluir dispositivos inactivos", + "description": "Envía también a los dispositivos móviles de los destinatarios que nadie está usando, como un Mac en reposo o un reloj que no se lleva puesto." + }, "dry_run": { "name": "Simulación", "description": "Simular calcula qué entregas se usarían y a quién alcanzarían, sin enviar realmente nada. El modo real es el modo de funcionamiento habitual." @@ -853,6 +857,7 @@ "enabled": "Activado", "mobile_discovery": "Descubrimiento de dispositivos móviles", "mobile_devices": "Dispositivos móviles", + "send_when_idle": "Notificar aunque no esté en uso", "target": "Destinos", "custom_target": "Destinos personalizados" }, @@ -863,6 +868,7 @@ "enabled": "Si se notifica a este destinatario", "mobile_discovery": "Usar los dispositivos de la app móvil registrados nuevamente para este destinatario", "mobile_devices": "Los dispositivos de la app móvil a notificar - los no marcados se omiten", + "send_when_idle": "Dispositivos a notificar aunque su sensor de uso indique que nadie los usa - un Mac en reposo, un reloj que no se lleva puesto", "target": "Entidades, dispositivos, áreas, plantas o etiquetas a notificar como este destinatario, como en la acción supernotify.notify", "custom_target": "Destinos que el selector no ofrece, uno por línea - un correo electrónico, un número de teléfono o categoría:valor, como telegram_chat_id:12345. Las categorías son: {categories}" }, diff --git a/custom_components/supernotify/translations/fr.json b/custom_components/supernotify/translations/fr.json index bb491da36..967234570 100644 --- a/custom_components/supernotify/translations/fr.json +++ b/custom_components/supernotify/translations/fr.json @@ -156,6 +156,10 @@ "name": "Forcer le renvoi", "description": "Envoyer même si la détection des doublons supprimerait autrement cette notification." }, + "include_idle_devices": { + "name": "Inclure les appareils inactifs", + "description": "Envoyer aussi aux appareils mobiles des destinataires que personne n'utilise, comme un Mac en veille ou une montre non portée." + }, "dry_run": { "name": "Simulation", "description": "Simuler détermine quelles livraisons seraient utilisées et qui elles atteindraient, sans réellement rien envoyer. Le mode réel est le mode de fonctionnement habituel." @@ -853,6 +857,7 @@ "enabled": "Activé", "mobile_discovery": "Découverte des appareils mobiles", "mobile_devices": "Appareils mobiles", + "send_when_idle": "Notifier même hors utilisation", "target": "Cibles", "custom_target": "Cibles personnalisées" }, @@ -863,6 +868,7 @@ "enabled": "Si ce destinataire est notifié ou non", "mobile_discovery": "Utiliser les appareils de l'application mobile nouvellement enregistrés pour ce destinataire", "mobile_devices": "Les appareils de l'application mobile à notifier - ceux non cochés sont exclus", + "send_when_idle": "Appareils à notifier même lorsque leur capteur d'utilisation indique que personne ne s'en sert - un Mac en veille, une montre non portée", "target": "Entités, appareils, pièces, étages ou étiquettes à notifier pour ce destinataire, comme dans l'action supernotify.notify", "custom_target": "Cibles que le sélecteur ne propose pas, une par ligne - une adresse e-mail, un numéro de téléphone ou catégorie:valeur, comme telegram_chat_id:12345. Les catégories sont : {categories}" }, diff --git a/custom_components/supernotify/translations/hi.json b/custom_components/supernotify/translations/hi.json index 8d06bc1fb..92bfed766 100644 --- a/custom_components/supernotify/translations/hi.json +++ b/custom_components/supernotify/translations/hi.json @@ -156,6 +156,10 @@ "name": "पुनः भेजना बाध्य करें", "description": "भेजें भले ही डुप्लिकेट-डिटेक्शन अन्यथा इस सूचना को दबा देती।" }, + "include_idle_devices": { + "name": "निष्क्रिय डिवाइस शामिल करें", + "description": "प्राप्तकर्ताओं के उन मोबाइल डिवाइस पर भी भेजें जिनका कोई उपयोग नहीं कर रहा, जैसे सोया हुआ Mac या न पहनी गई घड़ी।" + }, "dry_run": { "name": "ड्राई रन", "description": "सिम्युलेट यह पता लगाता है कि कौन सी डिलीवरी उपयोग की जाएंगी और वे किसे पहुंचेंगी, वास्तव में कुछ भी भेजे बिना। लाइव मोड सामान्य संचालन मोड है।" @@ -853,6 +857,7 @@ "enabled": "सक्षम", "mobile_discovery": "मोबाइल डिवाइस खोज", "mobile_devices": "मोबाइल डिवाइस", + "send_when_idle": "उपयोग में न होने पर भी सूचित करें", "target": "लक्ष्य", "custom_target": "कस्टम लक्ष्य" }, @@ -863,6 +868,7 @@ "enabled": "क्या इस प्राप्तकर्ता को सूचित किया जाता है", "mobile_discovery": "इस प्राप्तकर्ता के लिए नए पंजीकृत मोबाइल ऐप डिवाइस का उपयोग करें", "mobile_devices": "सूचित किए जाने वाले मोबाइल ऐप डिवाइस - जिन पर निशान नहीं है वे छोड़ दिए जाते हैं", + "send_when_idle": "वे डिवाइस जिन्हें तब भी सूचित करना है जब उनका उपयोग-सेंसर बताए कि कोई उनका उपयोग नहीं कर रहा - सोया हुआ Mac, न पहनी गई घड़ी", "target": "इस प्राप्तकर्ता के रूप में सूचित की जाने वाली एंटिटी, डिवाइस, क्षेत्र, मंज़िल या लेबल, जैसे supernotify.notify क्रिया में", "custom_target": "वे लक्ष्य जो चयनकर्ता नहीं दे सकता, प्रति पंक्ति एक - ई-मेल पता, फ़ोन नंबर, या श्रेणी:मान, जैसे telegram_chat_id:12345. श्रेणियाँ हैं: {categories}" }, diff --git a/custom_components/supernotify/translations/it.json b/custom_components/supernotify/translations/it.json index ae2cdb5a9..79d00ace3 100644 --- a/custom_components/supernotify/translations/it.json +++ b/custom_components/supernotify/translations/it.json @@ -191,6 +191,10 @@ "name": "Forza reinvio", "description": "Invia anche se il rilevamento dei duplicati sopprimerebbe altrimenti questa notifica." }, + "include_idle_devices": { + "name": "Includi i dispositivi inattivi", + "description": "Invia anche ai dispositivi mobili dei destinatari che nessuno sta usando, come un Mac in stop o un orologio non indossato." + }, "dry_run": { "name": "Simulazione", "description": "Simula calcola quali consegne verrebbero usate e chi raggiungerebbero, senza inviare realmente nulla. La modalità live è la normale modalità operativa." @@ -888,6 +892,7 @@ "enabled": "Abilitato", "mobile_discovery": "Rilevamento dispositivi mobili", "mobile_devices": "Dispositivi mobili", + "send_when_idle": "Notifica anche quando non in uso", "target": "Destinazioni", "custom_target": "Destinazioni personalizzate" }, @@ -898,6 +903,7 @@ "enabled": "Se questo recipient viene notificato", "mobile_discovery": "Usa i dispositivi dell'app mobile appena registrati per questo recipient", "mobile_devices": "I dispositivi dell'app mobile da notificare - quelli non selezionati vengono esclusi", + "send_when_idle": "Dispositivi da notificare anche quando il loro sensore di utilizzo dice che nessuno li sta usando - un Mac in stop, un orologio non indossato", "target": "Entità, dispositivi, aree, piani o etichette da notificare come questo recipient, come nell'azione supernotify.notify", "custom_target": "Destinazioni che il selettore non offre, una per riga - un indirizzo e-mail, un numero di telefono o categoria:valore, come telegram_chat_id:12345. Le categorie sono: {categories}" }, diff --git a/custom_components/supernotify/translations/ja.json b/custom_components/supernotify/translations/ja.json index c2a24e89b..c22b64738 100644 --- a/custom_components/supernotify/translations/ja.json +++ b/custom_components/supernotify/translations/ja.json @@ -156,6 +156,10 @@ "name": "再送信を強制", "description": "重複検出によりこの通知が抑制される場合でも送信します。" }, + "include_idle_devices": { + "name": "非アクティブなデバイスを含める", + "description": "スリープ中の Mac や着用していない腕時計など、誰も使っていない受信者のモバイルデバイスにも送信します。" + }, "dry_run": { "name": "ドライラン", "description": "シミュレートは、実際には何も送信せずに、どの配信が使用され、誰に届くかを計算します。通常の動作モードはライブモードです。" @@ -853,6 +857,7 @@ "enabled": "有効", "mobile_discovery": "モバイルデバイスの検出", "mobile_devices": "モバイルデバイス", + "send_when_idle": "使用中でなくても通知", "target": "ターゲット", "custom_target": "カスタムターゲット" }, @@ -863,6 +868,7 @@ "enabled": "この受信者に通知するかどうか", "mobile_discovery": "この受信者に新たに登録されたモバイルアプリのデバイスを使用する", "mobile_devices": "通知するモバイルアプリのデバイス - チェックのないものは除外されます", + "send_when_idle": "使用中センサーが誰も使っていないことを示していても通知するデバイス - スリープ中の Mac、着用していない腕時計など", "target": "この受信者として通知するエンティティ、デバイス、エリア、フロア、ラベル (supernotify.notify アクションと同様)", "custom_target": "セレクターで選べないターゲット、1 行に 1 つ - メールアドレス、電話番号、または telegram_chat_id:12345 のような カテゴリ:値。カテゴリ: {categories}" }, diff --git a/custom_components/supernotify/translations/nl.json b/custom_components/supernotify/translations/nl.json index c864569ac..1cd3647c2 100644 --- a/custom_components/supernotify/translations/nl.json +++ b/custom_components/supernotify/translations/nl.json @@ -156,6 +156,10 @@ "name": "Opnieuw verzenden forceren", "description": "Verzend zelfs als detectie van duplicaten deze melding anders zou onderdrukken." }, + "include_idle_devices": { + "name": "Inactieve apparaten meenemen", + "description": "Ook verzenden naar mobiele apparaten van de ontvangers die niemand gebruikt, zoals een slapende Mac of een horloge dat niet gedragen wordt." + }, "dry_run": { "name": "Testrun", "description": "Simuleren berekent welke bezorgingen gebruikt zouden worden en wie ze zouden bereiken, zonder daadwerkelijk iets te verzenden. De live-modus is de gebruikelijke werkingsmodus." @@ -853,6 +857,7 @@ "enabled": "Ingeschakeld", "mobile_discovery": "Detectie van mobiele apparaten", "mobile_devices": "Mobiele apparaten", + "send_when_idle": "Ook melden als niet in gebruik", "target": "Doelen", "custom_target": "Aangepaste doelen" }, @@ -863,6 +868,7 @@ "enabled": "Of deze ontvanger überhaupt een melding krijgt", "mobile_discovery": "Mobiele-app-apparaten gebruiken die nieuw voor deze ontvanger zijn geregistreerd", "mobile_devices": "De mobiele-app-apparaten om te melden - niet aangevinkte worden overgeslagen", + "send_when_idle": "Apparaten die ook een melding krijgen als hun gebruikssensor zegt dat niemand ze gebruikt - een slapende Mac, een horloge dat niet gedragen wordt", "target": "Entiteiten, apparaten, ruimtes, verdiepingen of labels om als deze ontvanger te melden, zoals in de actie supernotify.notify", "custom_target": "Doelen die de kiezer niet biedt, één per regel - een e-mailadres, een telefoonnummer of categorie:waarde, zoals telegram_chat_id:12345. De categorieën zijn: {categories}" }, diff --git a/custom_components/supernotify/translations/pl.json b/custom_components/supernotify/translations/pl.json index 680152aa3..84a2d827f 100644 --- a/custom_components/supernotify/translations/pl.json +++ b/custom_components/supernotify/translations/pl.json @@ -156,6 +156,10 @@ "name": "Wymuś ponowne wysłanie", "description": "Wyślij nawet, jeśli wykrywanie duplikatów w innym przypadku wstrzymałoby to powiadomienie." }, + "include_idle_devices": { + "name": "Uwzględnij nieaktywne urządzenia", + "description": "Wyślij także na urządzenia mobilne odbiorców, z których nikt nie korzysta, np. uśpiony Mac lub niezałożony zegarek." + }, "dry_run": { "name": "Próba", "description": "Symulacja określa, które dostawy zostałyby użyte i kogo by osiągnęły, bez faktycznego wysyłania czegokolwiek. Tryb rzeczywisty jest zwykłym trybem działania." @@ -853,6 +857,7 @@ "enabled": "Włączony", "mobile_discovery": "Wykrywanie urządzeń mobilnych", "mobile_devices": "Urządzenia mobilne", + "send_when_idle": "Powiadamiaj także, gdy nieużywane", "target": "Cele", "custom_target": "Własne cele" }, @@ -863,6 +868,7 @@ "enabled": "Czy ten odbiorca jest w ogóle powiadamiany", "mobile_discovery": "Używaj urządzeń aplikacji mobilnej nowo zarejestrowanych dla tego odbiorcy", "mobile_devices": "Urządzenia aplikacji mobilnej do powiadamiania - niezaznaczone są pomijane", + "send_when_idle": "Urządzenia powiadamiane także wtedy, gdy ich czujnik użycia wskazuje, że nikt z nich nie korzysta - uśpiony Mac, niezałożony zegarek", "target": "Encje, urządzenia, obszary, piętra lub etykiety powiadamiane jako ten odbiorca, jak w akcji supernotify.notify", "custom_target": "Cele, których selektor nie oferuje, po jednym w wierszu - adres e-mail, numer telefonu lub kategoria:wartość, np. telegram_chat_id:12345. Kategorie to: {categories}" }, diff --git a/custom_components/supernotify/translations/pt.json b/custom_components/supernotify/translations/pt.json index b811e7436..b270a1c69 100644 --- a/custom_components/supernotify/translations/pt.json +++ b/custom_components/supernotify/translations/pt.json @@ -156,6 +156,10 @@ "name": "Forçar reenvio", "description": "Envia mesmo que a deteção de duplicados suprimisse esta notificação." }, + "include_idle_devices": { + "name": "Incluir dispositivos inativos", + "description": "Envia também para os dispositivos móveis dos destinatários que ninguém está a usar, como um Mac em repouso ou um relógio que não está no pulso." + }, "dry_run": { "name": "Simulação", "description": "Simular calcula quais entregas seriam usadas e quem alcançariam, sem realmente enviar nada. O modo real é o modo de funcionamento habitual." @@ -853,6 +857,7 @@ "enabled": "Ativado", "mobile_discovery": "Descoberta de dispositivos móveis", "mobile_devices": "Dispositivos móveis", + "send_when_idle": "Notificar mesmo sem estar em uso", "target": "Destinos", "custom_target": "Destinos personalizados" }, @@ -863,6 +868,7 @@ "enabled": "Se este destinatário é notificado", "mobile_discovery": "Usar dispositivos da app móvel registados recentemente para este destinatário", "mobile_devices": "Os dispositivos da app móvel a notificar - os não marcados são excluídos", + "send_when_idle": "Dispositivos a notificar mesmo quando o sensor de utilização indica que ninguém os está a usar - um Mac em repouso, um relógio que não está no pulso", "target": "Entidades, dispositivos, áreas, pisos ou etiquetas a notificar como este destinatário, como na ação supernotify.notify", "custom_target": "Destinos que o seletor não oferece, um por linha - um endereço de e-mail, um número de telefone ou categoria:valor, como telegram_chat_id:12345. As categorias são: {categories}" }, diff --git a/custom_components/supernotify/translations/zh-Hans.json b/custom_components/supernotify/translations/zh-Hans.json index bd4e32551..8d2ec3354 100644 --- a/custom_components/supernotify/translations/zh-Hans.json +++ b/custom_components/supernotify/translations/zh-Hans.json @@ -156,6 +156,10 @@ "name": "强制重新发送", "description": "即使重复检测原本会抑制此通知,也发送。" }, + "include_idle_devices": { + "name": "包括闲置设备", + "description": "也发送到无人使用的接收者移动设备,例如休眠的 Mac 或未佩戴的手表。" + }, "dry_run": { "name": "演练", "description": "模拟会计算将使用哪些投递方式以及它们会送达给谁,而不实际发送任何内容。正式发送模式是通常的运行模式。" @@ -853,6 +857,7 @@ "enabled": "已启用", "mobile_discovery": "移动设备发现", "mobile_devices": "移动设备", + "send_when_idle": "未使用时也通知", "target": "目标", "custom_target": "自定义目标" }, @@ -863,6 +868,7 @@ "enabled": "是否通知此收件人", "mobile_discovery": "使用为此收件人新注册的移动应用设备", "mobile_devices": "要通知的移动应用设备 - 未勾选的会被排除", + "send_when_idle": "即使使用状态传感器显示无人使用也要通知的设备 - 例如休眠的 Mac、未佩戴的手表", "target": "作为此收件人通知的实体、设备、区域、楼层或标签,与 supernotify.notify 动作中相同", "custom_target": "选择器无法选择的目标,每行一个 - 电子邮件地址、电话号码,或 类别:值,例如 telegram_chat_id:12345。类别有:{categories}" }, diff --git a/docs/transports/mobile_push.md b/docs/transports/mobile_push.md index 89961fa92..643ec5d74 100644 --- a/docs/transports/mobile_push.md +++ b/docs/transports/mobile_push.md @@ -241,6 +241,50 @@ entry exists) and no `mobile_push` delivery is configured, a `mobile_push` deliv generated automatically and fires on every notification, with targets resolved per-recipient from the HA Companion App at delivery time. +## Devices Not in Use + +A recipient's mobile devices that nobody is using are left out, so a sleeping Mac doesn't +show a pile of stale alerts when it wakes, and a watch on the bedside table doesn't buzz. +Supernotify finds each device's in-use sensor from the Companion App itself, no configuration needed: + +| Device | Sensor | Off when | +|---------|---------------------------------|-----------------------------------------------| +| macOS | `binary_sensor._active` | asleep, screensaver on, display off or locked | +| Wear OS | `binary_sensor._on_body` | the watch isn't being worn | + +- A device is left out only when its sensor is `off`. With no sensor, or one that's `unknown` or + `unavailable`, it's notified as before +- `critical` notifications go to every device +- If every one of a person's devices would be left out, none is, so the notification still gets through +- A device given directly as a target of the notification, rather than through a recipient, is always notified +- Devices left out are listed in the notification's debug trace, as `idle_mobile_devices` + +Android's `is_interactive` sensor isn't used, since it's only whether the screen is on, so it's +off for a phone in a pocket. It can be given for a device where that does mean nobody is using +it, such as a tablet, as its `in_use_entity`, and so can any other `binary_sensor`, such as a +template sensor for an iPad: + +```yaml +recipients: + - person: person.bob + mobile_devices: + - mobile_app_id: mobile_app_bobs_tablet + in_use_entity: binary_sensor.bobs_tablet_is_interactive + - mobile_app_id: mobile_app_bobs_mac + send_when_idle: true +``` + +`send_when_idle` notifies a device whether in use or not, and can also be set on the +recipient's form as *Notify even when not in use*. For a single notification, set +`include_idle_devices: true`: + +```yaml + - action: supernotify.notify + data: + message: Something happened + include_idle_devices: true +``` + ## References ### Home Assistant Core diff --git a/tests/components/supernotify/test_idle_mobile_devices.py b/tests/components/supernotify/test_idle_mobile_devices.py new file mode 100644 index 000000000..856752de2 --- /dev/null +++ b/tests/components/supernotify/test_idle_mobile_devices.py @@ -0,0 +1,278 @@ +"""Mobile devices nobody is using - a sleeping Mac, a watch not worn - left out of a notification, +from the Companion app's own in-use sensor, found in the entity registry""" + +from __future__ import annotations + +import hashlib +from typing import TYPE_CHECKING, Any + +import pytest +from homeassistant.config_entries import SOURCE_RECONFIGURE, ConfigSubentryData +from homeassistant.const import STATE_OFF, STATE_ON, STATE_UNAVAILABLE, STATE_UNKNOWN +from homeassistant.data_entry_flow import FlowResultType +from homeassistant.helpers import entity_registry as er +from homeassistant.setup import async_setup_component + +from custom_components.supernotify import DOMAIN +from custom_components.supernotify.const import ( + CONF_IN_USE_ENTITY, + CONF_MOBILE_APP_ID, + CONF_MOBILE_DEVICES, + CONF_PERSON, + CONF_SEND_WHEN_IDLE, + SUBENTRY_TYPE_RECIPIENT, +) +from custom_components.supernotify.hass_api import HomeAssistantAPI, companion_sensor_id +from custom_components.supernotify.notification import Notification +from custom_components.supernotify.people import Recipient +from custom_components.supernotify.schema import MOBILE_DEVICE_SCHEMA +from custom_components.supernotify.transports.mobile_push import MobilePushTransport +from tests.components.supernotify.ha_testing import MockConfigEntry + +from .hass_setup_lib import TestingContext, first_envelope, register_mobile_app, set_state + +if TYPE_CHECKING: + from homeassistant.core import HomeAssistant + +PHONE = "mobile_app_bob_phone" +LAPTOP = "mobile_app_bob_laptop" +WATCH = "mobile_app_bob_watch" +LAPTOP_SENSOR = "binary_sensor.bob_laptop_active" +WATCH_SENSOR = "binary_sensor.bob_watch_on_body" + + +def test_companion_sensor_id() -> None: + assert companion_sensor_id("0123abcd_active") == "active" + assert companion_sensor_id("0123abcd_on_body") == "on_body" + assert companion_sensor_id("0123abcd_is_interactive") == "is_interactive" + assert companion_sensor_id("no-sensor-id") is None + assert companion_sensor_id(None) is None + + +def test_schema_takes_in_use_entity_and_send_when_idle() -> None: + device = MOBILE_DEVICE_SCHEMA({CONF_MOBILE_APP_ID: LAPTOP, CONF_IN_USE_ENTITY: LAPTOP_SENSOR, CONF_SEND_WHEN_IDLE: "yes"}) + assert device[CONF_IN_USE_ENTITY] == LAPTOP_SENSOR + assert device[CONF_SEND_WHEN_IDLE] is True + + +async def _ctx(**laptop: Any) -> TestingContext: + ctx = TestingContext( + recipients=[ + { + CONF_PERSON: "person.bob_mctest", + CONF_MOBILE_DEVICES: [ + {CONF_MOBILE_APP_ID: PHONE}, + {CONF_MOBILE_APP_ID: LAPTOP, CONF_IN_USE_ENTITY: LAPTOP_SENSOR, **laptop}, + {CONF_MOBILE_APP_ID: WATCH, CONF_IN_USE_ENTITY: WATCH_SENSOR}, + ], + }, + ], + services={"notify": [PHONE, LAPTOP, WATCH]}, + ) + await ctx.test_initialize() + return ctx + + +async def _send(ctx: TestingContext, message: str = "Hello", **kwargs: Any) -> Notification: + uut = Notification(ctx, message=message, **kwargs) + await uut.initialize() + await uut.deliver() + return uut + + +async def test_idle_devices_left_out() -> None: + ctx = await _ctx() + set_state(ctx.hass_api, LAPTOP_SENSOR, STATE_OFF) + set_state(ctx.hass_api, WATCH_SENSOR, STATE_ON) + + uut = await _send(ctx, action_data={"debug": True}) + envelope = first_envelope(uut, "mobile_push") + assert envelope.target.mobile_app_ids == [PHONE, WATCH] + # the person stays in the target + assert envelope.target.person_ids == ["person.bob_mctest"] + # and the trace says which device was left out, and by which sensor + assert uut.debug_trace.delivery_artefacts["mobile_push"]["idle_mobile_devices"] == {LAPTOP: LAPTOP_SENSOR} + + +@pytest.mark.parametrize("state", [STATE_ON, STATE_UNKNOWN, STATE_UNAVAILABLE, None]) +async def test_devices_not_plainly_idle_are_notified(state: str | None) -> None: + ctx = await _ctx() + if state is not None: + set_state(ctx.hass_api, LAPTOP_SENSOR, state) + set_state(ctx.hass_api, WATCH_SENSOR, state) + + envelope = first_envelope(await _send(ctx), "mobile_push") + assert envelope.target.mobile_app_ids == [PHONE, LAPTOP, WATCH] + + +async def test_send_when_idle() -> None: + ctx = await _ctx(**{CONF_SEND_WHEN_IDLE: True}) + set_state(ctx.hass_api, LAPTOP_SENSOR, STATE_OFF) + set_state(ctx.hass_api, WATCH_SENSOR, STATE_OFF) + + envelope = first_envelope(await _send(ctx), "mobile_push") + assert envelope.target.mobile_app_ids == [PHONE, LAPTOP] + + +@pytest.mark.parametrize("action_data", [{"priority": "critical"}, {"include_idle_devices": True}]) +async def test_critical_or_asked_for_reaches_idle_devices(action_data: dict[str, Any]) -> None: + ctx = await _ctx() + set_state(ctx.hass_api, LAPTOP_SENSOR, STATE_OFF) + set_state(ctx.hass_api, WATCH_SENSOR, STATE_OFF) + + envelope = first_envelope(await _send(ctx, action_data=action_data), "mobile_push") + assert envelope.target.mobile_app_ids == [PHONE, LAPTOP, WATCH] + + +async def test_device_given_in_the_action_is_notified_even_when_idle() -> None: + ctx = await _ctx() + set_state(ctx.hass_api, LAPTOP_SENSOR, STATE_OFF) + + envelope = first_envelope(await _send(ctx, target=[LAPTOP]), "mobile_push") + assert envelope.target.mobile_app_ids == [LAPTOP] + + +def test_all_idle_means_none_left_out(hass: HomeAssistant) -> None: + """So the notification still reaches the person somewhere""" + hass_api = HomeAssistantAPI(hass) + set_state(hass_api, LAPTOP_SENSOR, STATE_OFF) + set_state(hass_api, WATCH_SENSOR, STATE_OFF) + bob = Recipient({ + CONF_PERSON: "person.bob_mctest", + CONF_MOBILE_DEVICES: [ + {CONF_MOBILE_APP_ID: LAPTOP, CONF_IN_USE_ENTITY: LAPTOP_SENSOR}, + {CONF_MOBILE_APP_ID: WATCH, CONF_IN_USE_ENTITY: WATCH_SENSOR}, + ], + }) + assert bob.idle_mobile_app_ids([LAPTOP, WATCH], hass_api) == {} + assert bob.idle_mobile_app_ids([f"notify.{LAPTOP}", PHONE], hass_api) == {f"notify.{LAPTOP}": LAPTOP_SENSOR} + # a device the recipient doesn't have isn't theirs to judge + assert bob.idle_mobile_app_ids(["mobile_app_someone_else"], hass_api) == {} + + +def _add_sensor(hass_api: HomeAssistantAPI, device_name: str, sensor_id: str, **kwargs: Any) -> str: + hass = hass_api._hass + slug = device_name.lower().replace(" ", "_") + device = next(d for d in hass_api.mobile_app_by_user_id(_user_id(hass)) or [] if d.mobile_app_id == f"mobile_app_{slug}") + entry = er.async_get(hass).async_get_or_create( + "binary_sensor", + "mobile_app", + # as mobile_app has it, prefixed by the device's own webhook id, which is hex + f"{hashlib.md5(slug.encode()).hexdigest()}_{sensor_id}", + suggested_object_id=f"{slug}_{sensor_id}", + device_id=device.device_id, + **kwargs, + ) + hass_api.build_mobile_app_cache() + return entry.entity_id + + +async def test_in_use_sensor_discovered(hass: HomeAssistant) -> None: + ctx = TestingContext( + homeassistant=hass, + recipients=[{CONF_PERSON: "person.test_user"}], + components={"person": {}}, + transport_types=[MobilePushTransport], + ) + register_mobile_app(ctx.hass_api, person="person.test_user", device_name="Bobs Laptop", os_name="macOS") + register_mobile_app(ctx.hass_api, person="person.test_user", device_name="Bobs Watch", os_name="Android") + register_mobile_app(ctx.hass_api, person="person.test_user", device_name="Bobs Phone", os_name="Android") + register_mobile_app(ctx.hass_api, person="person.test_user", device_name="Bobs Tablet", os_name="Android") + laptop_sensor = _add_sensor(ctx.hass_api, "Bobs Laptop", "active") + watch_sensor = _add_sensor(ctx.hass_api, "Bobs Watch", "on_body") + # screen off is no sign a phone isn't in use, so `is_interactive` isn't taken + _add_sensor(ctx.hass_api, "Bobs Phone", "is_interactive") + # nor is a sensor switched off in Home Assistant, as it has no state + _add_sensor(ctx.hass_api, "Bobs Tablet", "active", disabled_by=er.RegistryEntryDisabler.USER) + + devices = {d.mobile_app_id: d for d in ctx.hass_api.mobile_app_by_user_id(_user_id(hass)) or []} + assert devices["mobile_app_bobs_laptop"].in_use_entity == laptop_sensor + assert devices["mobile_app_bobs_watch"].in_use_entity == watch_sensor + assert devices["mobile_app_bobs_phone"].in_use_entity is None + assert devices["mobile_app_bobs_tablet"].in_use_entity is None + + await ctx.test_initialize() + set_state(ctx.hass_api, laptop_sensor, STATE_OFF) + set_state(ctx.hass_api, watch_sensor, STATE_ON) + bob: Recipient = ctx.people_registry.people["person.test_user"] + assert bob.idle_mobile_app_ids(list(bob.enabled_mobile_devices), ctx.hass_api) == {"mobile_app_bobs_laptop": laptop_sensor} + + +async def test_configured_in_use_entity_wins_over_discovered(hass: HomeAssistant) -> None: + """As for an Android tablet, whose `is_interactive` isn't taken by default""" + ctx = TestingContext( + homeassistant=hass, + recipients=""" + - person: person.test_user + mobile_devices: + - mobile_app_id: mobile_app_bobs_tablet + in_use_entity: binary_sensor.bobs_tablet_is_interactive +""", + components={"person": {}}, + transport_types=[MobilePushTransport], + ) + register_mobile_app(ctx.hass_api, person="person.test_user", device_name="Bobs Phone") + register_mobile_app(ctx.hass_api, person="person.test_user", device_name="Bobs Tablet") + _add_sensor(ctx.hass_api, "Bobs Tablet", "active") + await ctx.test_initialize() + + bob: Recipient = ctx.people_registry.people["person.test_user"] + assert bob.mobile_devices["mobile_app_bobs_tablet"][CONF_IN_USE_ENTITY] == "binary_sensor.bobs_tablet_is_interactive" + set_state(ctx.hass_api, "binary_sensor.bobs_tablet_is_interactive", STATE_OFF) + assert bob.idle_mobile_app_ids(list(bob.enabled_mobile_devices), ctx.hass_api) == { + "mobile_app_bobs_tablet": "binary_sensor.bobs_tablet_is_interactive" + } + + +def _user_id(hass: HomeAssistant) -> str: + state = hass.states.get("person.test_user") + assert state is not None + return str(state.attributes["user_id"]) + + +async def test_recipient_form_keeps_device_settings_and_sets_send_when_idle(hass: HomeAssistant) -> None: + hass_api = HomeAssistantAPI(hass) + register_mobile_app(hass_api, person="person.bob", device_name="Bob Phone") + register_mobile_app(hass_api, person="person.bob", device_name="Bob Laptop") + entry = MockConfigEntry( + domain=DOMAIN, + data={"recipients_discovery": False}, + options={}, + subentries_data=[ + ConfigSubentryData( + data={ + "person": "person.bob", + "mobile_devices": [ + {"mobile_app_id": LAPTOP, "enabled": True, "in_use_entity": LAPTOP_SENSOR, "send_when_idle": True} + ], + }, + subentry_type=SUBENTRY_TYPE_RECIPIENT, + title="person.bob", + unique_id="person.bob", + ) + ], + ) + entry.add_to_hass(hass) + assert await async_setup_component( + hass, DOMAIN, {DOMAIN: {"delivery": {"testing": {"transport": "generic", "action": "notify.send_message"}}}} + ) + await hass.async_block_till_done() + (subentry,) = [s for s in entry.subentries.values() if s.subentry_type == SUBENTRY_TYPE_RECIPIENT] + + result = await hass.config_entries.subentries.async_init( + (entry.entry_id, SUBENTRY_TYPE_RECIPIENT), context={"source": SOURCE_RECONFIGURE, "subentry_id": subentry.subentry_id} + ) + suggested = {str(k): k.description["suggested_value"] for k in result["data_schema"].schema if k.description} + assert suggested["send_when_idle"] == [LAPTOP] + + result = await hass.config_entries.subentries.async_configure( + result["flow_id"], + {"enabled": True, "mobile_discovery": True, "mobile_devices": [PHONE, LAPTOP], "send_when_idle": [PHONE]}, + ) + assert result["type"] == FlowResultType.ABORT + await hass.async_block_till_done() + assert {d["mobile_app_id"]: d for d in subentry.data["mobile_devices"]} == { + PHONE: {"mobile_app_id": PHONE, "enabled": True, "send_when_idle": True}, + # set only in YAML, and kept + LAPTOP: {"mobile_app_id": LAPTOP, "enabled": True, "in_use_entity": LAPTOP_SENSOR}, + }