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

Add pre-commit setup, SVG icon, HACS configuration #6

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
52 changes: 52 additions & 0 deletions .github/workflows/pre-commit.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
---
name: pre-commit
on:
pull_request:
push:
jobs:
pre-commit:
runs-on: ubuntu-latest
env:
LOG_TO_CS: .github/logToCs.py
RAW_LOG: pre-commit.log
CS_XML: pre-commit.xml
steps:
- run: sudo apt-get update && sudo apt-get install cppcheck
if: false
- uses: actions/checkout@v4
- uses: actions/setup-python@v4
if: false
with:
cache: pip
python-version: 3.12.1
- run: python -m pip install pre-commit
- uses: actions/cache/restore@v4
with:
path: ~/.cache/pre-commit/
key: pre-commit-4|${{ env.pythonLocation }}|${{ hashFiles('.pre-commit-config.yaml')
}}
- name: Run pre-commit hooks
run: |
set -o pipefail
pre-commit gc
pre-commit run --show-diff-on-failure --color=always --all-files | tee ${RAW_LOG}
- name: Convert Raw Log to Annotations
uses: mdeweerd/[email protected]
if: ${{ failure() }}
with:
in: ${{ env.RAW_LOG }}
- uses: actions/cache/save@v4
if: ${{ always() }}
with:
path: ~/.cache/pre-commit/
key: pre-commit-4|${{ env.pythonLocation }}|${{ hashFiles('.pre-commit-config.yaml')
}}
- name: Provide log as artifact
uses: actions/upload-artifact@v4
if: ${{ always() }}
with:
name: precommit-logs
path: |
${{ env.RAW_LOG }}
${{ env.CS_XML }}
retention-days: 2
24 changes: 24 additions & 0 deletions .github/workflows/validate-hacs.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
---
name: Validate with hassfest

on:
push:
pull_request:
schedule:
- cron: 0 0 * * *

jobs:
validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: home-assistant/actions/hassfest@master
hacs:
name: HACS Action
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: HACS Action
uses: hacs/action@main
with:
category: integration
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
*.egg-info/
*.pyc
*.sublime-project
*.sublime-workspace
__pycache__
dist/
home-assistant-historical-sensor.sublime-workspace
Expand Down
112 changes: 111 additions & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,4 +1,33 @@
---
files: ^(.*\.(py|json|md|sh|yaml|cfg|txt))$
exclude: ^(\.[^/]*cache/.*|.*/_user.py|.github/logToCs.py)$
repos:
- repo: https://github.com/verhovsky/pyupgrade-docs
rev: v0.3.0
hooks:
- id: pyupgrade-docs

- repo: https://github.com/executablebooks/mdformat
# Do this before other tools "fixing" the line endings
rev: 0.7.17
hooks:
- id: mdformat
name: Format Markdown
entry: mdformat # Executable to run, with fixed options
language: python
types: [markdown]
args: [--wrap, '75', --number]
additional_dependencies:
- mdformat-toc
- mdformat-beautysh
# -mdformat-shfmt
# -mdformat-tables
- mdformat-config
- mdformat-black
- mdformat-web
- mdformat-gfm
- setuptools

- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
hooks:
Expand All @@ -12,6 +41,10 @@ repos:
- id: check-toml
# - id: check-yaml
- id: debug-statements
- id: check-executables-have-shebangs
- id: check-shebang-scripts-are-executable
- id: fix-byte-order-marker
- id: check-case-conflict

- repo: https://github.com/asottile/pyupgrade
rev: v3.15.0
Expand All @@ -20,7 +53,7 @@ repos:
args: ['--py311-plus']

- repo: https://github.com/pycqa/isort
rev: 5.13.0
rev: 5.13.2
hooks:
- id: isort
args: ['--profile', 'black']
Expand All @@ -29,3 +62,80 @@ repos:
rev: 23.12.1
hooks:
- id: black

- repo: https://github.com/adrienverge/yamllint.git
rev: v1.33.0
hooks:
- id: yamllint
args:
- --no-warnings
- -d
- '{extends: relaxed, rules: {line-length: {max: 90}}}'

- repo: https://github.com/asottile/pyupgrade
rev: v3.15.0
hooks:
- id: pyupgrade
args:
- --py310-plus

- repo: https://github.com/Lucas-C/pre-commit-hooks-bandit
rev: v1.0.6
hooks:
- id: python-bandit-vulnerability-check

- repo: https://github.com/fsouza/autoflake8
rev: v0.4.1
hooks:
- id: autoflake8
args:
- -i
- -r
- --expand-star-imports
- custom_components

- repo: https://github.com/PyCQA/flake8
rev: 6.1.0
hooks:
- id: flake8
additional_dependencies:
# - pyproject-flake8>=0.0.1a5
- flake8-bugbear>=22.7.1
- flake8-comprehensions>=3.10.1
- flake8-2020>=1.7.0
- mccabe>=0.7.0
- pycodestyle>=2.9.1
- pyflakes>=2.5.0

- repo: https://github.com/PyCQA/isort
rev: 5.13.2
hooks:
- id: isort

- repo: https://github.com/codespell-project/codespell
rev: v2.2.6
hooks:
- id: codespell
args:
# - --builtin=clear,rare,informal,usage,code,names,en-GB_to_en-US
- --builtin=clear,rare,informal,usage,code,names
- --ignore-words-list=hass,master
- --skip="./.*"
- --quiet-level=2
- repo: https://github.com/pylint-dev/pylint
rev: v3.0.3
hooks:
- id: pylint
additional_dependencies:
- homeassistant-stubs
- sqlalchemy
- pyyaml

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.7.1
hooks:
- id: mypy
additional_dependencies:
- homeassistant-stubs
- sqlalchemy
- pyyaml
2 changes: 1 addition & 1 deletion Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ name = "pypi"
[packages]

[dev-packages]
# homeassistant-historical-sensor = {editable = true, path = "."}
black = "*"
build = "*"
homeassistant = ">=2024.1.0"
homeassistant-historical-sensor = {editable = true, path = "."}
ipdb = "*"
ipython = "*"
isort = "*"
Expand Down
8 changes: 3 additions & 5 deletions custom_components/delorian/manifest.json
Original file line number Diff line number Diff line change
@@ -1,18 +1,16 @@
{
"domain": "delorian",
"name": "Delorian - Testing integration for historical sensors",
"after_dependencies": ["recorder"],
"codeowners": [
"@ldotlopez"
],
"dependencies": [
"recorder"
],
"config_flow": true,
"documentation": "https://github.com/ldotlopez/ha-historical-sensor",
"iot_class": "cloud_polling",
"issue_tracker": "https://github.com/ldotlopez/ha-historical-sensor/issues",
"requirements": [
"homeassistant-historical-sensor==2.0.0rc4"
"homeassistant-historical-sensor==3.0.0a1"
],
"version": "2.0.0rc4"
"version": "3.0.0a1"
}
45 changes: 26 additions & 19 deletions custom_components/delorian/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,10 @@
# Important methods include comments about code itself and reasons behind them
#

import itertools
import math
import statistics
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo

from homeassistant.components.recorder.models import StatisticData, StatisticMetaData
from homeassistant.components.sensor import SensorDeviceClass, SensorEntity
Expand All @@ -41,6 +42,7 @@
HistoricalState,
PollUpdateMixin,
)
from homeassistant_historical_sensor.state import group_by_interval

from .api import API
from .const import DOMAIN, NAME
Expand Down Expand Up @@ -92,18 +94,29 @@ async def async_update_historical(self):
# This functions is equivaled to the `Sensor.async_update` from
# HomeAssistant core
#
# Important: You must provide datetime with tzinfo
# Important: ts is in UTC

hist_states = [
upstream_data = self.api.fetch(
start=datetime.now() - timedelta(days=3), step=timedelta(minutes=15)
)

upstream_data_with_timestamps = [
(
dt.timestamp() if dt.tzinfo else dtutil.as_local(dt).timestamp(),
state,
)
for (dt, state) in upstream_data
]

historical_states = [
HistoricalState(
state=state,
dt=dtutil.as_local(dt), # Add tzinfo, required by HistoricalSensor
)
for (dt, state) in self.api.fetch(
start=datetime.now() - timedelta(days=3), step=timedelta(minutes=15)
ts=ts,
)
for (ts, state) in upstream_data_with_timestamps
]
self._attr_historical_states = hist_states

self._attr_historical_states = historical_states

@property
def statistic_id(self) -> str:
Expand Down Expand Up @@ -131,24 +144,18 @@ async def async_calculate_statistic_data(

accumulated = latest["sum"] if latest else 0

def hour_block_for_hist_state(hist_state: HistoricalState) -> datetime:
# XX:00:00 states belongs to previous hour block
if hist_state.dt.minute == 0 and hist_state.dt.second == 0:
dt = hist_state.dt - timedelta(hours=1)
return dt.replace(minute=0, second=0, microsecond=0)

else:
return hist_state.dt.replace(minute=0, second=0, microsecond=0)

ret = []
for dt, collection_it in itertools.groupby(
hist_states, key=hour_block_for_hist_state
for block_ts, collection_it in group_by_interval(
hist_states, granurality=60 * 60
):
collection = list(collection_it)

mean = statistics.mean([x.state for x in collection])
partial_sum = sum([x.state for x in collection])
accumulated = accumulated + partial_sum

dt = datetime.fromtimestamp(block_ts).replace(tzinfo=ZoneInfo("UTC"))

ret.append(
StatisticData(
start=dt,
Expand Down
40 changes: 40 additions & 0 deletions ha-historical-sensor.sublime-project
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
{
"folders":
[
{
"file_exclude_patterns": [
"*.pyc",
"*.swp",
"Pipfile.lock"
],
"folder_exclude_patterns": [
"*.egg-info",
".mypy_cache",
".venv",
"__pycache__",
"dist",
],
"follow_symlinks": true,
"path": ".",
}
],
"settings": {
"python_interpreter": "${project_path}/.venv/bin/python",

"sublack.black_command": "${project_path}/.venv/bin/black",
"sublack.black_on_save": true,

"isort.sort_on_save": false,

"SublimeLinter.linters.flake8.executable": "${project_path}/.venv/bin/flake8",
"SublimeLinter.linters.flake8.disable": false,

"SublimeLinter.linters.mypy.executable": "${project_path}/.venv/bin/mypy",
"SublimeLinter.linters.mypy.disable": false,
// "SublimeLinter.linters.mypy.args": ["--ignore-missing-imports"],

"SublimeLinter.linters.pycodestyle.executable": "${project_path}/.venv/bin/pycodestyle",
"SublimeLinter.linters.pycodestyle.disable": true,
}

}
8 changes: 8 additions & 0 deletions hacs.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"name": "Delorian - Testing integration for historical sensors",
"content_in_root": false,
"zip_release": false,
"render_readme": true,
"persistent_directory": "local",
"homeassistant": "2023.1"
}
Loading