Skip to content

Commit

Permalink
new ruff rules applied (#160)
Browse files Browse the repository at this point in the history
  • Loading branch information
maciej-or authored Apr 12, 2024
1 parent b9a34db commit 56d6ecf
Show file tree
Hide file tree
Showing 11 changed files with 113 additions and 74 deletions.
3 changes: 2 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
- Install Ruff extension and select ruff as default formatter in vscode settings
- Code must follow [Home Assistant code style guidelines](https://developers.home-assistant.io/docs/development_guidelines)
- Line length limit must be 120 characters - `"python.formatting.blackArgs": ["--line-length", "120"]` in .vscode/settings.json
- Line length limit must be 120 characters
12 changes: 5 additions & 7 deletions custom_components/hikvision_next/__init__.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
"""hikvision component"""
"""hikvision component."""

from __future__ import annotations

import asyncio
import contextlib
import logging
from typing import Hashable

from httpx import TimeoutException

Expand Down Expand Up @@ -88,7 +88,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:


async def async_remove_config_entry_device(hass: HomeAssistant, config_entry, device_entry) -> bool:
"""Delete device if not entities"""
"""Delete device if not entities."""
if not device_entry.via_device_id:
_LOGGER.error(
"You cannot delete the NVR device via the device delete method. Please remove the integration instead"
Expand All @@ -112,10 +112,8 @@ async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
# Reset alarm server after it has been set
if config[DATA_SET_ALARM_SERVER]:
isapi = config[DATA_ISAPI]
try:
with contextlib.contextlib(Exception):
await isapi.set_alarm_server("http://0.0.0.0:80", "/")
except Exception: # pylint: disable=broad-except
pass

if unload_ok:
hass.data[DOMAIN].pop(entry.entry_id)
Expand All @@ -124,7 +122,7 @@ async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:


def get_first_instance_unique_id(hass: HomeAssistant) -> int:
"""Get entry unique_id for first instance of integration"""
"""Get entry unique_id for first instance of integration."""
entry = [entry for entry in hass.config_entries.async_entries(DOMAIN) if not entry.disabled_by][0]
return entry.unique_id

Expand Down
1 change: 1 addition & 0 deletions custom_components/hikvision_next/binary_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ class EventBinarySensor(BinarySensorEntity):
_attr_is_on = False

def __init__(self, isapi, device_id: int, event: EventInfo) -> None:
"""Initialize."""
self.entity_id = ENTITY_ID_FORMAT.format(event.unique_id)
self._attr_unique_id = self.entity_id
self._attr_name = f"{EVENTS[event.id]['label']}{' ' + str(event.io_port_id) if event.io_port_id != 0 else ''}"
Expand Down
3 changes: 2 additions & 1 deletion custom_components/hikvision_next/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ class HikvisionFlowHandler(ConfigFlow, domain=DOMAIN):
_reauth_entry: ConfigEntry | None = None

async def get_schema(self, user_input: dict[str, Any]):
"""Get schema with default values or entered by user"""
"""Get schema with default values or entered by user."""

local_ip = await async_get_source_ip(self.hass)
return vol.Schema(
{
Expand Down
19 changes: 9 additions & 10 deletions custom_components/hikvision_next/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@

from __future__ import annotations

import asyncio
from datetime import timedelta
import logging

import async_timeout

from homeassistant.components.switch import ENTITY_ID_FORMAT
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
Expand All @@ -22,10 +21,10 @@


class EventsCoordinator(DataUpdateCoordinator):
"""Manage fetching events state from NVR or camera"""
"""Manage fetching events state from NVR or camera."""

def __init__(self, hass: HomeAssistant, isapi: ISAPI) -> None:
"""Initialize"""
"""Initialize."""
self.isapi = isapi

super().__init__(
Expand All @@ -36,8 +35,8 @@ def __init__(self, hass: HomeAssistant, isapi: ISAPI) -> None:
)

async def _async_update_data(self):
"""Update data via ISAPI"""
async with async_timeout.timeout(30):
"""Update data via ISAPI."""
async with asyncio.timeout(30):
data = {}

# Get camera event status
Expand Down Expand Up @@ -77,10 +76,10 @@ async def _async_update_data(self):


class SecondaryCoordinator(DataUpdateCoordinator):
"""Manage fetching events state from NVR"""
"""Manage fetching events state from NVR."""

def __init__(self, hass: HomeAssistant, isapi: ISAPI) -> None:
"""Initialize"""
"""Initialize."""
self.isapi = isapi

super().__init__(
Expand All @@ -91,8 +90,8 @@ def __init__(self, hass: HomeAssistant, isapi: ISAPI) -> None:
)

async def _async_update_data(self):
"""Update data via ISAPI"""
async with async_timeout.timeout(20):
"""Update data via ISAPI."""
async with asyncio.timeout(20):
data = {}
try:
if self.isapi.device_info.support_holiday_mode:
Expand Down
13 changes: 7 additions & 6 deletions custom_components/hikvision_next/diagnostics.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Diagnostics support for Wiser"""
"""Diagnostics support for Wiser."""

from __future__ import annotations

import inspect
Expand Down Expand Up @@ -112,8 +113,7 @@ def to_json(obj):
"""Convert object to json."""
result = json.dumps(obj, cls=ObjectEncoder, sort_keys=True, indent=2)
result = json.loads(result)
result = anonymise_data(result)
return result
return anonymise_data(result)


def anonymise_data(data):
Expand All @@ -128,12 +128,13 @@ class ObjectEncoder(json.JSONEncoder):
"""Class to encode object to json."""

def default(self, o):
"""Implement encoding logic."""
if hasattr(o, "to_json"):
return self.default(o.to_json())

if hasattr(o, "__dict__"):
data = dict(
(key, value)
data = {
key: value
for key, value in inspect.getmembers(o)
if not key.startswith("__")
and not inspect.isabstract(value)
Expand All @@ -144,6 +145,6 @@ def default(self, o):
and not inspect.ismethod(value)
and not inspect.ismethoddescriptor(value)
and not inspect.isroutine(value)
)
}
return self.default(data)
return o
Loading

0 comments on commit 56d6ecf

Please sign in to comment.