Skip to content

Commit

Permalink
Version bumps and lint fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
Jc2k committed Jan 31, 2022
1 parent 3c6eebd commit 4bf26f8
Show file tree
Hide file tree
Showing 14 changed files with 518 additions and 449 deletions.
4 changes: 2 additions & 2 deletions aiohomekit/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
from __future__ import annotations

import argparse
from argparse import ArgumentParser, Namespace
Expand All @@ -23,7 +24,6 @@
import pathlib
import re
import sys
from typing import List, Optional

from .controller import Controller
from .exceptions import HomeKitException
Expand Down Expand Up @@ -405,7 +405,7 @@ def setup_parser_for_pairing(parser: ArgumentParser) -> None:
)


async def main(argv: Optional[List[str]] = None) -> None:
async def main(argv: list[str] | None = None) -> None:
argv = argv or sys.argv[1:]

parser = argparse.ArgumentParser(
Expand Down
6 changes: 3 additions & 3 deletions aiohomekit/controller/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,13 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
from __future__ import annotations

import json
from json.decoder import JSONDecodeError
import logging
import pathlib
import re
from typing import Dict

from ..const import BLE_TRANSPORT_SUPPORTED, IP_TRANSPORT_SUPPORTED
from ..exceptions import (
Expand Down Expand Up @@ -130,7 +130,7 @@ async def shutdown(self) -> None:
for p in self.pairings:
await self.pairings[p].close()

def load_pairing(self, alias: str, pairing_data: Dict[str, str]) -> AbstractPairing:
def load_pairing(self, alias: str, pairing_data: dict[str, str]) -> AbstractPairing:
"""
Loads a pairing instance from a pairing data dict.
"""
Expand All @@ -150,7 +150,7 @@ def load_pairing(self, alias: str, pairing_data: Dict[str, str]) -> AbstractPair
connection_type = pairing_data["Connection"]
raise NotImplementedError(f"{connection_type} support")

def get_pairings(self) -> Dict[str, IpPairing]:
def get_pairings(self) -> dict[str, IpPairing]:
"""
Returns a dict containing all pairings known to the controller.
Expand Down
7 changes: 4 additions & 3 deletions aiohomekit/crypto/chacha20poly1305.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,16 @@
Implements the ChaCha20 stream cipher and the Poly1350 authenticator. More information can be found on
https://tools.ietf.org/html/rfc7539. See HomeKit spec page 51.
"""
from typing import Tuple, Union

from __future__ import annotations

from cryptography.exceptions import InvalidTag
from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305


def chacha20_aead_encrypt(
aad: bytes, key: bytes, iv: bytes, constant: bytes, plaintext: bytes
) -> Tuple[bytearray, bytes]:
) -> tuple[bytearray, bytes]:
"""
The encrypt method for chacha20 aead as required by the Apple specification. The 96-bit nonce from RFC7539 is
formed from the constant and the initialisation vector.
Expand All @@ -53,7 +54,7 @@ def chacha20_aead_encrypt(

def chacha20_aead_decrypt(
aad: bytes, key: bytes, iv: bytes, constant: bytes, ciphertext: bytes
) -> Union[bool, bytearray]:
) -> bool | bytearray:
"""
The decrypt method for chacha20 aead as required by the Apple specification. The 96-bit nonce from RFC7539 is
formed from the constant and the initialisation vector.
Expand Down
23 changes: 12 additions & 11 deletions aiohomekit/model/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
from __future__ import annotations

import json
from typing import Any, Dict, Iterable, List, Optional
from typing import Any, Iterable

from aiohomekit.protocol.statuscodes import to_status_code

Expand All @@ -41,7 +42,7 @@

class Services:
def __init__(self):
self._services: List[Service] = []
self._services: list[Service] = []

def __iter__(self):
return iter(self._services)
Expand All @@ -53,10 +54,10 @@ def filter(
self,
*,
service_type: str = None,
characteristics: Dict[str, str] = None,
characteristics: dict[str, str] = None,
parent_service: Service = None,
child_service: Service = None,
order_by: Optional[List[str]] = None,
order_by: list[str] | None = None,
) -> Iterable[Service]:
matches = iter(self._services)

Expand Down Expand Up @@ -90,7 +91,7 @@ def first(
self,
*,
service_type: str = None,
characteristics: Dict[str, str] = None,
characteristics: dict[str, str] = None,
parent_service: Service = None,
child_service: Service = None,
) -> Service:
Expand All @@ -114,7 +115,7 @@ class Characteristics:
def __init__(self, services):
self._services = services

def iid(self, iid: int) -> Optional[Characteristic]:
def iid(self, iid: int) -> Characteristic | None:
for service in self._services:
for char in service.characteristics:
if char.iid == iid:
Expand All @@ -137,7 +138,7 @@ def create_with_info(
model: str,
serial_number: str,
firmware_revision: str,
) -> "Accessory":
) -> Accessory:
self = cls()

accessory_info = self.add_service(ServicesTypes.ACCESSORY_INFORMATION)
Expand Down Expand Up @@ -182,7 +183,7 @@ def available(self):
return all(s.available for s in self.services)

@classmethod
def create_from_dict(cls, data: Dict[str, Any]) -> "Accessory":
def create_from_dict(cls, data: dict[str, Any]) -> Accessory:
accessory = cls()
accessory.aid = data["aid"]

Expand Down Expand Up @@ -230,7 +231,7 @@ def get_next_id(self) -> int:
return self._next_id

def add_service(
self, service_type: str, name: Optional[str] = None, add_required: bool = False
self, service_type: str, name: str | None = None, add_required: bool = False
) -> Service:
service = Service(self, service_type, name=name, add_required=add_required)
self.services.append(service)
Expand All @@ -255,12 +256,12 @@ def __getitem__(self, idx):
return self.accessories[idx]

@classmethod
def from_file(cls, path) -> "Accessories":
def from_file(cls, path) -> Accessories:
with open(path) as fp:
return cls.from_list(json.load(fp))

@classmethod
def from_list(cls, accessories) -> "Accessories":
def from_list(cls, accessories) -> Accessories:
self = cls()
for accessory in accessories:
self.add_accessory(Accessory.create_from_dict(accessory))
Expand Down
11 changes: 6 additions & 5 deletions aiohomekit/model/characteristics/characteristic.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,13 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
from __future__ import annotations

import base64
import binascii
from decimal import ROUND_HALF_UP, Decimal, localcontext
from distutils.util import strtobool
from typing import TYPE_CHECKING, Any, Dict, Optional
from typing import TYPE_CHECKING, Any

from aiohomekit.exceptions import CharacteristicPermissionError, FormatError
from aiohomekit.protocol.statuscodes import HapStatusCode
Expand Down Expand Up @@ -59,7 +60,7 @@


class Characteristic:
def __init__(self, service: "Service", characteristic_type: str, **kwargs) -> None:
def __init__(self, service: Service, characteristic_type: str, **kwargs) -> None:
self.service = service
self.iid = service.accessory.get_next_id()
try:
Expand Down Expand Up @@ -111,10 +112,10 @@ def __init__(self, service: "Service", characteristic_type: str, **kwargs) -> No

def _get_configuration(
self,
kwargs: Dict[str, Any],
kwargs: dict[str, Any],
key: str,
default: Optional[Any] = None,
) -> Optional[Any]:
default: Any | None = None,
) -> Any | None:
if key in kwargs:
return kwargs[key]
if self.type not in characteristics:
Expand Down
19 changes: 10 additions & 9 deletions aiohomekit/protocol/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,11 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
from __future__ import annotations

from binascii import hexlify
import logging
from typing import Any, Dict, Generator, List, Tuple, Union
from typing import Any, Generator

from cryptography import exceptions as cryptography_exceptions
from cryptography.hazmat.primitives import serialization
Expand Down Expand Up @@ -89,7 +90,7 @@ def handle_state_step(tlv_dict, expected_state):
def perform_pair_setup_part1(
with_auth: bool = True,
) -> Generator[
Tuple[List[Tuple[int, bytearray]], List[int]], None, Tuple[bytearray, bytearray]
tuple[list[tuple[int, bytearray]], list[int]], None, tuple[bytearray, bytearray]
]:
"""
Performs a pair setup operation as described in chapter 4.7 page 39 ff.
Expand Down Expand Up @@ -177,7 +178,7 @@ def validate_mfi(session_key, response_tlv):

def perform_pair_setup_part2(
pin: str, ios_pairing_id: str, salt: bytearray, server_public_key: bytearray
) -> Generator[Tuple[List[Tuple[int, bytearray]], List[int]], None, Dict[str, str]]:
) -> Generator[tuple[list[tuple[int, bytearray]], list[int]], None, dict[str, str]]:
"""
Performs a pair setup operation as described in chapter 4.7 page 39 ff.
Expand Down Expand Up @@ -350,14 +351,14 @@ def perform_pair_setup_part2(


def get_session_keys(
pairing_data: Dict[str, Union[str, int, List[Any]]]
pairing_data: dict[str, str | int | list[Any]]
) -> Generator[
Union[
Tuple[List[Union[Tuple[int, bytearray], Tuple[int, bytes]]], List[int]],
Tuple[List[Tuple[int, bytearray]], List[int]],
],
(
tuple[list[tuple[int, bytearray] | tuple[int, bytes]], list[int]]
| tuple[list[tuple[int, bytearray]], list[int]]
),
None,
Tuple[bytes, bytes],
tuple[bytes, bytes],
]:
"""
HomeKit Controller state machine to perform a pair verify operation as described in chapter 4.8 page 47 ff.
Expand Down
10 changes: 5 additions & 5 deletions aiohomekit/protocol/tlv.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
from __future__ import annotations

import logging
from typing import Any, List, Optional, Union
from typing import Any

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -94,13 +96,11 @@ class TLV:
kTLVHAPParamHAPValidValuesRangeDescriptor = 0x12

@staticmethod
def decode_bytes(
bs: Union[bytearray, bytes], expected: Optional[List[int]] = None
) -> list:
def decode_bytes(bs: bytearray | bytes, expected: list[int] | None = None) -> list:
return TLV.decode_bytearray(bytearray(bs), expected)

@staticmethod
def decode_bytearray(ba: bytearray, expected: Optional[List[int]] = None) -> list:
def decode_bytearray(ba: bytearray, expected: list[int] | None = None) -> list:
result = []
# do not influence caller!
tail = ba.copy()
Expand Down
6 changes: 3 additions & 3 deletions aiohomekit/testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
from __future__ import annotations

import base64
import logging
from typing import Dict

from aiohomekit import exceptions
from aiohomekit.controller import Controller
Expand All @@ -37,7 +37,7 @@

class FakeDiscovery:
def __init__(
self, controller: "FakeController", device_id: str, accessories: Accessories
self, controller: FakeController, device_id: str, accessories: Accessories
):
self.controller = controller
self.device_id = device_id
Expand Down Expand Up @@ -195,7 +195,7 @@ def __init__(self, controller, pairing_data, accessories: Accessories):
self.connection.transport = "mock_transport"
self.connection.protocol = "mock_protocol"
self.accessories = accessories
self.pairing_data: Dict[str, AbstractPairing] = {}
self.pairing_data: dict[str, AbstractPairing] = {}
self.available = True

self.testing = PairingTester(self)
Expand Down
15 changes: 7 additions & 8 deletions aiohomekit/tlv8.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

from collections import abc
from dataclasses import field, fields
import enum
Expand All @@ -7,7 +9,6 @@
Any,
Callable,
ClassVar,
Dict,
Generic,
Iterable,
Sequence,
Expand Down Expand Up @@ -115,13 +116,11 @@ def deserialize_int_enum(value_type: type, value: bytes) -> enum.IntEnum:
return value_type(int_value)


def deserialize_tlv_struct(value_type: type, value: bytes) -> "TLVStruct":
def deserialize_tlv_struct(value_type: type, value: bytes) -> TLVStruct:
return value_type.decode(value)


def deserialize_typing_sequence(
value_type: type, value: bytes
) -> Sequence["TLVStruct"]:
def deserialize_typing_sequence(value_type: type, value: bytes) -> Sequence[TLVStruct]:
inner_type = value_type.__args__[0]

results = []
Expand Down Expand Up @@ -151,7 +150,7 @@ def serialize_int_enum(value_type: type, value: enum.IntEnum) -> bytes:
return serialize_u8(value_type, int(value))


def serialize_tlv_struct(value_type: type, value: "TLVStruct") -> bytes:
def serialize_tlv_struct(value_type: type, value: TLVStruct) -> bytes:
return value.encode()


Expand Down Expand Up @@ -256,7 +255,7 @@ def decode(cls: T, encoded_struct: bytes) -> T:
return cls(**kwargs)


DESERIALIZERS: Dict[type, DeserializerCallback] = {
DESERIALIZERS: dict[type, DeserializerCallback] = {
u8: deserialize_u8,
u16: deserialize_u16,
u32: deserialize_u32,
Expand All @@ -266,7 +265,7 @@ def decode(cls: T, encoded_struct: bytes) -> T:
abc.Sequence: deserialize_typing_sequence,
}

SERIALIZERS: Dict[type, SerializerCallback] = {
SERIALIZERS: dict[type, SerializerCallback] = {
u8: serialize_u8,
u16: serialize_u16,
u32: serialize_u32,
Expand Down
Loading

0 comments on commit 4bf26f8

Please sign in to comment.