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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 17 additions & 3 deletions custom_components/supernotify/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@
CONF_PRIORITY,
CONF_RECIPIENTS_DISCOVERY,
CONF_SELECTION,
CONF_SEND_WHEN_IDLE,
CONF_SENTENCE_COMMANDS,
CONF_SIZE,
CONF_SNAPSHOT_URL_LOCAL,
Expand Down Expand Up @@ -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))
Expand All @@ -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(
Expand All @@ -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},
Expand Down
10 changes: 10 additions & 0 deletions custom_components/supernotify/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"


Expand Down
24 changes: 23 additions & 1 deletion custom_components/supernotify/hass_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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 {
Expand All @@ -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:
Expand All @@ -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 `<webhook_id>_<sensor id>`, 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.

Expand Down Expand Up @@ -1018,17 +1031,26 @@ 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

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
Expand Down
22 changes: 22 additions & 0 deletions custom_components/supernotify/notification.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -47,6 +49,7 @@
DRY_RUN_LIVE,
DRY_RUN_SIMULATE,
INCLUSION_DEFAULT,
PRIORITY_CRITICAL,
PRIORITY_MEDIUM,
PRIORITY_VALUES,
TARGET_USE_FIXED,
Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -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:
Expand All @@ -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

Expand Down
27 changes: 27 additions & 0 deletions custom_components/supernotify/people.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
Expand Down Expand Up @@ -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 [
Expand Down
6 changes: 6 additions & 0 deletions custom_components/supernotify/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -116,6 +117,7 @@
CONF_FALLBACK,
CONF_HOUSEKEEPING,
CONF_HOUSEKEEPING_TIME,
CONF_IN_USE_ENTITY,
CONF_INCLUSION,
CONF_LEVEL,
CONF_LOAD,
Expand Down Expand Up @@ -148,6 +150,7 @@
CONF_SCENARIOS,
CONF_SELECTION,
CONF_SELECTION_RANK,
CONF_SEND_WHEN_IDLE,
CONF_SIZE,
CONF_SNAP_WAIT,
CONF_SNAPSHOT_URL_LOCAL,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
3 changes: 3 additions & 0 deletions custom_components/supernotify/services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,9 @@ notify:
force_resend:
selector:
boolean:
include_idle_devices:
selector:
boolean:
dry_run:
required: false
default: live
Expand Down
6 changes: 6 additions & 0 deletions custom_components/supernotify/translations/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -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."
Expand Down Expand Up @@ -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"
},
Expand All @@ -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}"
},
Expand Down
6 changes: 6 additions & 0 deletions custom_components/supernotify/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -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."
Expand Down Expand Up @@ -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"
},
Expand All @@ -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}"
},
Expand Down
Loading
Loading