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
24 changes: 6 additions & 18 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,17 +1,11 @@
repos:
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: v0.0.256
rev: v0.14.10
hooks:
- id: ruff
- id: ruff-check
args:
- --fix
- repo: https://github.com/psf/black
rev: 23.1.0
hooks:
- id: black
args:
- --quiet
files: ^((custom_components|tests)/.+)?[^/]+\.py$
- id: ruff-format
- repo: https://github.com/codespell-project/codespell
rev: v2.2.2
hooks:
Expand All @@ -21,15 +15,9 @@ repos:
- --skip="./.*,*.csv,*.json"
- --quiet-level=2
exclude_types: [csv, json]
- repo: https://github.com/PyCQA/isort
rev: 5.12.0
hooks:
- id: isort
- repo: https://github.com/pre-commit/mirrors-prettier
rev: v2.7.1
hooks:
- id: prettier
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.1.1
rev: v1.19.1
hooks:
- id: mypy
additional_dependencies:
- types-dateparser
23 changes: 16 additions & 7 deletions custom_components/intesisbox/intesisbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from __future__ import annotations

import asyncio
from asyncio import BaseTransport, ensure_future
from collections.abc import Callable
import logging

Expand Down Expand Up @@ -36,6 +35,16 @@

NULL_VALUES = ["-32768", "32768"]

background_tasks = set()


def ensure_background_task(coro):
"""Ensure background task is running."""
task = asyncio.ensure_future(coro)
background_tasks.add(task)
task.add_done_callback(background_tasks.discard)
return task


class IntesisBox(asyncio.Protocol):
"""Handles communication with an intesisbox device via WMP."""
Expand All @@ -47,7 +56,7 @@ def __init__(self, ip: str, port: int = 3310, loop=None):
self._mac = None
self._device: dict[str, str] = {}
self._connectionStatus = API_DISCONNECTED
self._transport: BaseTransport | None = None
self._transport: asyncio.BaseTransport | None = None
self._updateCallbacks: list[Callable[[], None]] = []
self._errorCallbacks: list[Callable[[str], None]] = []
self._errorMessage: str | None = None
Expand All @@ -65,11 +74,11 @@ def __init__(self, ip: str, port: int = 3310, loop=None):
self._setpoint_minimum: int | None = None
self._setpoint_maximum: int | None = None

def connection_made(self, transport: BaseTransport):
def connection_made(self, transport: asyncio.BaseTransport):
"""Asyncio callback for a successful connection."""
_LOGGER.debug("Connected to IntesisBox")
self._transport = transport
_ = asyncio.ensure_future(self.query_initial_state())
ensure_background_task(self.query_initial_state())

async def keep_alive(self):
"""Send a keepalive command to reset it's watchdog timer."""
Expand Down Expand Up @@ -128,8 +137,8 @@ def data_received(self, data):
if cmd == "ID":
self._parse_id_received(args)
self._connectionStatus = API_AUTHENTICATED
_ = asyncio.ensure_future(self.poll_status())
_ = asyncio.ensure_future(self.poll_ambtemp())
ensure_background_task(self.poll_status())
ensure_background_task(self.poll_ambtemp())
elif cmd == "CHN,1":
self._parse_change_received(args)
statusChanged = True
Expand Down Expand Up @@ -216,7 +225,7 @@ def connect(self):
_LOGGER.debug(
"Opening connection to IntesisBox %s:%s", self._ip, self._port
)
_ = ensure_future(coro, loop=self._eventLoop)
ensure_background_task(coro)
else:
_LOGGER.debug("Missing IP address or port.")
self._connectionStatus = API_DISCONNECTED
Expand Down
207 changes: 28 additions & 179 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,191 +1,33 @@
[tool.poetry]
[project]
name = "intesisbox"
version = "0.0.0"
description = "Home Assistant integration for Intesisbox devices"
authors = ["Your Name <you@example.com>"]
readme = "README.md"

[tool.poetry.dependencies]
python = "^3.11"
homeassistant = "^2023.3.6"


[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"

[tool.black]
extend-exclude = "/generated/"

[tool.isort]
# https://github.com/PyCQA/isort/wiki/isort-Settings
profile = "black"
# will group `import x` and `from x import` of the same module.
force_sort_within_sections = true
known_first_party = [
"homeassistant",
"tests",
]
forced_separate = [
"tests",
]
combine_as_imports = true

[tool.pylint.MAIN]
py-version = "3.10"
ignore = [
"tests",
]
# Use a conservative default here; 2 should speed up most setups and not hurt
# any too bad. Override on command line as appropriate.
jobs = 2
init-hook = """\
from pathlib import Path; \
import sys; \
from pylint.config import find_default_config_files; \
sys.path.append( \
str(Path(next(find_default_config_files())).parent.joinpath('pylint/plugins'))
) \
"""
load-plugins = [
"pylint.extensions.code_style",
"pylint.extensions.typing",
"hass_enforce_type_hints",
"hass_imports",
"hass_logger",
"pylint_per_file_ignores",
]
persistent = false
extension-pkg-allow-list = [
"av.audio.stream",
"av.stream",
"ciso8601",
"orjson",
"cv2",
]
fail-on = [
"I",
]

[tool.pylint.BASIC]
class-const-naming-style = "any"
good-names = [
"_",
"ev",
"ex",
"fp",
"i",
"id",
"j",
"k",
"Run",
"ip",
]

[tool.pylint."MESSAGES CONTROL"]
# Reasons disabled:
# format - handled by black
# locally-disabled - it spams too much
# duplicate-code - unavoidable
# cyclic-import - doesn't test if both import on load
# abstract-class-little-used - prevents from setting right foundation
# unused-argument - generic callbacks and setup methods create a lot of warnings
# too-many-* - are not enforced for the sake of readability
# too-few-* - same as too-many-*
# abstract-method - with intro of async there are always methods missing
# inconsistent-return-statements - doesn't handle raise
# too-many-ancestors - it's too strict.
# wrong-import-order - isort guards this
# consider-using-f-string - str.format sometimes more readable
# ---
# Pylint CodeStyle plugin
# consider-using-namedtuple-or-dataclass - too opinionated
# consider-using-assignment-expr - decision to use := better left to devs
disable = [
"format",
"abstract-method",
"cyclic-import",
"duplicate-code",
"inconsistent-return-statements",
"locally-disabled",
"not-context-manager",
"too-few-public-methods",
"too-many-ancestors",
"too-many-arguments",
"too-many-branches",
"too-many-instance-attributes",
"too-many-lines",
"too-many-locals",
"too-many-public-methods",
"too-many-return-statements",
"too-many-statements",
"too-many-boolean-expressions",
"unused-argument",
"wrong-import-order",
"consider-using-f-string",
"consider-using-namedtuple-or-dataclass",
"consider-using-assignment-expr",
]
enable = [
#"useless-suppression", # temporarily every now and then to clean them up
"use-symbolic-message-instead",
requires-python = ">=3.13.2, <3.14"
dependencies = [
"homeassistant>=2025.12.4",
]

[tool.pylint.REPORTS]
score = false

[tool.pylint.TYPECHECK]
ignored-classes = [
"_CountingAttr", # for attrs
]
mixin-class-rgx = ".*[Mm]ix[Ii]n"

[tool.pylint.FORMAT]
expected-line-ending-format = "LF"

[tool.pylint.EXCEPTIONS]
overgeneral-exceptions = [
"builtins.BaseException",
"builtins.Exception",
# "homeassistant.exceptions.HomeAssistantError", # too many issues
]

[tool.pylint.TYPING]
runtime-typing = false

[tool.pylint.CODE_STYLE]
max-line-length-suggestions = 72

[tool.pylint-per-file-ignores]
# hass-component-root-import: Tests test non-public APIs
# protected-access: Tests do often test internals a lot
# redefined-outer-name: Tests reference fixtures in the test function
"/tests/"="hass-component-root-import,protected-access,redefined-outer-name"

[tool.pytest.ini_options]
testpaths = [
"tests",
]
norecursedirs = [
".git",
"testing_config",
]
log_format = "%(asctime)s.%(msecs)03d %(levelname)-8s %(threadName)s %(name)s:%(filename)s:%(lineno)s %(message)s"
log_date_format = "%Y-%m-%d %H:%M:%S"
asyncio_mode = "auto"
filterwarnings = ["error::sqlalchemy.exc.SAWarning"]
asyncio_default_fixture_loop_scope = "function"
filterwarnings = []

[tool.ruff]
target-version = "py310"
target-version = "py313"

[tool.ruff.lint]
select = [
"B007", # Loop control variable {name} not used within loop body
"B014", # Exception handler with duplicate exception
"C", # complexity
"D", # docstrings
"E", # pycodestyle
"F", # pyflakes/autoflake
"ICN001", # import concentions; {name} should be imported as {asname}
"I", # isort
"PGH004", # Use specific rule codes when using noqa
"PLC0414", # Useless import alias. Import alias does not rename original package.
"SIM105", # Use contextlib.suppress({exception}) instead of try-except-pass
Expand All @@ -210,30 +52,37 @@ ignore = [
"D407", # Section name underlining
"E501", # line too long
"E731", # do not assign a lambda expression, use a def
# Ignored due to performance: https://github.com/charliermarsh/ruff/issues/2923
"UP038", # Use `X | Y` in `isinstance` call instead of `(X, Y)`
]

[tool.ruff.flake8-import-conventions.extend-aliases]
[tool.ruff.lint.flake8-import-conventions.extend-aliases]
voluptuous = "vol"
"homeassistant.helpers.area_registry" = "ar"
"homeassistant.helpers.config_validation" = "cv"
"homeassistant.helpers.device_registry" = "dr"
"homeassistant.helpers.entity_registry" = "er"
"homeassistant.helpers.issue_registry" = "ir"

[tool.ruff.flake8-pytest-style]
[tool.ruff.lint.flake8-pytest-style]
fixture-parentheses = false

[tool.ruff.pyupgrade]
[tool.ruff.lint.pyupgrade]
keep-runtime-typing = true

[tool.ruff.per-file-ignores]
[tool.ruff.lint.mccabe]
max-complexity = 25

# Allow for main entry & scripts to write to stdout
"homeassistant/__main__.py" = ["T201"]
"homeassistant/scripts/*" = ["T201"]
"script/*" = ["T20"]
[tool.ruff.lint.per-file-ignores]
"tests/*" = [
"D", # docstrings
]

[tool.ruff.mccabe]
max-complexity = 25
[tool.ruff.lint.isort]
force-sort-within-sections = true
known-first-party = [
"homeassistant",
"tests",
]
forced-separate = [
"tests",
]
combine-as-imports = true
Loading