Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Forecast fix for Home Assistant >= 2024.4.0 #150

Merged
merged 6 commits into from
May 8, 2024
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
16 changes: 10 additions & 6 deletions .devcontainer.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "ludeeus/integration_blueprint",
"image": "mcr.microsoft.com/vscode/devcontainers/python:0-3.10-bullseye",
"image": "mcr.microsoft.com/devcontainers/python:1-3.12",
"postCreateCommand": "scripts/setup",
"forwardPorts": [
8123
Expand All @@ -17,17 +17,21 @@
"ms-python.python",
"github.vscode-pull-request-github",
"ryanluker.vscode-coverage-gutters",
"ms-python.vscode-pylance"
"ms-python.vscode-pylance",
"ms-python.black-formatter",
"ms-python.pylint"
],
"settings": {
"files.eol": "\n",
"editor.tabSize": 4,
"python.pythonPath": "/usr/bin/python3",
"python.analysis.autoSearchPaths": false,
"python.linting.pylintEnabled": true,
"python.linting.enabled": true,
"python.formatting.provider": "black",
"python.formatting.blackPath": "/usr/local/py-utils/bin/black",
"[python]": {
"editor.defaultFormatter": "ms-python.black-formatter"
},
"black-formatter.path": [
"/usr/local/py-utils/bin/black"
],
"editor.formatOnPaste": false,
"editor.formatOnSave": true,
"editor.formatOnType": true,
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ jobs:
uses: "actions/checkout@v4"

- name: "Set up Python"
uses: actions/setup-python@v4.6.1
uses: actions/setup-python@v5
with:
python-version: "3.10"
python-version-file: 'pyproject.toml'
cache: "pip"

- name: "Install requirements"
Expand Down
6 changes: 3 additions & 3 deletions .github/workflows/py-dead-code.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@ jobs:
echo "package=$(ls -F | grep \/$ | grep -v "scripts\|examples\|tests\|config" | sed -n "s/\///g;1p")" >> $GITHUB_ENV

- name: "Set up Python"
uses: actions/setup-python@v4
uses: actions/setup-python@v5
with:
python-version: '3.9'
python-version-file: 'pyproject.toml'

- name: "Cache pip"
uses: actions/cache@v3
uses: actions/cache@v4
with:
# This path is specific to Ubuntu
path: ~/.cache/pip
Expand Down
18 changes: 7 additions & 11 deletions .github/workflows/py-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,12 @@ jobs:
echo "package=$(ls -F | grep \/$ | grep -v "bin\|examples\|tests" | sed -n "s/\///g;1p")" >> $GITHUB_ENV

- name: "Set up Python"
uses: actions/setup-python@v4
uses: actions/setup-python@v5
with:
python-version: '3.11'
python-version-file: 'pyproject.toml'

- name: "Cache pip"
uses: actions/cache@v3
uses: actions/cache@v4
with:
# This path is specific to Ubuntu
path: ~/.cache/pip
Expand Down Expand Up @@ -63,21 +63,17 @@ jobs:
name: "Test package"
needs: lint
runs-on: ubuntu-latest
strategy:
max-parallel: 3
matrix:
python-version: ['3.9', '3.10', '3.11']
steps:
- name: "Checkout code"
uses: actions/checkout@v4

- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
python-version-file: 'pyproject.toml'

- name: "Cache pip"
uses: actions/cache@v3
uses: actions/cache@v4
with:
# This path is specific to Ubuntu
path: ~/.cache/pip
Expand Down
6 changes: 3 additions & 3 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,13 @@ jobs:

- name: "Set up Python"
if: env.release_version != '' && success()
uses: actions/setup-python@v4
uses: actions/setup-python@v5
with:
python-version: 3.9
python-version-file: 'pyproject.toml'

- name: "Cache pip"
if: env.release_version != '' && success()
uses: actions/cache@v3
uses: actions/cache@v4
with:
# This path is specific to Ubuntu
path: ~/.cache/pip
Expand Down
10 changes: 5 additions & 5 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,20 @@ repos:
language: script
files: ^(custom_components/.+/const\.py|requirements\.txt)$
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: v0.0.241
rev: v0.3.5
hooks:
- id: ruff
args:
- --fix
files: ^(custom_components|bin|tests)/.+\.py$
- repo: https://github.com/asottile/pyupgrade
rev: v3.3.1
rev: v3.15.2
hooks:
- id: pyupgrade
args: [ --py310-plus ]
args: [ --py312-plus ]
stages: [manual]
- repo: https://github.com/psf/black
rev: 23.1.0
rev: 24.3.0
hooks:
- id: black
args:
Expand All @@ -37,7 +37,7 @@ repos:
files: ^(custom_components|bin|tests)/.+\.py$
stages: [manual]
- repo: https://github.com/PyCQA/bandit
rev: 1.7.4
rev: 1.7.8
hooks:
- id: bandit
args:
Expand Down
67 changes: 34 additions & 33 deletions .ruff.toml
Original file line number Diff line number Diff line change
@@ -1,48 +1,49 @@
# The contents of this file is based on https://github.com/home-assistant/core/blob/dev/pyproject.toml

target-version = "py310"
target-version = "py312"

[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}
"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}
"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
"SIM117", # Merge with-statements that use the same scope
"SIM118", # Use {key} in {dict} instead of {key} in {dict}.keys()
"SIM201", # Use {left} != {right} instead of not {left} == {right}
"SIM212", # Use {a} if {a} else {b} instead of {b} if not {a} else {a}
"SIM300", # Yoda conditions. Use 'age == 42' instead of '42 == age'.
"SIM401", # Use get from dict with default instead of an if block
"T20", # flake8-print
"TRY004", # Prefer TypeError exception for invalid type
"RUF006", # Store a reference to the return value of asyncio.create_task
"UP", # pyupgrade
"W", # pycodestyle
"SIM105", # Use contextlib.suppress({exception}) instead of try-except-pass
"SIM117", # Merge with-statements that use the same scope
"SIM118", # Use {key} in {dict} instead of {key} in {dict}.keys()
"SIM201", # Use {left} != {right} instead of not {left} == {right}
"SIM212", # Use {a} if {a} else {b} instead of {b} if not {a} else {a}
"SIM300", # Yoda conditions. Use 'age == 42' instead of '42 == age'.
"SIM401", # Use get from dict with default instead of an if block
"T20", # flake8-print
"TRY004", # Prefer TypeError exception for invalid type
"RUF006", # Store a reference to the return value of asyncio.create_task
"UP", # pyupgrade
"W", # pycodestyle
]

ignore = [
"D202", # No blank lines allowed after function docstring
"D203", # 1 blank line required before class docstring
"D213", # Multi-line docstring summary should start at the second line
"D404", # First word of the docstring should not be This
"D406", # Section name should end with a newline
"D407", # Section name underlining
"D411", # Missing blank line before section
"E501", # line too long
"E731", # do not assign a lambda expression, use a def
"D202", # No blank lines allowed after function docstring
"D203", # 1 blank line required before class docstring
"D213", # Multi-line docstring summary should start at the second line
"D404", # First word of the docstring should not be This
"D406", # Section name should end with a newline
"D407", # Section name underlining
"D411", # Missing blank line before section
"E501", # line too long
"E731", # do not assign a lambda expression, use a def
]

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

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

[mccabe]
max-complexity = 25
[lint.mccabe]
max-complexity = 25
27 changes: 20 additions & 7 deletions custom_components/snowtire/binary_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,21 @@
from collections.abc import Callable
from datetime import datetime
import logging
from typing import Optional

import voluptuous as vol

from homeassistant.components.binary_sensor import BinarySensorEntity
from homeassistant.components.weather import (
ATTR_FORECAST,
ATTR_FORECAST_TEMP,
ATTR_FORECAST_TEMP_LOW,
ATTR_FORECAST_TIME,
ATTR_WEATHER_TEMPERATURE,
DOMAIN as WEATHER,
SERVICE_GET_FORECASTS,
WeatherEntityFeature,
)
from homeassistant.const import (
ATTR_SUPPORTED_FEATURES,
CONF_NAME,
CONF_UNIQUE_ID,
EVENT_HOMEASSISTANT_START,
Expand Down Expand Up @@ -89,7 +90,7 @@ class SnowtireBinarySensor(BinarySensorEntity):

def __init__(
self,
unique_id: Optional[str],
unique_id: str | None,
friendly_name: str,
weather_entity: str,
days: int,
Expand Down Expand Up @@ -140,8 +141,8 @@ def icon(self):

@staticmethod
def _temp2c(
temperature: Optional[float], temperature_unit: Optional[str]
) -> Optional[float]:
temperature: float | None, temperature_unit: str | None
) -> float | None:
"""Convert weather temperature to Celsius degree."""
if temperature is not None and temperature_unit != TEMP_CELSIUS:
temperature = TemperatureConverter.convert(
Expand All @@ -161,9 +162,21 @@ async def async_update(
f"Unable to find an entity called {self._weather_entity}"
)

if (
wdata.attributes.get(ATTR_SUPPORTED_FEATURES)
is not WeatherEntityFeature.FORECAST_DAILY
):
raise HomeAssistantError("Weather entity doesn't support 'daily' forecast")

tmpu = self.hass.config.units.temperature_unit
temp = wdata.attributes.get(ATTR_WEATHER_TEMPERATURE)
forecast = wdata.attributes.get(ATTR_FORECAST)
forecast = await self.hass.services.async_call(
WEATHER,
SERVICE_GET_FORECASTS,
{"type": "daily", "entity_id": [self._weather_entity]},
blocking=True,
return_response=True,
)

if forecast is None:
raise HomeAssistantError(
Expand All @@ -180,7 +193,7 @@ async def async_update(

_LOGGER.debug("Inspect weather forecast from %s till %s", cur_date, stop_date)
temp = [self._temp2c(temp, tmpu)]
for fcast in forecast:
for fcast in forecast[self._weather_entity]["forecast"]:
fc_date = fcast.get(ATTR_FORECAST_TIME)
if isinstance(fc_date, int):
fc_date = dt_util.as_local(
Expand Down
7 changes: 2 additions & 5 deletions custom_components/snowtire/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,6 @@
"documentation": "https://github.com/Limych/ha-snowtire",
"iot_class": "calculated",
"issue_tracker": "https://github.com/Limych/ha-snowtire/issues",
"requirements": [
"colorlog==6.7.0",
"ruff==0.1.1"
],
"requirements": [],
"version": "1.4.7-alpha"
}
}
2 changes: 1 addition & 1 deletion hacs.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "Snowtire Sensor",
"filename": "snowtire.zip",
"hide_default_branch": true,
"homeassistant": "2023.1.0",
"homeassistant": "2024.4",
"render_readme": true,
"zip_release": true
}
2 changes: 1 addition & 1 deletion pylintrc
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ 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
load-plugins=pylint_strict_informational
fail-on=I
persistent=no
extension-pkg-whitelist=ciso8601

Expand Down
Loading
Loading