Skip to content

Commit

Permalink
Enable strict typing for ios (home-assistant#107382)
Browse files Browse the repository at this point in the history
  • Loading branch information
cdce8p authored Jan 12, 2024
1 parent 0257cd8 commit a9420bf
Show file tree
Hide file tree
Showing 6 changed files with 46 additions and 25 deletions.
1 change: 1 addition & 0 deletions .strict-typing
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,7 @@ homeassistant.components.input_select.*
homeassistant.components.input_text.*
homeassistant.components.integration.*
homeassistant.components.intent.*
homeassistant.components.ios.*
homeassistant.components.ipp.*
homeassistant.components.iqvia.*
homeassistant.components.islamic_prayer_times.*
Expand Down
28 changes: 15 additions & 13 deletions homeassistant/components/ios/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
"""Native Home Assistant iOS app component."""
import datetime
from http import HTTPStatus
from typing import Any

from aiohttp import web
import voluptuous as vol

from homeassistant import config_entries
Expand Down Expand Up @@ -218,7 +220,7 @@
PLATFORMS = [Platform.SENSOR]


def devices_with_push(hass):
def devices_with_push(hass: HomeAssistant) -> dict[str, str]:
"""Return a dictionary of push enabled targets."""
return {
device_name: device.get(ATTR_PUSH_ID)
Expand All @@ -227,7 +229,7 @@ def devices_with_push(hass):
}


def enabled_push_ids(hass):
def enabled_push_ids(hass: HomeAssistant) -> list[str]:
"""Return a list of push enabled target push IDs."""
return [
device.get(ATTR_PUSH_ID)
Expand All @@ -236,16 +238,16 @@ def enabled_push_ids(hass):
]


def devices(hass):
def devices(hass: HomeAssistant) -> dict[str, dict[str, Any]]:
"""Return a dictionary of all identified devices."""
return hass.data[DOMAIN][ATTR_DEVICES]
return hass.data[DOMAIN][ATTR_DEVICES] # type: ignore[no-any-return]


def device_name_for_push_id(hass, push_id):
def device_name_for_push_id(hass: HomeAssistant, push_id: str) -> str | None:
"""Return the device name for the push ID."""
for device_name, device in hass.data[DOMAIN][ATTR_DEVICES].items():
if device.get(ATTR_PUSH_ID) is push_id:
return device_name
return device_name # type: ignore[no-any-return]
return None


Expand Down Expand Up @@ -299,12 +301,12 @@ class iOSPushConfigView(HomeAssistantView):
url = "/api/ios/push"
name = "api:ios:push"

def __init__(self, push_config):
def __init__(self, push_config: dict[str, Any]) -> None:
"""Init the view."""
self.push_config = push_config

@callback
def get(self, request):
def get(self, request: web.Request) -> web.Response:
"""Handle the GET request for the push configuration."""
return self.json(self.push_config)

Expand All @@ -315,12 +317,12 @@ class iOSConfigView(HomeAssistantView):
url = "/api/ios/config"
name = "api:ios:config"

def __init__(self, config):
def __init__(self, config: dict[str, Any]) -> None:
"""Init the view."""
self.config = config

@callback
def get(self, request):
def get(self, request: web.Request) -> web.Response:
"""Handle the GET request for the user-defined configuration."""
return self.json(self.config)

Expand All @@ -331,18 +333,18 @@ class iOSIdentifyDeviceView(HomeAssistantView):
url = "/api/ios/identify"
name = "api:ios:identify"

def __init__(self, config_path):
def __init__(self, config_path: str) -> None:
"""Initialize the view."""
self._config_path = config_path

async def post(self, request):
async def post(self, request: web.Request) -> web.Response:
"""Handle the POST request for device identification."""
try:
data = await request.json()
except ValueError:
return self.json_message("Invalid JSON", HTTPStatus.BAD_REQUEST)

hass = request.app["hass"]
hass: HomeAssistant = request.app["hass"]

data[ATTR_LAST_SEEN_AT] = datetime.datetime.now().isoformat()

Expand Down
13 changes: 8 additions & 5 deletions homeassistant/components/ios/notify.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

from http import HTTPStatus
import logging
from typing import Any

import requests

Expand All @@ -25,11 +26,13 @@
PUSH_URL = "https://ios-push.home-assistant.io/push"


def log_rate_limits(hass, target, resp, level=20):
def log_rate_limits(
hass: HomeAssistant, target: str, resp: dict[str, Any], level: int = 20
) -> None:
"""Output rate limit log line at given level."""
rate_limits = resp["rateLimits"]
resetsAt = dt_util.parse_datetime(rate_limits["resetsAt"])
resetsAtTime = resetsAt - dt_util.utcnow()
resetsAtTime = resetsAt - dt_util.utcnow() if resetsAt is not None else "---"
rate_limit_msg = (
"iOS push notification rate limits for %s: "
"%d sent, %d allowed, %d errors, "
Expand Down Expand Up @@ -69,13 +72,13 @@ def __init__(self) -> None:
"""Initialize the service."""

@property
def targets(self):
def targets(self) -> dict[str, str]:
"""Return a dictionary of registered targets."""
return ios.devices_with_push(self.hass)

def send_message(self, message="", **kwargs):
def send_message(self, message: str = "", **kwargs: Any) -> None:
"""Send a message to the Lambda APNS gateway."""
data = {ATTR_MESSAGE: message}
data: dict[str, Any] = {ATTR_MESSAGE: message}

# Remove default title from notifications.
if (
Expand Down
13 changes: 9 additions & 4 deletions homeassistant/components/ios/sensor.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
"""Support for Home Assistant iOS app sensors."""
from __future__ import annotations

from typing import Any

from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntity,
Expand Down Expand Up @@ -66,7 +68,10 @@ class IOSSensor(SensorEntity):
_attr_has_entity_name = True

def __init__(
self, device_name, device, description: SensorEntityDescription
self,
device_name: str,
device: dict[str, Any],
description: SensorEntityDescription,
) -> None:
"""Initialize the sensor."""
self.entity_description = description
Expand All @@ -92,7 +97,7 @@ def device_info(self) -> DeviceInfo:
)

@property
def extra_state_attributes(self):
def extra_state_attributes(self) -> dict[str, Any]:
"""Return the device state attributes."""
device = self._device[ios.ATTR_DEVICE]
device_battery = self._device[ios.ATTR_BATTERY]
Expand All @@ -105,7 +110,7 @@ def extra_state_attributes(self):
}

@property
def icon(self):
def icon(self) -> str:
"""Return the icon to use in the frontend, if any."""
device_battery = self._device[ios.ATTR_BATTERY]
battery_state = device_battery[ios.ATTR_BATTERY_STATE]
Expand All @@ -128,7 +133,7 @@ def icon(self):
return icon_for_battery_level(battery_level=battery_level, charging=charging)

@callback
def _update(self, device):
def _update(self, device: dict[str, Any]) -> None:
"""Get the latest state of the sensor."""
self._device = device
self._attr_native_value = self._device[ios.ATTR_BATTERY][
Expand Down
6 changes: 3 additions & 3 deletions homeassistant/util/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ def json_loads_object(__obj: bytes | bytearray | memoryview | str) -> JsonObject


def load_json(
filename: str | PathLike,
filename: str | PathLike[str],
default: JsonValueType = _SENTINEL, # type: ignore[assignment]
) -> JsonValueType:
"""Load JSON data from a file.
Expand All @@ -89,7 +89,7 @@ def load_json(


def load_json_array(
filename: str | PathLike,
filename: str | PathLike[str],
default: JsonArrayType = _SENTINEL, # type: ignore[assignment]
) -> JsonArrayType:
"""Load JSON data from a file and return as list.
Expand All @@ -109,7 +109,7 @@ def load_json_array(


def load_json_object(
filename: str | PathLike,
filename: str | PathLike[str],
default: JsonObjectType = _SENTINEL, # type: ignore[assignment]
) -> JsonObjectType:
"""Load JSON data from a file and return as dict.
Expand Down
10 changes: 10 additions & 0 deletions mypy.ini
Original file line number Diff line number Diff line change
Expand Up @@ -2091,6 +2091,16 @@ disallow_untyped_defs = true
warn_return_any = true
warn_unreachable = true

[mypy-homeassistant.components.ios.*]
check_untyped_defs = true
disallow_incomplete_defs = true
disallow_subclassing_any = true
disallow_untyped_calls = true
disallow_untyped_decorators = true
disallow_untyped_defs = true
warn_return_any = true
warn_unreachable = true

[mypy-homeassistant.components.ipp.*]
check_untyped_defs = true
disallow_incomplete_defs = true
Expand Down

0 comments on commit a9420bf

Please sign in to comment.