Move shared constant in ios (#125748)

This commit is contained in:
epenet 2024-09-11 16:07:42 +02:00 committed by GitHub
parent 29311c7eb8
commit e140a2980b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 77 additions and 52 deletions

View File

@ -19,6 +19,16 @@ from homeassistant.helpers.typing import ConfigType
from homeassistant.util.json import load_json_object from homeassistant.util.json import load_json_object
from .const import ( from .const import (
ATTR_BATTERY,
ATTR_BATTERY_LEVEL,
ATTR_BATTERY_STATE,
ATTR_DEVICE,
ATTR_DEVICE_ID,
ATTR_DEVICE_NAME,
ATTR_DEVICE_PERMANENT_ID,
ATTR_DEVICE_SYSTEM_VERSION,
ATTR_DEVICE_TYPE,
BATTERY_STATES,
CONF_ACTION_BACKGROUND_COLOR, CONF_ACTION_BACKGROUND_COLOR,
CONF_ACTION_ICON, CONF_ACTION_ICON,
CONF_ACTION_ICON_COLOR, CONF_ACTION_ICON_COLOR,
@ -64,21 +74,14 @@ BEHAVIORS = [ATTR_DEFAULT_BEHAVIOR, ATTR_TEXT_INPUT_BEHAVIOR]
ATTR_LAST_SEEN_AT = "lastSeenAt" ATTR_LAST_SEEN_AT = "lastSeenAt"
ATTR_DEVICE = "device"
ATTR_PUSH_TOKEN = "pushToken" ATTR_PUSH_TOKEN = "pushToken"
ATTR_APP = "app" ATTR_APP = "app"
ATTR_PERMISSIONS = "permissions" ATTR_PERMISSIONS = "permissions"
ATTR_PUSH_ID = "pushId" ATTR_PUSH_ID = "pushId"
ATTR_DEVICE_ID = "deviceId"
ATTR_PUSH_SOUNDS = "pushSounds" ATTR_PUSH_SOUNDS = "pushSounds"
ATTR_BATTERY = "battery"
ATTR_DEVICE_NAME = "name"
ATTR_DEVICE_LOCALIZED_MODEL = "localizedModel" ATTR_DEVICE_LOCALIZED_MODEL = "localizedModel"
ATTR_DEVICE_MODEL = "model" ATTR_DEVICE_MODEL = "model"
ATTR_DEVICE_PERMANENT_ID = "permanentID"
ATTR_DEVICE_SYSTEM_VERSION = "systemVersion"
ATTR_DEVICE_TYPE = "type"
ATTR_DEVICE_SYSTEM_NAME = "systemName" ATTR_DEVICE_SYSTEM_NAME = "systemName"
ATTR_APP_BUNDLE_IDENTIFIER = "bundleIdentifier" ATTR_APP_BUNDLE_IDENTIFIER = "bundleIdentifier"
@ -90,20 +93,6 @@ ATTR_NOTIFICATIONS_PERMISSION = "notifications"
PERMISSIONS = [ATTR_LOCATION_PERMISSION, ATTR_NOTIFICATIONS_PERMISSION] PERMISSIONS = [ATTR_LOCATION_PERMISSION, ATTR_NOTIFICATIONS_PERMISSION]
ATTR_BATTERY_STATE = "state"
ATTR_BATTERY_LEVEL = "level"
ATTR_BATTERY_STATE_UNPLUGGED = "Not Charging"
ATTR_BATTERY_STATE_CHARGING = "Charging"
ATTR_BATTERY_STATE_FULL = "Full"
ATTR_BATTERY_STATE_UNKNOWN = "Unknown"
BATTERY_STATES = [
ATTR_BATTERY_STATE_UNPLUGGED,
ATTR_BATTERY_STATE_CHARGING,
ATTR_BATTERY_STATE_FULL,
ATTR_BATTERY_STATE_UNKNOWN,
]
ATTR_DEVICES = "devices" ATTR_DEVICES = "devices"

View File

@ -2,6 +2,28 @@
DOMAIN = "ios" DOMAIN = "ios"
ATTR_BATTERY = "battery"
ATTR_BATTERY_LEVEL = "level"
ATTR_BATTERY_STATE = "state"
ATTR_BATTERY_STATE_UNPLUGGED = "Not Charging"
ATTR_BATTERY_STATE_CHARGING = "Charging"
ATTR_BATTERY_STATE_FULL = "Full"
ATTR_BATTERY_STATE_UNKNOWN = "Unknown"
BATTERY_STATES = [
ATTR_BATTERY_STATE_UNPLUGGED,
ATTR_BATTERY_STATE_CHARGING,
ATTR_BATTERY_STATE_FULL,
ATTR_BATTERY_STATE_UNKNOWN,
]
ATTR_DEVICE = "device"
ATTR_DEVICE_ID = "deviceId"
ATTR_DEVICE_NAME = "name"
ATTR_DEVICE_PERMANENT_ID = "permanentID"
ATTR_DEVICE_SYSTEM_VERSION = "systemVersion"
ATTR_DEVICE_TYPE = "type"
CONF_ACTION_NAME = "name" CONF_ACTION_NAME = "name"
CONF_ACTION_BACKGROUND_COLOR = "background_color" CONF_ACTION_BACKGROUND_COLOR = "background_color"
CONF_ACTION_LABEL = "label" CONF_ACTION_LABEL = "label"

View File

@ -20,7 +20,7 @@ from homeassistant.core import HomeAssistant
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
import homeassistant.util.dt as dt_util import homeassistant.util.dt as dt_util
from .. import ios from . import device_name_for_push_id, devices_with_push, enabled_push_ids
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -42,7 +42,7 @@ def log_rate_limits(
_LOGGER.log( _LOGGER.log(
level, level,
rate_limit_msg, rate_limit_msg,
ios.device_name_for_push_id(hass, target), device_name_for_push_id(hass, target),
rate_limits["successful"], rate_limits["successful"],
rate_limits["maximum"], rate_limits["maximum"],
rate_limits["errors"], rate_limits["errors"],
@ -60,7 +60,7 @@ def get_service(
# Need this to enable requirements checking in the app. # Need this to enable requirements checking in the app.
hass.config.components.add("ios.notify") hass.config.components.add("ios.notify")
if not ios.devices_with_push(hass): if not devices_with_push(hass):
return None return None
return iOSNotificationService() return iOSNotificationService()
@ -75,7 +75,7 @@ class iOSNotificationService(BaseNotificationService):
@property @property
def targets(self) -> dict[str, str]: def targets(self) -> dict[str, str]:
"""Return a dictionary of registered targets.""" """Return a dictionary of registered targets."""
return ios.devices_with_push(self.hass) return devices_with_push(self.hass)
def send_message(self, message: str = "", **kwargs: Any) -> None: def send_message(self, message: str = "", **kwargs: Any) -> None:
"""Send a message to the Lambda APNS gateway.""" """Send a message to the Lambda APNS gateway."""
@ -89,13 +89,13 @@ class iOSNotificationService(BaseNotificationService):
data[ATTR_TITLE] = kwargs.get(ATTR_TITLE) data[ATTR_TITLE] = kwargs.get(ATTR_TITLE)
if not (targets := kwargs.get(ATTR_TARGET)): if not (targets := kwargs.get(ATTR_TARGET)):
targets = ios.enabled_push_ids(self.hass) targets = enabled_push_ids(self.hass)
if kwargs.get(ATTR_DATA) is not None: if kwargs.get(ATTR_DATA) is not None:
data[ATTR_DATA] = kwargs.get(ATTR_DATA) data[ATTR_DATA] = kwargs.get(ATTR_DATA)
for target in targets: for target in targets:
if target not in ios.enabled_push_ids(self.hass): if target not in enabled_push_ids(self.hass):
_LOGGER.error("The target (%s) does not exist in .ios.conf", targets) _LOGGER.error("The target (%s) does not exist in .ios.conf", targets)
return return

View File

@ -18,8 +18,22 @@ from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.icon import icon_for_battery_level from homeassistant.helpers.icon import icon_for_battery_level
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from .. import ios from . import devices
from .const import DOMAIN from .const import (
ATTR_BATTERY,
ATTR_BATTERY_LEVEL,
ATTR_BATTERY_STATE,
ATTR_BATTERY_STATE_FULL,
ATTR_BATTERY_STATE_UNKNOWN,
ATTR_BATTERY_STATE_UNPLUGGED,
ATTR_DEVICE,
ATTR_DEVICE_ID,
ATTR_DEVICE_NAME,
ATTR_DEVICE_PERMANENT_ID,
ATTR_DEVICE_SYSTEM_VERSION,
ATTR_DEVICE_TYPE,
DOMAIN,
)
SENSOR_TYPES: tuple[SensorEntityDescription, ...] = ( SENSOR_TYPES: tuple[SensorEntityDescription, ...] = (
SensorEntityDescription( SensorEntityDescription(
@ -55,7 +69,7 @@ async def async_setup_entry(
"""Set up iOS from a config entry.""" """Set up iOS from a config entry."""
async_add_entities( async_add_entities(
IOSSensor(device_name, device, description) IOSSensor(device_name, device, description)
for device_name, device in ios.devices(hass).items() for device_name, device in devices(hass).items()
for description in SENSOR_TYPES for description in SENSOR_TYPES
) )
@ -76,7 +90,7 @@ class IOSSensor(SensorEntity):
self.entity_description = description self.entity_description = description
self._device = device self._device = device
device_id = device[ios.ATTR_DEVICE_ID] device_id = device[ATTR_DEVICE_ID]
self._attr_unique_id = f"{description.key}_{device_id}" self._attr_unique_id = f"{description.key}_{device_id}"
@property @property
@ -85,44 +99,44 @@ class IOSSensor(SensorEntity):
return DeviceInfo( return DeviceInfo(
identifiers={ identifiers={
( (
ios.DOMAIN, DOMAIN,
self._device[ios.ATTR_DEVICE][ios.ATTR_DEVICE_PERMANENT_ID], self._device[ATTR_DEVICE][ATTR_DEVICE_PERMANENT_ID],
) )
}, },
manufacturer="Apple", manufacturer="Apple",
model=self._device[ios.ATTR_DEVICE][ios.ATTR_DEVICE_TYPE], model=self._device[ATTR_DEVICE][ATTR_DEVICE_TYPE],
name=self._device[ios.ATTR_DEVICE][ios.ATTR_DEVICE_NAME], name=self._device[ATTR_DEVICE][ATTR_DEVICE_NAME],
sw_version=self._device[ios.ATTR_DEVICE][ios.ATTR_DEVICE_SYSTEM_VERSION], sw_version=self._device[ATTR_DEVICE][ATTR_DEVICE_SYSTEM_VERSION],
) )
@property @property
def extra_state_attributes(self) -> dict[str, Any]: def extra_state_attributes(self) -> dict[str, Any]:
"""Return the device state attributes.""" """Return the device state attributes."""
device = self._device[ios.ATTR_DEVICE] device = self._device[ATTR_DEVICE]
device_battery = self._device[ios.ATTR_BATTERY] device_battery = self._device[ATTR_BATTERY]
return { return {
"Battery State": device_battery[ios.ATTR_BATTERY_STATE], "Battery State": device_battery[ATTR_BATTERY_STATE],
"Battery Level": device_battery[ios.ATTR_BATTERY_LEVEL], "Battery Level": device_battery[ATTR_BATTERY_LEVEL],
"Device Type": device[ios.ATTR_DEVICE_TYPE], "Device Type": device[ATTR_DEVICE_TYPE],
"Device Name": device[ios.ATTR_DEVICE_NAME], "Device Name": device[ATTR_DEVICE_NAME],
"Device Version": device[ios.ATTR_DEVICE_SYSTEM_VERSION], "Device Version": device[ATTR_DEVICE_SYSTEM_VERSION],
} }
@property @property
def icon(self) -> str: def icon(self) -> str:
"""Return the icon to use in the frontend, if any.""" """Return the icon to use in the frontend, if any."""
device_battery = self._device[ios.ATTR_BATTERY] device_battery = self._device[ATTR_BATTERY]
battery_state = device_battery[ios.ATTR_BATTERY_STATE] battery_state = device_battery[ATTR_BATTERY_STATE]
battery_level = device_battery[ios.ATTR_BATTERY_LEVEL] battery_level = device_battery[ATTR_BATTERY_LEVEL]
charging = True charging = True
icon_state = DEFAULT_ICON_STATE icon_state = DEFAULT_ICON_STATE
if battery_state in ( if battery_state in (
ios.ATTR_BATTERY_STATE_FULL, ATTR_BATTERY_STATE_FULL,
ios.ATTR_BATTERY_STATE_UNPLUGGED, ATTR_BATTERY_STATE_UNPLUGGED,
): ):
charging = False charging = False
icon_state = f"{DEFAULT_ICON_STATE}-off" icon_state = f"{DEFAULT_ICON_STATE}-off"
elif battery_state == ios.ATTR_BATTERY_STATE_UNKNOWN: elif battery_state == ATTR_BATTERY_STATE_UNKNOWN:
battery_level = None battery_level = None
charging = False charging = False
icon_state = f"{DEFAULT_ICON_LEVEL}-unknown" icon_state = f"{DEFAULT_ICON_LEVEL}-unknown"
@ -135,17 +149,17 @@ class IOSSensor(SensorEntity):
def _update(self, device: dict[str, Any]) -> None: def _update(self, device: dict[str, Any]) -> None:
"""Get the latest state of the sensor.""" """Get the latest state of the sensor."""
self._device = device self._device = device
self._attr_native_value = self._device[ios.ATTR_BATTERY][ self._attr_native_value = self._device[ATTR_BATTERY][
self.entity_description.key self.entity_description.key
] ]
self.async_write_ha_state() self.async_write_ha_state()
async def async_added_to_hass(self) -> None: async def async_added_to_hass(self) -> None:
"""Handle addition to hass: register to dispatch.""" """Handle addition to hass: register to dispatch."""
self._attr_native_value = self._device[ios.ATTR_BATTERY][ self._attr_native_value = self._device[ATTR_BATTERY][
self.entity_description.key self.entity_description.key
] ]
device_id = self._device[ios.ATTR_DEVICE_ID] device_id = self._device[ATTR_DEVICE_ID]
self.async_on_remove( self.async_on_remove(
async_dispatcher_connect(self.hass, f"{DOMAIN}.{device_id}", self._update) async_dispatcher_connect(self.hass, f"{DOMAIN}.{device_id}", self._update)
) )