├── requirements.txt ├── example.jpg ├── scripts ├── lint ├── check_dirty ├── run-in-env ├── update ├── develop ├── _common ├── install_requirements ├── update_requirements ├── setup ├── update_manifest ├── release ├── devcontainer └── gen_releasenotes ├── hacs.json ├── requirements-dev.txt ├── custom_components └── car_wash │ ├── translations │ ├── binary_sensor.en.json │ ├── binary_sensor.pl.json │ ├── binary_sensor.pt.json │ ├── binary_sensor.uk.json │ ├── binary_sensor.de.json │ ├── binary_sensor.ru.json │ └── binary_sensor.it.json │ ├── __init__.py │ ├── manifest.json │ ├── const.py │ └── binary_sensor.py ├── requirements-test.txt ├── config ├── bootstrap.sh └── configuration.yaml ├── CONTRIBUTING.md ├── info.md ├── pyproject.toml └── LICENSE.md /requirements.txt: -------------------------------------------------------------------------------- 1 | homeassistant>=2024.6.0 2 | pip>=21.3.1 3 | -------------------------------------------------------------------------------- /example.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Limych/ha-car_wash/HEAD/example.jpg -------------------------------------------------------------------------------- /scripts/lint: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -e 4 | 5 | cd "$(dirname "$0")/.." 6 | 7 | ruff format . 8 | ruff check . --fix 9 | -------------------------------------------------------------------------------- /hacs.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Car Wash", 3 | "hide_default_branch": true, 4 | "homeassistant": "2024.6.0", 5 | "render_readme": true 6 | } 7 | -------------------------------------------------------------------------------- /requirements-dev.txt: -------------------------------------------------------------------------------- 1 | -r requirements-test.txt 2 | black~=24.8 3 | packaging~=24.1 4 | pre-commit~=4.0 5 | PyGithub~=2.4 6 | pyupgrade~=3.17 7 | yamllint~=1.35 8 | -------------------------------------------------------------------------------- /custom_components/car_wash/translations/binary_sensor.en.json: -------------------------------------------------------------------------------- 1 | { 2 | "state": { 3 | "car_wash__": { 4 | "off": "Should not wash", 5 | "on": "Worth wash" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /custom_components/car_wash/translations/binary_sensor.pl.json: -------------------------------------------------------------------------------- 1 | { 2 | "state": { 3 | "car_wash__": { 4 | "off": "Nie należy myć", 5 | "on": "Warto umyć" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /custom_components/car_wash/translations/binary_sensor.pt.json: -------------------------------------------------------------------------------- 1 | { 2 | "state": { 3 | "car_wash__": { 4 | "off": "Não deve lavar", 5 | "on": "Pode lavar" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /custom_components/car_wash/translations/binary_sensor.uk.json: -------------------------------------------------------------------------------- 1 | { 2 | "state": { 3 | "car_wash__": { 4 | "off": "Не варто мити", 5 | "on": "Варто помити" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /custom_components/car_wash/translations/binary_sensor.de.json: -------------------------------------------------------------------------------- 1 | { 2 | "state": { 3 | "car_wash__": { 4 | "off": "Waschen sinnlos", 5 | "on": "Jetzt waschen" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /custom_components/car_wash/translations/binary_sensor.ru.json: -------------------------------------------------------------------------------- 1 | { 2 | "state": { 3 | "car_wash__": { 4 | "off": "Нет смысла мыть", 5 | "on": "Стоит помыть" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /custom_components/car_wash/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | The Car Wash binary sensor. 3 | 4 | For more details about this platform, please refer to the documentation at 5 | https://github.com/Limych/ha-car_wash/ 6 | """ 7 | -------------------------------------------------------------------------------- /custom_components/car_wash/translations/binary_sensor.it.json: -------------------------------------------------------------------------------- 1 | { 2 | "state": { 3 | "car_wash__": { 4 | "off": "Lavaggio sconsigliato", 5 | "on": "Procedi al lavaggio" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /scripts/check_dirty: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | [[ -z $(git ls-files --others --exclude-standard) ]] && exit 0 3 | 4 | echo -e '\n***** ERROR\nTests are leaving files behind. Please update the tests to avoid writing any files:' 5 | git ls-files --others --exclude-standard 6 | echo 7 | exit 1 8 | -------------------------------------------------------------------------------- /requirements-test.txt: -------------------------------------------------------------------------------- 1 | -r requirements.txt 2 | async-timeout 3 | asynctest~=0.13 4 | colorlog~=6.8 5 | flake8~=7.1 6 | flake8-docstrings~=1.7 7 | mypy~=1.11 8 | pylint~=3.3 9 | pylint-strict-informational==0.1 10 | pytest>=7.2 11 | pytest-cov>=3.0 12 | pytest-homeassistant-custom-component>=0.13 13 | tzdata 14 | ruff>=0.4 15 | -------------------------------------------------------------------------------- /config/bootstrap.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ROOT="$( cd "$( dirname "$(readlink -f "$0")" )/.." >/dev/null 2>&1 && pwd )" 4 | 5 | GITHUB_TOKEN=$(grep github_token ${ROOT}/secrets.yaml | cut -d' ' -f2) 6 | FILES=$(grep "{GITHUB_TOKEN}" ${ROOT}/requirements.txt | sed "s/{GITHUB_TOKEN}/${GITHUB_TOKEN}/g" | tr "\r\n" " ") 7 | 8 | [ -z "${FILES}" ] || python3 -m pip install --upgrade ${FILES} 9 | -------------------------------------------------------------------------------- /scripts/run-in-env: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | set -eu 3 | 4 | # Activate pyenv and virtualenv if present, then run the specified command 5 | 6 | # pyenv, pyenv-virtualenv 7 | if [ -s .python-version ]; then 8 | PYENV_VERSION=$(head -n 1 .python-version) 9 | export PYENV_VERSION 10 | fi 11 | 12 | # other common virtualenvs 13 | for venv in venv .venv .; do 14 | if [ -f $venv/bin/activate ]; then 15 | . $venv/bin/activate 16 | fi 17 | done 18 | 19 | exec "$@" 20 | -------------------------------------------------------------------------------- /custom_components/car_wash/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "domain": "car_wash", 3 | "name": "Car Wash", 4 | "codeowners": [ 5 | "@Limych" 6 | ], 7 | "config_flow": false, 8 | "dependencies": [ 9 | "weather" 10 | ], 11 | "documentation": "https://github.com/Limych/ha-car_wash", 12 | "iot_class": "calculated", 13 | "issue_tracker": "https://github.com/Limych/ha-car_wash/issues", 14 | "requirements": [ 15 | "pip>=21.3.1" 16 | ], 17 | "version": "1.5.8" 18 | } -------------------------------------------------------------------------------- /config/configuration.yaml: -------------------------------------------------------------------------------- 1 | default_config: 2 | 3 | # https://www.home-assistant.io/integrations/homeassistant/ 4 | homeassistant: 5 | debug: true 6 | 7 | # https://www.home-assistant.io/integrations/logger/ 8 | logger: 9 | default: info 10 | logs: 11 | custom_components.car_wash: debug 12 | 13 | # If you need to debug uncomment the line below (doc: https://www.home-assistant.io/integrations/debugpy/) 14 | # debugpy: 15 | 16 | binary_sensor: 17 | - platform: car_wash 18 | weather: weather.home_assistant 19 | unique_id: __legacy__ 20 | -------------------------------------------------------------------------------- /scripts/update: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # Update application to run for its current checkout. 3 | 4 | # Stop on errors 5 | set -e 6 | 7 | ROOT="$( cd "$( dirname "$(readlink -f "$0")" )/.." >/dev/null 2>&1 && pwd )" 8 | cd "${ROOT}" 9 | 10 | if git branch -r | grep -q "blueprint/dev" ; then 11 | git fetch blueprint dev 12 | elif git branch -r | grep -q "blueprint/develop" ; then 13 | git fetch blueprint develop 14 | elif git branch -r | grep -q "blueprint/master" ; then 15 | git fetch blueprint master 16 | elif git branch -r | grep -q "blueprint/main" ; then 17 | git fetch blueprint main 18 | fi 19 | 20 | git fetch 21 | git submodule update --remote 22 | -------------------------------------------------------------------------------- /scripts/develop: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -e 4 | 5 | cd "$(dirname "$0")/.." 6 | 7 | # Create config dir if not present 8 | if [[ ! -d "${PWD}/config" ]]; then 9 | mkdir -p "${PWD}/config" 10 | hass --config "${PWD}/config" --script ensure_config 11 | fi 12 | 13 | # Set the path to custom_components 14 | ## This let's us have the structure we want /custom_components/integration_blueprint 15 | ## while at the same time have Home Assistant configuration inside /config 16 | ## without resulting to symlinks. 17 | export PYTHONPATH="${PYTHONPATH}:${PWD}/custom_components" 18 | 19 | # Start Home Assistant 20 | hass --config "${PWD}/config" --debug 21 | -------------------------------------------------------------------------------- /scripts/_common: -------------------------------------------------------------------------------- 1 | #!/nonexistent 2 | 3 | readonly __COLORS_ESCAPE="\033["; 4 | readonly __COLORS_RESET="${__COLORS_ESCAPE}0m" 5 | readonly __COLORS_RED="${__COLORS_ESCAPE}31m" 6 | readonly __COLORS_GREEN="${__COLORS_ESCAPE}32m" 7 | readonly __COLORS_MAGENTA="${__COLORS_ESCAPE}35m" 8 | 9 | log.fatal() { 10 | local message=$* 11 | echo -e "${__COLORS_RED}${message}${__COLORS_RESET}" >&2 12 | } 13 | 14 | log.error() { 15 | local message=$* 16 | echo -e "${__COLORS_MAGENTA}${message}${__COLORS_RESET}" >&2 17 | } 18 | 19 | log.info() { 20 | local message=$* 21 | echo -e "${__COLORS_GREEN}${message}${__COLORS_RESET}" >&2 22 | } 23 | 24 | die() { 25 | local message=${1:-} 26 | local code=${2:-1} 27 | if [[ -n "${message}" ]]; then 28 | log.fatal "${message}" 29 | fi 30 | exit "${code}" 31 | } 32 | -------------------------------------------------------------------------------- /scripts/install_requirements: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # Install component requirements. 3 | # Require requirements.txt file path as first argument 4 | # and GitHub access token as second argument. 5 | 6 | # Stop on errors 7 | set -e 8 | 9 | ROOT="$( cd "$( dirname "$(readlink -f "$0")" )/.." >/dev/null 2>&1 && pwd )" 10 | cd "${ROOT}" 11 | 12 | file="requirements.txt" 13 | token="nonexistent" 14 | flags=() 15 | 16 | while test $# -gt 0; do 17 | case "${1}" in 18 | --pre) 19 | flags+=("${1}") 20 | ;; 21 | *) 22 | if test "${token}" != "nonexistent"; then 23 | file="${token}" 24 | fi 25 | token="${1}" 26 | ;; 27 | esac 28 | shift 29 | done 30 | 31 | python=$(which python3) 32 | pip="${python} -m pip" 33 | 34 | REQ=$(cat "${file}") 35 | while true; do 36 | FILES=$(echo "${REQ}" | grep "^-r " | sed "s/^-r\\s\+//g") 37 | if test -z "${FILES}"; then 38 | break 39 | fi 40 | for FILE in ${FILES}; do 41 | FILE_R=$(echo "${FILE}" | sed "s/\\./\\\\./g") 42 | REQ=$(echo "${REQ}" | sed -e "/^-r\\s\+${FILE_R}/{r ${FILE}" -e "d" -e "}") 43 | done 44 | done 45 | GIT=$(echo "${REQ}" | grep "{GITHUB_TOKEN}" | tr '\r\n' ' ') 46 | REQ=$(echo "${REQ}" | grep -v "{GITHUB_TOKEN}" | tr '\r\n' ' ') 47 | 48 | if test -n "${GIT}"; then 49 | GIT=$(echo "${GIT}" | sed "s/{GITHUB_TOKEN}/${token}/g") 50 | REQ="${GIT} ${REQ}" 51 | fi 52 | 53 | ${pip} install ${flags} --upgrade ${REQ} 54 | -------------------------------------------------------------------------------- /scripts/update_requirements: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Helper script to update requirements.""" 3 | import json 4 | import os 5 | import sys 6 | 7 | import requests 8 | 9 | ROOT = os.path.dirname(os.path.abspath(f"{__file__}/..")) 10 | 11 | PKG_PATH = PACKAGE = None 12 | for fname in os.listdir(f"{ROOT}/custom_components"): 13 | if fname != "__pycache__" and os.path.isdir(f"{ROOT}/custom_components/{fname}"): 14 | PACKAGE = fname 15 | PKG_PATH = f"{ROOT}/custom_components/{PACKAGE}" 16 | break 17 | 18 | if not PACKAGE: 19 | print("Package not found.") 20 | sys.exit(1) 21 | 22 | 23 | def get_package(requre: str) -> str: 24 | """Extract package name from requirement.""" 25 | return requre.split(">")[0].split("<")[0].split("!")[0].split("=")[0].split("~")[0] 26 | 27 | 28 | harequire = ["homeassistant"] 29 | request = requests.get( 30 | "https://raw.githubusercontent.com/home-assistant/core/dev/requirements.txt", 31 | timeout=10 32 | ) 33 | request = request.text.split("\n") 34 | for req in request: 35 | if "=" in req: 36 | harequire.append(get_package(req)) 37 | 38 | with open(f"{PKG_PATH}/manifest.json", encoding="utf8") as manifest: 39 | manifest = json.load(manifest) 40 | 41 | with open(f"{ROOT}/requirements.txt", encoding="utf8") as requirements: 42 | tmp = requirements.readlines() 43 | requirements = [] 44 | for req in tmp: 45 | pkg = get_package(req) 46 | if pkg not in harequire: 47 | requirements.append(req.replace("\n", "")) 48 | manifest["requirements"] = requirements 49 | 50 | with open(f"{PKG_PATH}/manifest.json", "w", encoding="utf8") as manifestfile: 51 | manifestfile.write(json.dumps(manifest, indent=4)) 52 | -------------------------------------------------------------------------------- /scripts/setup: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # Setups the development environment. 3 | 4 | # Stop on errors 5 | set -e 6 | 7 | ROOT="$( cd "$( dirname "$(readlink -f "$0")" )/.." >/dev/null 2>&1 && pwd )" 8 | cd "${ROOT}" 9 | 10 | python=$(which python3) 11 | 12 | # Load common functions 13 | source ./scripts/_common 14 | 15 | if [ ! -d "venv" ]; then 16 | log.info "Initializing the virtual environment..." 17 | # For error 'executable `python` not found' run 18 | # rm -Rf ~/.local/share/virtualenv 19 | ${python} -m venv ./venv 20 | source ./venv/bin/activate 21 | python="${ROOT}/venv/bin/python3" 22 | else 23 | ${python} -m venv ./venv 24 | fi 25 | 26 | pip="${python} -m pip" 27 | 28 | log.info "Updating PIP..." 29 | ${pip} install --upgrade pip 30 | 31 | log.info "Installing development dependencies..." 32 | ${pip} install colorlog pre-commit $(grep mypy requirements-dev.txt) 33 | 34 | pre-commit install 35 | 36 | REQ=$(cat requirements-dev.txt) 37 | while true; do 38 | FILES=$(echo "${REQ}" | grep "^-r " | sed "s/^-r\\s\+//g") 39 | if test -z "${FILES}"; then 40 | break 41 | fi 42 | for FILE in ${FILES}; do 43 | FILE_R=$(echo "${FILE}" | sed "s/\\./\\\\./g") 44 | REQ=$(echo "${REQ}" | sed -e "/^-r\\s\+${FILE_R}/{r ${FILE}" -e "d" -e "}") 45 | done 46 | done 47 | GIT=$(echo "${REQ}" | grep "{GITHUB_TOKEN}" | tr '\r\n' ' ') 48 | REQ=$(echo "${REQ}" | grep -v "{GITHUB_TOKEN}" | tr '\r\n' ' ') 49 | 50 | if test -n "${GIT}"; then 51 | GITHUB_TOKEN=$(grep github_token secrets.yaml | cut -d' ' -f2) 52 | GIT=$(echo "${GIT}" | sed "s/{GITHUB_TOKEN}/${GITHUB_TOKEN}/g") 53 | ${pip} install --upgrade ${GIT} 54 | fi 55 | 56 | ${pip} install --upgrade ${REQ} 57 | 58 | echo '"""Custom components module."""' >custom_components/__init__.py 59 | -------------------------------------------------------------------------------- /custom_components/car_wash/const.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019-2021, Andrey "Limych" Khrolenok 2 | # Creative Commons BY-NC-SA 4.0 International Public License 3 | # (see LICENSE.md or https://creativecommons.org/licenses/by-nc-sa/4.0/) 4 | """ 5 | The Car Wash binary sensor. 6 | 7 | For more details about this platform, please refer to the documentation at 8 | https://github.com/Limych/ha-car_wash/ 9 | """ 10 | 11 | from typing import Final 12 | 13 | from homeassistant.components.weather import ( 14 | ATTR_CONDITION_EXCEPTIONAL, 15 | ATTR_CONDITION_HAIL, 16 | ATTR_CONDITION_LIGHTNING_RAINY, 17 | ATTR_CONDITION_POURING, 18 | ATTR_CONDITION_RAINY, 19 | ATTR_CONDITION_SNOWY, 20 | ATTR_CONDITION_SNOWY_RAINY, 21 | ) 22 | 23 | # Base component constants 24 | NAME: Final = "Car Wash" 25 | DOMAIN: Final = "car_wash" 26 | VERSION: Final = "1.5.8" 27 | ISSUE_URL: Final = "https://github.com/Limych/ha-car_wash/issues" 28 | 29 | STARTUP_MESSAGE: Final = f""" 30 | ------------------------------------------------------------------- 31 | {NAME} 32 | Version: {VERSION} 33 | This is a custom integration! 34 | If you have ANY issues with this you need to open an issue here: 35 | {ISSUE_URL} 36 | ------------------------------------------------------------------- 37 | """ 38 | 39 | # Icons 40 | ICON: Final = "mdi:car-wash" 41 | 42 | # Configuration and options 43 | CONF_WEATHER: Final = "weather" 44 | CONF_DAYS: Final = "days" 45 | 46 | # Defaults 47 | DEFAULT_NAME: Final = "Car Wash" 48 | DEFAULT_DAYS: Final = 2 49 | 50 | 51 | BAD_CONDITIONS: Final = [ 52 | ATTR_CONDITION_LIGHTNING_RAINY, 53 | ATTR_CONDITION_RAINY, 54 | ATTR_CONDITION_POURING, 55 | ATTR_CONDITION_SNOWY, 56 | ATTR_CONDITION_SNOWY_RAINY, 57 | ATTR_CONDITION_HAIL, 58 | ATTR_CONDITION_EXCEPTIONAL, 59 | ] 60 | -------------------------------------------------------------------------------- /scripts/update_manifest: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # Update manifest.json of custom component. 3 | 4 | # Stop on errors 5 | set -e 6 | 7 | ROOT="$( cd "$( dirname "$(readlink -f "$0")" )/.." >/dev/null 2>&1 && pwd )" 8 | cd "${ROOT}" 9 | 10 | # Load common functions 11 | source ./scripts/_common 12 | 13 | if [[ $(ls -q "${ROOT}/custom_components/" | grep -v __ | wc -l) > 1 ]]; then 14 | log.error "WARNING: Detected more than one custom component. This script will update only first one of them." 15 | fi 16 | 17 | component=$(ls -q "${ROOT}/custom_components/" | grep -v __ | head -n 1) 18 | const_path="custom_components/${component}/const.py" 19 | reqs_path="requirements.txt" 20 | 21 | name=$(grep -Ei "^NAME(: Final)? =" ${const_path} | sed -E "s/^[^\"]+\"([^\"]*).*$/\\1/") 22 | domain=$(grep -Ei "^DOMAIN(: Final)? =" ${const_path} | sed -E "s/^[^\"]+\"([^\"]*).*$/\\1/") 23 | version=$(grep -Ei "^VERSION(: Final)? =" ${const_path} | sed -E "s/^[^\"]+\"([^\"]*).*$/\\1/") 24 | issue_url=$(grep -Ei "^ISSUE_URL(: Final)? =" ${const_path} | sed -E "s/^[^\"]+\"([^\"]*).*$/\\1/") 25 | ha_version=$(grep -Ei "^homeassistant>=" ${reqs_path} | sed -E "s/^[^=]+=(\S*).*$/\\1/") 26 | 27 | log.info "Update manifest.json data..." 28 | manifest_path="custom_components/${component}/manifest.json" 29 | sed -i -E "s!(\"name\": \")[^\"]*!\\1${name}!" ${manifest_path} 30 | sed -i -E "s!(\"domain\": \")[^\"]*!\\1${domain}!" ${manifest_path} 31 | sed -i -E "s!(\"version\": \")[^\"]*!\\1${version}!" ${manifest_path} 32 | sed -i -E "s!(\"issue_tracker\": \")[^\"]*!\\1${issue_url}!" ${manifest_path} 33 | 34 | ./scripts/update_requirements 35 | 36 | log.info "Update hacs.json data..." 37 | hacs_path="${ROOT}/hacs.json" 38 | sed -i -E "s!(\"name\": \")[^\"]*!\\1${name}!" ${hacs_path} 39 | sed -i -E "s!(\"homeassistant\": \")[^\"]*!\\1${ha_version}!" ${hacs_path} 40 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contribution guidelines 2 | 3 | Contributing to this project should be as easy and transparent as possible, whether it's: 4 | 5 | - Reporting a bug 6 | - Discussing the current state of the code 7 | - Submitting a fix 8 | - Proposing new features 9 | 10 | ## IMPORTANT! Install development environment first 11 | 12 | When making changes in code, please use the existing development environment — this will save you from many errors and help create more convenient code to support. To install the environment, run the `./scripts/setup` script. 13 | 14 | ## Github is used for everything 15 | 16 | Github is used to host code, to track issues and feature requests, as well as accept pull requests. 17 | 18 | Pull requests are the best way to propose changes to the codebase. 19 | 20 | 1. Fork the repo and create your branch from `main`. 21 | 2. If you've changed something, update the documentation. 22 | 3. Make sure your code lints (using black). 23 | 4. Test you contribution. 24 | 5. Issue that pull request! 25 | 26 | ## Any contributions you make will be under the MIT Software License 27 | 28 | In short, when you submit code changes, your submissions are understood to be under the same [MIT License](http://choosealicense.com/licenses/mit/) that covers the project. Feel free to contact the maintainers if that's a concern. 29 | 30 | ## Report bugs using Github's [issues](../../issues) 31 | 32 | GitHub issues are used to track public bugs. 33 | Report a bug by [opening a new issue](../../issues/new/choose); it's that easy! 34 | 35 | ## Write bug reports with detail, background, and sample code 36 | 37 | **Great Bug Reports** tend to have: 38 | 39 | - A quick summary and/or background 40 | - Steps to reproduce 41 | - Be specific! 42 | - Give sample code if you can. 43 | - What you expected would happen 44 | - What actually happens 45 | - Notes (possibly including why you think this might be happening, or stuff you tried that didn't work) 46 | 47 | People *love* thorough bug reports. I'm not even kidding. 48 | 49 | ## Use a Consistent Coding Style 50 | 51 | Use [black](https://github.com/ambv/black) to make sure the code follows the style. 52 | 53 | ## Test your code modification 54 | 55 | This custom component is based on [integration blueprint template](https://github.com/Limych/ha-car_wash). 56 | 57 | It comes with development environment in a container, easy to launch 58 | if you use Visual Studio Code. With this container you will have a stand alone 59 | Home Assistant instance running and already configured with the included 60 | [`configuration.yaml`](./config/configuration.yaml) 61 | file. 62 | 63 | ## License 64 | 65 | By contributing, you agree that your contributions will be licensed under its MIT License. 66 | -------------------------------------------------------------------------------- /info.md: -------------------------------------------------------------------------------- 1 | {% if prerelease %} 2 | ### NB!: This is a Beta version! 3 | {% endif %} 4 | {% if (version_installed.split(".")[0:2] | join | int) < 15 %} 5 | ### ATTENTION! Breaking changes! 6 | 7 | The mechanism for specifying the unique ID of sensors has been changed. To prevent duplicate sensors from being created, add option `unique_id: __legacy__` to the settings of already available sensors. For more information, see the component's documentation. 8 | {% endif %} 9 | 10 | [![GitHub Release][releases-shield]][releases] 11 | [![GitHub Activity][commits-shield]][commits] 12 | [![License][license-shield]][license] 13 | 14 | [![hacs][hacs-shield]][hacs] 15 | [![Project Maintenance][maintenance-shield]][user_profile] 16 | [![Support me on Patreon][patreon-shield]][patreon] 17 | 18 | [![Community Forum][forum-shield]][forum] 19 | 20 | _This component checks the weather forecast for several days in advance and concludes whether it is worth washing the car now._ 21 | 22 | ![example][exampleimg] 23 | 24 | ## Features: 25 | 26 | - Can use any weather provider for calculations; 27 | - It takes into account various unusual weather conditions; 28 | - It takes into account possible pollution of the car from melted snow even in fine weather conditions. 29 | 30 | {% if not installed %} 31 | ## Installation 32 | 33 | 1. Click install. 34 | 1. In the HA UI go to "Configuration" -> "Integrations" click "+" and search for "Car Wash". 35 | 36 | {% endif %} 37 | ## Useful Links 38 | 39 | - [Documentation][component] 40 | - [Report a Bug][report_bug] 41 | - [Suggest an idea][suggest_idea] 42 | 43 |

* * *

44 | I put a lot of work into making this repo and component available and updated to inspire and help others! I will be glad to receive thanks from you — it will give me new strength and add enthusiasm: 45 |


46 | Patreon 47 |
or support via Bitcoin or Etherium:
48 | Bitcoin
49 | 16yfCfz9dZ8y8yuSwBFVfiAa3CNYdMh7Ts
50 |

51 | 52 | *** 53 | 54 | [component]: https://github.com/Limych/ha-car_wash 55 | [commits-shield]: https://img.shields.io/github/commit-activity/y/Limych/ha-car_wash.svg?style=popout 56 | [commits]: https://github.com/Limych/ha-car_wash/commits/dev 57 | [hacs-shield]: https://img.shields.io/badge/HACS-Default-orange.svg?style=popout 58 | [hacs]: https://hacs.xyz 59 | [exampleimg]: https://github.com/Limych/ha-car_wash/raw/dev/example.jpg 60 | [forum-shield]: https://img.shields.io/badge/community-forum-brightgreen.svg?style=popout 61 | [forum]: https://community.home-assistant.io/t/car-wash-binary-sensor/110046 62 | [license]: https://github.com/Limych/ha-car_wash/blob/main/LICENSE.md 63 | [license-shield]: https://img.shields.io/badge/license-Creative_Commons_BY--NC--SA_License-lightgray.svg?style=popout 64 | [maintenance-shield]: https://img.shields.io/badge/maintainer-Andrey%20Khrolenok%20%40Limych-blue.svg?style=popout 65 | [releases-shield]: https://img.shields.io/github/release/Limych/ha-car_wash.svg?style=popout 66 | [releases]: https://github.com/Limych/ha-car_wash/releases 67 | [releases-latest]: https://github.com/Limych/ha-car_wash/releases/latest 68 | [user_profile]: https://github.com/Limych 69 | [report_bug]: https://github.com/Limych/ha-car_wash/issues/new?template=bug_report.md 70 | [suggest_idea]: https://github.com/Limych/ha-car_wash/issues/new?template=feature_request.md 71 | [contributors]: https://github.com/Limych/ha-car_wash/graphs/contributors 72 | [patreon-shield]: https://img.shields.io/endpoint.svg?url=https%3A%2F%2Fshieldsio-patreon.vercel.app%2Fapi%3Fusername%3DLimych%26type%3Dpatrons&style=popout 73 | [patreon]: https://www.patreon.com/join/limych 74 | -------------------------------------------------------------------------------- /scripts/release: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Stop on errors 4 | set -e 5 | 6 | ROOT="$( cd "$( dirname "$(readlink -f "$0")" )/.." >/dev/null 2>&1 && pwd )" 7 | cd "${ROOT}" 8 | 9 | # Load common functions 10 | source ./scripts/_common 11 | 12 | 13 | NAT='0|[1-9][0-9]*' 14 | ALPHANUM='[0-9]*[A-Za-z-][0-9A-Za-z-]*' 15 | IDENT="$NAT|$ALPHANUM" 16 | FIELD='[0-9A-Za-z-]+' 17 | 18 | SEMVER_REGEX="\ 19 | ^($NAT)\\.($NAT)\\.($NAT)\ 20 | (\\-(${IDENT})(\\.(${IDENT}))*)?\ 21 | (\\+${FIELD}(\\.${FIELD})*)?$" 22 | 23 | function validate_version { 24 | local version=$1 25 | if [[ "$version" =~ $SEMVER_REGEX ]]; then 26 | # if a second argument is passed, store the result in var named by $2 27 | if test "$#" -eq "2"; then 28 | local major=${BASH_REMATCH[1]} 29 | local minor=${BASH_REMATCH[2]} 30 | local patch=${BASH_REMATCH[3]} 31 | local prere=${BASH_REMATCH[4]} 32 | local build=${BASH_REMATCH[8]} 33 | eval "$2=(\"$major\" \"$minor\" \"$patch\" \"$prere\" \"$build\")" 34 | else 35 | echo "$version" 36 | fi 37 | else 38 | die "Version $version does not match the SemVer scheme 'X.Y.Z(-PRERELEASE)(+BUILD)'" 39 | fi 40 | } 41 | 42 | PREFIX_ALPHANUM='[.0-9A-Za-z-]*[.A-Za-z-]' 43 | DIGITS='[0-9][0-9]*' 44 | EXTRACT_REGEX="^(${PREFIX_ALPHANUM})*(${DIGITS})$" 45 | 46 | function extract_prerel { 47 | local prefix; local numeric; 48 | 49 | if [[ "$1" =~ $EXTRACT_REGEX ]]; then 50 | # found prefix and trailing numeric parts 51 | prefix="${BASH_REMATCH[1]}" 52 | numeric="${BASH_REMATCH[2]}" 53 | else 54 | # no numeric part 55 | prefix="${1}" 56 | numeric= 57 | fi 58 | 59 | eval "$2=(\"$prefix\" \"$numeric\")" 60 | } 61 | 62 | function bump_prerel { 63 | validate_version "${1}" parts 64 | # shellcheck disable=SC2154 65 | local major="${parts[0]}" 66 | local minor="${parts[1]}" 67 | local patch="${parts[2]}" 68 | 69 | extract_prerel "${parts[3]#-}" prerel_parts # extract parts of previous pre-release 70 | # shellcheck disable=SC2154 71 | prev_prefix="${prerel_parts[0]}" 72 | prev_numeric="${prerel_parts[1]}" 73 | 74 | if test -n "$prev_numeric"; then 75 | # previous pre-release is already numbered, bump it 76 | : $(( ++prev_numeric )) 77 | echo "$(validate_version "${major}.${minor}.${patch}-${prev_prefix}${prev_numeric}")" 78 | else 79 | # append starting number 80 | echo "$(validate_version "${major}.${minor}.${patch}-${prev_prefix}2")" 81 | fi 82 | } 83 | 84 | if output=$(git branch --show-current) \ 85 | && [[ "$output" != "master" && "$output" != "main" && "$output" != "dev" ]]; then 86 | log.fatal "Please, change HEAD to 'master', 'main' or 'dev' branch." 87 | log.info "At now HEAD at '${output}' branch." 88 | exit 1 89 | fi 90 | if output=$(git status --porcelain) && [[ -n "$output" ]]; then 91 | log.fatal "Please, make working tree clean first." 92 | log.info ${output} 93 | exit 2 94 | fi 95 | if ! pytest; then 96 | exit 3 97 | fi 98 | 99 | const_path=$(find custom_components/ -name const.py) 100 | version=$(grep "^VERSION: Final =" ${const_path} | sed -E "s/^[^\"]+\"([^\"]*).*$/\\1/") 101 | 102 | if [[ -z $1 ]]; then 103 | log.fatal "Please, describe new version number as first argument." 104 | log.info "Current version number is ${version}" 105 | exit 3 106 | fi 107 | 108 | new=$(validate_version "${1}") 109 | 110 | log.info "Patch files to version '${new}'..." 111 | sed -i -E "s/(^VERSION: Final = \")[^\"]*/\\1${new}/" ${const_path} 112 | ./scripts/update_manifest 113 | if output=$(git status --porcelain) && [[ -n "$output" ]]; then 114 | git commit -a --no-verify -m "Bump version to ${new}" 115 | fi 116 | git tag -a "$new" -m "v$new" 117 | log.info "Commit tagged as v$new" 118 | 119 | if echo "${new}" | grep -q "-"; then 120 | dev=$(bump_prerel "${new}") 121 | else 122 | dev="$(echo "${new}" | awk -F. '/[0-9]+\./{($NF)++;print}' OFS=.)-alpha" 123 | fi 124 | 125 | log.info "Patch files to version '${dev}'..." 126 | sed -i -E "s/(^VERSION: Final = \")[^\"]*/\\1${dev}/" ${const_path} 127 | ./scripts/update_manifest 128 | -------------------------------------------------------------------------------- /scripts/devcontainer: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Stop on errors 4 | set -e 5 | 6 | ROOT="$( cd "$( dirname "$(readlink -f "$0")" )/.." >/dev/null 2>&1 && pwd )" 7 | cd "${ROOT}" 8 | 9 | # Load common functions 10 | source ./scripts/_common 11 | 12 | docker=$(which docker) || die "ERROR: Docker not found." 13 | 14 | workspace=${PWD##*/} 15 | workdir="/workspaces/${workspace}" 16 | 17 | container="dev-${workspace}" 18 | port="127.0.0.1:9123:8123" 19 | image="devcontainer" 20 | volume="${ROOT}:${workdir}" 21 | 22 | cmd="menu" 23 | while test $# -gt 0; do 24 | case "${1}" in 25 | --help|-h) 26 | log.info "devcontainer [options] [command]" 27 | log.info "" 28 | log.info "Options:" 29 | log.info " -h, --help Show this help." 30 | log.info " --public Create dev container externally accessible"\ 31 | "(Only makes sense when creating a new container)." 32 | log.info "" 33 | log.info "Commands:" 34 | log.info " start Start dev container." 35 | log.info " stop Save current state of dev container and stop it." 36 | log.info " check Run Home Assistant config check." 37 | log.info " set-version Install a specific version of Home Assistant." 38 | log.info " upgrade Upgrade Home Assistant to latest dev"\ 39 | "then run user's bootstrap script again." 40 | log.info " bootstrap Run user's bootstrap script again." 41 | log.info " bash Run command line into dev container." 42 | log.info " down Destroy dev container." 43 | die 44 | ;; 45 | --public) 46 | log.info "Attention! The container is creating externally accessible." 47 | port=$(echo "${port}" | sed "s/127.0.0.1/0.0.0.0/") 48 | ;; 49 | *) 50 | cmd="${1}" 51 | ;; 52 | esac 53 | shift 54 | done 55 | 56 | docker_start() { 57 | tmp=$(echo "${port}" | cut -d":" -f2) 58 | tmp=$(${docker} ps | grep ":${tmp}" | awk "{print \$NF}") 59 | if test -n "${tmp}" ; then 60 | log.info "Stop container ${tmp}..." 61 | ${docker} stop "${tmp}" 62 | fi 63 | 64 | tmp=$(${docker} ps | grep "${container}" | awk "{print \$NF}") 65 | if test -n "${tmp}" ; then 66 | log.info "Stop container ${tmp}..." 67 | ${docker} stop "${tmp}" 68 | fi 69 | 70 | log.info "Start container..." 71 | ${docker} start "${container}" 72 | } 73 | 74 | bootstrap() { 75 | if test -f "${ROOT}/config/bootstrap.sh"; then 76 | log.info "Execute bootstrap.sh..." 77 | ${docker} exec -it -w "${workdir}" "${container}" config/bootstrap.sh "$1" 78 | fi 79 | } 80 | 81 | if ! ${docker} ps -a | grep -wq ${container} && [[ "${cmd}" != "down" ]]; then 82 | log.info "Create container..." 83 | ${docker} build -t "${image}" "${ROOT}/.devcontainer/" 84 | ${docker} create -it --name "${container}" -p "${port}" -v "${volume}" "${image}" 85 | 86 | docker_start 87 | fi 88 | 89 | if [[ "${cmd}" == "menu" ]]; then 90 | PS3='Please enter your choice: ' 91 | options=(\ 92 | "Run Home Assistant on port 9123" 93 | "Run Home Assistant configuration against /config" 94 | "Upgrade Home Assistant to latest dev" 95 | "Install a specific version of Home Assistant" 96 | ) 97 | echo 98 | select opt in "${options[@]}" 99 | do 100 | case $REPLY in 101 | 1 ) 102 | cmd="start" 103 | ;; 104 | 2 ) 105 | cmd="check" 106 | ;; 107 | 3 ) 108 | cmd="upgrade" 109 | ;; 110 | 4 ) 111 | cmd="set-version" 112 | ;; 113 | esac 114 | break 115 | done 116 | fi 117 | case "${cmd}" in 118 | "stop" ) 119 | log.info "Stop container..." 120 | ${docker} stop "${container}" 121 | ;; 122 | "down" ) 123 | log.info "Destroy container..." 124 | ${docker} stop -t 10 "${container}" >/dev/null 125 | ${docker} rm "${container}" 126 | ;; 127 | "bash" ) 128 | if ! ${docker} ps | grep -wq ${container}; then 129 | docker_start 130 | fi 131 | log.info "Interactive mode..." 132 | ${docker} exec -it "${container}" bash 133 | ;; 134 | "bootstrap" ) 135 | bootstrap "${cmd}" 136 | ;; 137 | * ) 138 | if ! ${docker} ps | grep -wq ${container}; then 139 | docker_start 140 | fi 141 | log.info "Send command '${cmd}' to container..." 142 | if [[ "${cmd}" == "start" || "${cmd}" == "up" || "${cmd}" == "run" ]]; then 143 | log.info "Note: After Home Assistant initialization you can access to system on http://localhost:9123/" 144 | fi 145 | ${docker} exec -it -w "${workdir}" "${container}" container "${cmd}" 146 | 147 | if [[ "${cmd}" == "upgrade" || "${cmd}" == "update" \ 148 | || "${cmd}" == "install" || "${cmd}" == "reinstall" ]]; then 149 | bootstrap "${cmd}" 150 | fi 151 | ;; 152 | esac 153 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "car_wash" 3 | requires-python = ">=3.12" 4 | 5 | [tool.black] 6 | target-version = ["py312"] 7 | extend-exclude = "/generated/" 8 | 9 | [tool.isort] 10 | # https://github.com/PyCQA/isort/wiki/isort-Settings 11 | profile = "black" 12 | # will group `import x` and `from x import` of the same module. 13 | force_sort_within_sections = true 14 | known_first_party = [ 15 | "homeassistant", 16 | "tests", 17 | ] 18 | forced_separate = [ 19 | "tests", 20 | ] 21 | combine_as_imports = true 22 | 23 | [tool.pylint.MAIN] 24 | py-version = "3.12" 25 | ignore = [ 26 | "tests", 27 | ] 28 | # Use a conservative default here; 2 should speed up most setups and not hurt 29 | # any too bad. Override on command line as appropriate. 30 | jobs = 2 31 | init-hook = """\ 32 | from pathlib import Path; \ 33 | import sys; \ 34 | 35 | from pylint.config import find_default_config_files; \ 36 | 37 | sys.path.append( \ 38 | str(Path(next(find_default_config_files())).parent.joinpath('pylint/plugins')) 39 | ) \ 40 | """ 41 | load-plugins = [ 42 | "pylint.extensions.code_style", 43 | "pylint.extensions.typing", 44 | "hass_enforce_type_hints", 45 | "hass_imports", 46 | "hass_logger", 47 | "pylint_per_file_ignores", 48 | ] 49 | persistent = false 50 | extension-pkg-allow-list = [ 51 | "av.audio.stream", 52 | "av.stream", 53 | "ciso8601", 54 | "orjson", 55 | "cv2", 56 | ] 57 | fail-on = [ 58 | "I", 59 | ] 60 | 61 | [tool.pylint.BASIC] 62 | class-const-naming-style = "any" 63 | good-names = [ 64 | "_", 65 | "ev", 66 | "ex", 67 | "fp", 68 | "i", 69 | "id", 70 | "j", 71 | "k", 72 | "Run", 73 | "ip", 74 | ] 75 | 76 | [tool.pylint."MESSAGES CONTROL"] 77 | # Reasons disabled: 78 | # format - handled by black 79 | # locally-disabled - it spams too much 80 | # duplicate-code - unavoidable 81 | # cyclic-import - doesn't test if both import on load 82 | # abstract-class-little-used - prevents from setting right foundation 83 | # unused-argument - generic callbacks and setup methods create a lot of warnings 84 | # too-many-* - are not enforced for the sake of readability 85 | # too-few-* - same as too-many-* 86 | # abstract-method - with intro of async there are always methods missing 87 | # inconsistent-return-statements - doesn't handle raise 88 | # too-many-ancestors - it's too strict. 89 | # wrong-import-order - isort guards this 90 | # consider-using-f-string - str.format sometimes more readable 91 | # --- 92 | # Pylint CodeStyle plugin 93 | # consider-using-namedtuple-or-dataclass - too opinionated 94 | # consider-using-assignment-expr - decision to use := better left to devs 95 | disable = [ 96 | "format", 97 | "abstract-method", 98 | "cyclic-import", 99 | "duplicate-code", 100 | "inconsistent-return-statements", 101 | "locally-disabled", 102 | "not-context-manager", 103 | "too-few-public-methods", 104 | "too-many-ancestors", 105 | "too-many-arguments", 106 | "too-many-branches", 107 | "too-many-instance-attributes", 108 | "too-many-lines", 109 | "too-many-locals", 110 | "too-many-public-methods", 111 | "too-many-return-statements", 112 | "too-many-statements", 113 | "too-many-boolean-expressions", 114 | "unused-argument", 115 | "wrong-import-order", 116 | "consider-using-f-string", 117 | "consider-using-namedtuple-or-dataclass", 118 | "consider-using-assignment-expr", 119 | ] 120 | enable = [ 121 | #"useless-suppression", # temporarily every now and then to clean them up 122 | "use-symbolic-message-instead", 123 | ] 124 | 125 | [tool.pylint.REPORTS] 126 | score = false 127 | 128 | [tool.pylint.TYPECHECK] 129 | ignored-classes = [ 130 | "_CountingAttr", # for attrs 131 | ] 132 | mixin-class-rgx = ".*[Mm]ix[Ii]n" 133 | 134 | [tool.pylint.FORMAT] 135 | expected-line-ending-format = "LF" 136 | 137 | [tool.pylint.EXCEPTIONS] 138 | overgeneral-exceptions = [ 139 | "builtins.BaseException", 140 | "builtins.Exception", 141 | # "homeassistant.exceptions.HomeAssistantError", # too many issues 142 | ] 143 | 144 | [tool.pylint.TYPING] 145 | runtime-typing = false 146 | 147 | [tool.pylint.CODE_STYLE] 148 | max-line-length-suggestions = 72 149 | 150 | [tool.pylint-per-file-ignores] 151 | # hass-component-root-import: Tests test non-public APIs 152 | # protected-access: Tests do often test internals a lot 153 | # redefined-outer-name: Tests reference fixtures in the test function 154 | "/tests/"="hass-component-root-import,protected-access,redefined-outer-name" 155 | 156 | [tool.pytest.ini_options] 157 | testpaths = [ 158 | "tests", 159 | ] 160 | norecursedirs = [ 161 | ".git", 162 | "testing_config", 163 | ] 164 | log_format = "%(asctime)s.%(msecs)03d %(levelname)-8s %(threadName)s %(name)s:%(filename)s:%(lineno)s %(message)s" 165 | log_date_format = "%Y-%m-%d %H:%M:%S" 166 | asyncio_mode = "auto" 167 | 168 | [tool.ruff] 169 | target-version = "py312" 170 | 171 | select = [ 172 | "C", # complexity 173 | "D", # docstrings 174 | "E", # pycodestyle 175 | "F", # pyflakes/autoflake 176 | "PGH004", # Use specific rule codes when using noqa 177 | "PLC0414", # Useless import alias. Import alias does not rename original package. 178 | "SIM105", # Use contextlib.suppress({exception}) instead of try-except-pass 179 | "SIM117", # Merge with-statements that use the same scope 180 | "SIM300", # Yoda conditions. Use 'age == 42' instead of '42 == age'. 181 | "SIM401", # Use get from dict with default instead of an if block 182 | "T20", # flake8-print 183 | "TRY004", # Prefer TypeError exception for invalid type 184 | "UP", # pyupgrade 185 | "W", # pycodestyle 186 | ] 187 | 188 | ignore = [ 189 | "D202", # No blank lines allowed after function docstring 190 | "D203", # 1 blank line required before class docstring 191 | "D213", # Multi-line docstring summary should start at the second line 192 | "D404", # First word of the docstring should not be This 193 | "D406", # Section name should end with a newline 194 | "D407", # Section name underlining 195 | "D411", # Missing blank line before section 196 | "E501", # line too long 197 | "E731", # do not assign a lambda expression, use a def 198 | ] 199 | 200 | [tool.ruff.flake8-pytest-style] 201 | fixture-parentheses = false 202 | 203 | [tool.ruff.pyupgrade] 204 | keep-runtime-typing = true 205 | 206 | [tool.ruff.per-file-ignores] 207 | 208 | # TODO: these files have functions that are too complex, but flake8's and ruff's 209 | # complexity (and/or nested-function) handling differs; trying to add a noqa doesn't work 210 | # because the flake8-noqa plugin then disagrees on whether there should be a C901 noqa 211 | # on that line. So, for now, we just ignore C901s on these files as far as ruff is concerned. 212 | 213 | "homeassistant/components/light/__init__.py" = ["C901"] 214 | "homeassistant/components/mqtt/discovery.py" = ["C901"] 215 | "homeassistant/components/websocket_api/http.py" = ["C901"] 216 | 217 | # Allow for main entry & scripts to write to stdout 218 | "homeassistant/__main__.py" = ["T201"] 219 | "homeassistant/scripts/*" = ["T201"] 220 | "script/*" = ["T20"] 221 | 222 | [tool.ruff.mccabe] 223 | max-complexity = 25 224 | -------------------------------------------------------------------------------- /scripts/gen_releasenotes: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """Helper script to generate release notes.""" 3 | import argparse 4 | from datetime import datetime 5 | import logging 6 | import os 7 | import re 8 | import subprocess 9 | from typing import List, Optional, Tuple 10 | 11 | from github import Github, GithubException, Repository, Tag 12 | from packaging.version import Version 13 | 14 | # http://docs.python.org/2/howto/logging.html#library-config 15 | # Avoids spurious error messages if no logger is configured by the user 16 | logging.getLogger(__name__).addHandler(logging.NullHandler()) 17 | 18 | logging.basicConfig(level=logging.CRITICAL) 19 | 20 | _LOGGER = logging.getLogger(__name__) 21 | 22 | VERSION = "1.2.1" 23 | 24 | ROOT = os.path.dirname(os.path.abspath(f"{__file__}/..")) 25 | 26 | BODY = """ 27 | [![Downloads for this release](https://img.shields.io/github/downloads/{repo}/{version}/total.svg)](https://github.com/{repo}/releases/{version}) 28 | 29 | {changes} 30 | 31 | ... and by bots: 32 | 33 | {bot_changes} 34 | 35 | ## Links 36 | 37 | - [If you like what I (@limych) do please consider sponsoring me on Patreon](https://www.patreon.com/join/limych?) 38 | """ 39 | 40 | CHANGE = "- [{line}]({link}) @{author}\n" 41 | NOCHANGE = "_No changes in this release._" 42 | 43 | RE_PEP440 = re.compile( 44 | r"([1-9][0-9]*!)?(0|[1-9][0-9]*)(\.(0|[1-9][0-9]*))*((a|b|rc)" 45 | r"(0|[1-9][0-9]*))?(\.post(0|[1-9][0-9]*))?(\.dev(0|[1-9][0-9]*))?(\.rc(0|[1-9][0-9]*))?" 46 | ) 47 | 48 | 49 | def is_pep440(version: str) -> bool: 50 | """Return True if the version is PEP 440 compliant.""" 51 | return bool(RE_PEP440.match(version)) 52 | 53 | 54 | def get_commits(repo: Repository, since: datetime, until: datetime): 55 | """Get commits in repo.""" 56 | commits = repo.get_commits(since=since, until=until) 57 | try: 58 | dev = repo.get_branch("develop") 59 | dev_commits = repo.get_commits(sha=dev.commit.sha, since=since, until=until) 60 | if dev_commits.totalCount > commits.totalCount: 61 | commits = dev_commits 62 | except GithubException: 63 | pass 64 | if len(list(commits)) == 1: 65 | return [] 66 | return reversed(list(commits)[:-1]) 67 | 68 | 69 | def get_release_tags(repo: Repository) -> List[Tag.Tag]: 70 | """Get list of all release tags from repository.""" 71 | tags = list( 72 | filter(lambda tag: is_pep440(tag.name.lstrip("v")), list(repo.get_tags())) 73 | ) 74 | tags.sort(key=lambda x: x.name.lstrip("v"), reverse=True) 75 | _LOGGER.debug("Found tags: %s", tags) 76 | return tags 77 | 78 | 79 | def get_period(repo: Repository, release: Optional[str] = None) -> List[datetime]: 80 | """Return time period for release notes.""" 81 | data = [datetime.now()] 82 | dateformat = "%a, %d %b %Y %H:%M:%S GMT" 83 | found = release is None 84 | last = False 85 | is_prerelease = Version(release).is_prerelease if release is not None else False 86 | for tag in get_release_tags(repo): 87 | last = False 88 | commit = repo.get_commit(tag.commit.sha) 89 | timestamp = datetime.strptime(commit.last_modified, dateformat) 90 | _LOGGER.debug("Process tag %s => timestamp %s", tag.name, timestamp) 91 | data.append(timestamp) 92 | if found and (not Version(tag.name).is_prerelease or is_prerelease): 93 | break 94 | if release is not None and release == tag.name: 95 | found = last = True 96 | if (found and last) or len(data) < 2: 97 | data.append(datetime.fromtimestamp(0)) 98 | return list(reversed(data[-2:])) 99 | 100 | 101 | def gen_changes(repo: Repository, tag: Optional[str] = None) -> Tuple[str, str, str]: 102 | """Generate list of commits.""" 103 | all_changes = "" 104 | human_changes = "" 105 | bot_changes = "" 106 | period = get_period(repo, tag) 107 | _LOGGER.debug("Period: %s", period) 108 | 109 | commits = get_commits(repo, period[0], period[1]) 110 | for commit in commits: 111 | msg = repo.get_git_commit(commit.sha).message 112 | if "\n" in msg: 113 | msg = msg.split("\n")[0] 114 | if ( 115 | "Initial commit" in msg 116 | or "Bump version" in msg 117 | or "Version bump" in msg 118 | or "Merge remote-tracking branch" in msg 119 | or "Merge branch" in msg 120 | or "Merge tag" in msg 121 | or "Merge pull request" in msg 122 | or "Fix errors" in msg 123 | ): 124 | continue 125 | 126 | change = CHANGE.format( 127 | line=msg, link=commit.html_url, author=commit.author.login 128 | ) 129 | all_changes += change 130 | if "[bot]" not in commit.author.login: 131 | human_changes += change 132 | else: 133 | bot_changes += change 134 | 135 | return ( 136 | all_changes if all_changes != "" else NOCHANGE, 137 | human_changes if human_changes != "" else NOCHANGE, 138 | bot_changes if bot_changes != "" else NOCHANGE, 139 | ) 140 | 141 | 142 | def _bump_release(release, bump_type): 143 | """Bump a release tuple consisting of 3 numbers.""" 144 | major, minor, patch = release 145 | 146 | if bump_type == "patch": 147 | patch += 1 148 | elif bump_type == "minor": 149 | minor += 1 150 | patch = 0 151 | 152 | return major, minor, patch 153 | 154 | 155 | def bump_version(version: Version) -> Version: 156 | """Return a new version given a current version.""" 157 | to_change = {} 158 | 159 | # Convert 0.67.3 to 0.67.4 160 | # Convert 0.67.3.b5 to 0.67.3 161 | # Convert 0.67.3.dev0 to 0.67.3 162 | to_change["dev"] = None 163 | to_change["pre"] = None 164 | 165 | if not version.is_prerelease: 166 | to_change["release"] = _bump_release(version.release, "patch") 167 | 168 | temp = Version("0") 169 | temp._version = version._version._replace( # pylint: disable=protected-access 170 | **to_change 171 | ) 172 | return Version(str(temp)) 173 | 174 | 175 | def main(): 176 | """Execute script.""" 177 | parser = argparse.ArgumentParser( 178 | description=f"Release notes generator. Version {VERSION}" 179 | ) 180 | parser.add_argument( 181 | "-v", 182 | "--verbose", 183 | action="store_true", 184 | help="Enable debugging output.", 185 | ) 186 | parser.add_argument( 187 | "-n", 188 | "--dry-run", 189 | "--dryrun", 190 | action="store_true", 191 | help="Preview release notes generation without running it.", 192 | ) 193 | parser.add_argument( 194 | "--token", 195 | help="Github token to access to repository.", 196 | # required=True, 197 | ) 198 | parser.add_argument( 199 | "--repo", 200 | help="Github repository (default: %(default)s).", 201 | default=subprocess.run( 202 | ["git", "config", "--get", "remote.origin.url"], 203 | stdout=subprocess.PIPE, 204 | check=True, 205 | ) 206 | .stdout.decode("UTF-8") 207 | .replace("https://github.com/", "") 208 | .replace(".git", "") 209 | .strip(), 210 | ) 211 | parser.add_argument( 212 | "--release", 213 | help="Github release tag to update release notes.", 214 | ) 215 | arguments = parser.parse_args() 216 | 217 | if arguments.verbose: 218 | _LOGGER.setLevel(logging.DEBUG) 219 | 220 | if arguments.dry_run: 221 | _LOGGER.debug("Dry run mode ENABLED") 222 | print("!!! Dry Run !!!") 223 | 224 | github = Github(arguments.token) 225 | _LOGGER.debug("Repo: %s", arguments.repo) 226 | repo = github.get_repo(arguments.repo) 227 | if arguments.release is None: 228 | changes = gen_changes(repo)[0] 229 | _LOGGER.debug(changes) 230 | if changes != NOCHANGE: 231 | version = Version(get_release_tags(repo)[0].name.lstrip("v")) 232 | _LOGGER.debug(version) 233 | new_version = bump_version(version) 234 | _LOGGER.debug(new_version) 235 | print(f"Generated release notes for v{new_version}:\n{changes}") 236 | else: 237 | print("Not enough changes for a release.") 238 | else: 239 | tag = arguments.release.replace("refs/tags/", "") 240 | _LOGGER.debug("Release tag: %s", tag) 241 | version = Version(tag) 242 | (_, human_changes, bot_changes) = gen_changes(repo, tag) 243 | msg = BODY.format( 244 | repo=arguments.repo, 245 | version=str(version), 246 | changes=human_changes, 247 | bot_changes=bot_changes, 248 | ) 249 | if arguments.dry_run: 250 | print("Is prerelease:", version.is_prerelease) 251 | print("Generated release notes:\n" + msg) 252 | else: 253 | release = repo.get_release(tag) 254 | release.update_release( 255 | name=tag, 256 | prerelease=version.is_prerelease, 257 | draft=release.draft, 258 | message=msg, 259 | ) 260 | 261 | 262 | if __name__ == "__main__": 263 | main() 264 | -------------------------------------------------------------------------------- /custom_components/car_wash/binary_sensor.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2019-2021, Andrey "Limych" Khrolenok 2 | # Creative Commons BY-NC-SA 4.0 International Public License 3 | # (see LICENSE.md or https://creativecommons.org/licenses/by-nc-sa/4.0/) 4 | """ 5 | The Car Wash binary sensor. 6 | 7 | For more details about this platform, please refer to the documentation at 8 | https://github.com/Limych/ha-car_wash/ 9 | """ 10 | 11 | import logging 12 | from datetime import datetime 13 | 14 | import voluptuous as vol 15 | from homeassistant.components.binary_sensor import BinarySensorEntity 16 | from homeassistant.components.weather import ( 17 | ATTR_FORECAST_CONDITION, 18 | ATTR_FORECAST_PRECIPITATION, 19 | ATTR_FORECAST_TEMP, 20 | ATTR_FORECAST_TEMP_LOW, 21 | ATTR_FORECAST_TIME, 22 | ATTR_WEATHER_TEMPERATURE, 23 | SERVICE_GET_FORECASTS, 24 | WeatherEntityFeature, 25 | ) 26 | from homeassistant.components.weather import ( 27 | DOMAIN as WEATHER_DOMAIN, 28 | ) 29 | from homeassistant.const import ( 30 | ATTR_SUPPORTED_FEATURES, 31 | CONF_ENTITY_ID, 32 | CONF_NAME, 33 | CONF_TYPE, 34 | CONF_UNIQUE_ID, 35 | EVENT_HOMEASSISTANT_START, 36 | UnitOfTemperature, 37 | ) 38 | from homeassistant.core import Event, HomeAssistant, callback 39 | from homeassistant.exceptions import HomeAssistantError 40 | from homeassistant.helpers import config_validation as cv 41 | from homeassistant.helpers.entity_platform import AddEntitiesCallback 42 | from homeassistant.helpers.event import async_track_state_change_event 43 | from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType 44 | from homeassistant.util import dt as dt_util 45 | from homeassistant.util.unit_conversion import TemperatureConverter 46 | 47 | from .const import ( 48 | BAD_CONDITIONS, 49 | CONF_DAYS, 50 | CONF_WEATHER, 51 | DEFAULT_DAYS, 52 | DEFAULT_NAME, 53 | DOMAIN, 54 | ICON, 55 | STARTUP_MESSAGE, 56 | ) 57 | 58 | _LOGGER = logging.getLogger(__name__) 59 | 60 | PLATFORM_SCHEMA = cv.PLATFORM_SCHEMA.extend( 61 | { 62 | vol.Required(CONF_WEATHER): cv.entity_id, 63 | vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, 64 | vol.Optional(CONF_DAYS, default=DEFAULT_DAYS): cv.positive_int, 65 | vol.Optional(CONF_UNIQUE_ID): cv.string, 66 | } 67 | ) 68 | 69 | 70 | # pylint: disable=unused-argument 71 | async def async_setup_platform( 72 | hass: HomeAssistant, # noqa: ARG001 73 | config: ConfigType, 74 | async_add_entities: AddEntitiesCallback, 75 | discovery_info: DiscoveryInfoType = None, # noqa: ARG001 76 | ) -> None: 77 | """Set up the Car Wash sensor.""" 78 | # Print startup message 79 | _LOGGER.info(STARTUP_MESSAGE) 80 | 81 | async_add_entities( 82 | [ 83 | CarWashBinarySensor( 84 | config.get(CONF_UNIQUE_ID), 85 | config.get(CONF_NAME), 86 | config.get(CONF_WEATHER), 87 | config.get(CONF_DAYS), 88 | ) 89 | ] 90 | ) 91 | 92 | 93 | class CarWashBinarySensor(BinarySensorEntity): 94 | """Implementation of an Car Wash binary sensor.""" 95 | 96 | def __init__( 97 | self, 98 | unique_id: str | None, 99 | friendly_name: str, 100 | weather_entity: str, 101 | days: int, 102 | ) -> None: 103 | """Initialize the sensor.""" 104 | self._weather_entity = weather_entity 105 | self._days = days 106 | 107 | self._attr_should_poll = False # No polling needed 108 | self._attr_name = friendly_name 109 | self._attr_is_on = None 110 | self._attr_icon = ICON 111 | self._attr_device_class = f"{DOMAIN}__" 112 | # 113 | self._attr_unique_id = ( 114 | DOMAIN + "-" + str(self._weather_entity).split(".")[1] 115 | if unique_id == "__legacy__" 116 | else unique_id 117 | ) 118 | 119 | @property 120 | def available(self) -> bool: 121 | """Return True if entity is available.""" 122 | return self._attr_is_on is not None 123 | 124 | async def async_added_to_hass(self) -> None: 125 | """Register callbacks.""" 126 | 127 | # pylint: disable=unused-argument 128 | @callback 129 | def sensor_state_listener(event: Event) -> None: # noqa: ARG001 130 | """Handle device state changes.""" 131 | self.async_schedule_update_ha_state(force_refresh=True) 132 | 133 | # pylint: disable=unused-argument 134 | @callback 135 | def sensor_startup(event: Event) -> None: # noqa: ARG001 136 | """Update template on startup.""" 137 | async_track_state_change_event( 138 | self.hass, [self._weather_entity], sensor_state_listener 139 | ) 140 | 141 | self.async_schedule_update_ha_state(force_refresh=True) 142 | 143 | self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, sensor_startup) 144 | 145 | @staticmethod 146 | def _temp2c(temperature: float | None, temperature_unit: str) -> float | None: 147 | """Convert weather temperature to Celsius degree.""" 148 | if temperature is not None and temperature_unit != UnitOfTemperature.CELSIUS: 149 | temperature = TemperatureConverter.convert( 150 | temperature, temperature_unit, UnitOfTemperature.CELSIUS 151 | ) 152 | return temperature 153 | 154 | # pylint: disable=too-many-branches,too-many-statements 155 | async def async_update(self) -> None: # noqa: PLR0912, PLR0915 156 | """Update the sensor state.""" 157 | wstate = self.hass.states.get(self._weather_entity) 158 | if wstate is None: 159 | msg = f"Unable to find an entity called {self._weather_entity}" 160 | raise HomeAssistantError(msg) 161 | 162 | tmpu = self.hass.config.units.temperature_unit 163 | temp = wstate.attributes.get(ATTR_WEATHER_TEMPERATURE) 164 | cond = wstate.state 165 | 166 | wfeatures = wstate.attributes.get(ATTR_SUPPORTED_FEATURES) or 0 167 | if (wfeatures & WeatherEntityFeature.FORECAST_DAILY) != 0: 168 | forecast_type = "daily" 169 | elif (wfeatures & WeatherEntityFeature.FORECAST_TWICE_DAILY) != 0: 170 | forecast_type = "twice_daily" 171 | elif (wfeatures & WeatherEntityFeature.FORECAST_HOURLY) != 0: 172 | forecast_type = "hourly" 173 | else: 174 | msg = "Weather entity doesn't support any forecast" 175 | raise HomeAssistantError(msg) 176 | 177 | try: 178 | forecast = await self.hass.services.async_call( 179 | WEATHER_DOMAIN, 180 | SERVICE_GET_FORECASTS, 181 | { 182 | CONF_TYPE: forecast_type, 183 | CONF_ENTITY_ID: self._weather_entity, 184 | }, 185 | blocking=True, 186 | return_response=True, 187 | ) 188 | except HomeAssistantError as ex: 189 | self._attr_is_on = None 190 | msg = "Can't get forecast data! Are you sure it's the weather provider?" 191 | raise HomeAssistantError(msg) from ex 192 | 193 | _LOGGER.debug("Current temperature %s, condition '%s'", temp, cond) 194 | 195 | temp = self._temp2c(temp, tmpu) 196 | 197 | if cond in BAD_CONDITIONS: 198 | _LOGGER.debug("Detected bad weather condition") 199 | self._attr_is_on = False 200 | return 201 | 202 | today = dt_util.start_of_local_day() 203 | cur_date = today.strftime("%F") 204 | stop_date = datetime.fromtimestamp( 205 | today.timestamp() + 86400 * (self._days + 1), 206 | tz=dt_util.DEFAULT_TIME_ZONE, 207 | ).strftime("%F") 208 | 209 | _LOGGER.debug("Inspect weather forecast from now till %s", stop_date) 210 | for fcast in forecast[self._weather_entity]["forecast"]: 211 | fc_date = fcast.get(ATTR_FORECAST_TIME) 212 | if isinstance(fc_date, int): 213 | fc_date = dt_util.as_local( 214 | datetime.fromtimestamp(fc_date / 1000, dt_util.UTC) 215 | ).strftime("%F") 216 | elif isinstance(fc_date, datetime): 217 | fc_date = dt_util.as_local(fc_date).strftime("%F") 218 | if fc_date < cur_date: 219 | continue 220 | if fc_date == stop_date: 221 | break 222 | _LOGGER.debug("Inspect weather forecast for %s", fc_date) 223 | 224 | prec = fcast.get(ATTR_FORECAST_PRECIPITATION) 225 | cond = fcast.get(ATTR_FORECAST_CONDITION) 226 | tmin = fcast.get(ATTR_FORECAST_TEMP_LOW) 227 | tmax = fcast.get(ATTR_FORECAST_TEMP) 228 | _LOGGER.debug( 229 | "Precipitation %s, Condition '%s'," 230 | " Min temperature: %s, Max temperature %s", 231 | prec, 232 | cond, 233 | tmin, 234 | tmax, 235 | ) 236 | 237 | if prec and prec != "null": 238 | _LOGGER.debug("Precipitation detected") 239 | self._attr_is_on = False 240 | return 241 | if cond in BAD_CONDITIONS: 242 | _LOGGER.debug("Detected bad weather condition") 243 | self._attr_is_on = False 244 | return 245 | if tmin is not None and fc_date != cur_date: 246 | tmin = self._temp2c(tmin, tmpu) 247 | if temp < 0 <= tmin: 248 | _LOGGER.debug( 249 | "Detected passage of temperature through melting point" 250 | ) 251 | self._attr_is_on = False 252 | return 253 | temp = tmin 254 | if tmax is not None: 255 | tmax = self._temp2c(tmax, tmpu) 256 | if temp < 0 <= tmax: 257 | _LOGGER.debug( 258 | "Detected passage of temperature through melting point" 259 | ) 260 | self._attr_is_on = False 261 | return 262 | temp = tmax 263 | 264 | _LOGGER.debug("Inspection done. No bad forecast detected") 265 | self._attr_is_on = True 266 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | ## creative commons 2 | 3 | # Attribution-NonCommercial-ShareAlike 4.0 International License 4 | 5 | Copyright (c) 2019-2022 Andrey "Limych" Khrolenok 6 | 7 | Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. 8 | 9 | ### Using Creative Commons Public Licenses 10 | 11 | Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. 12 | 13 | * __Considerations for licensors:__ Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. [More considerations for licensors](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors). 14 | 15 | * __Considerations for the public:__ By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. [More considerations for the public](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees). 16 | 17 | ## Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License 18 | 19 | By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. 20 | 21 | ### Section 1 – Definitions. 22 | 23 | a. __Adapted Material__ means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. 24 | 25 | b. __Adapter's License__ means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. 26 | 27 | c. __BY-NC-SA Compatible License__ means a license listed at [creativecommons.org/compatiblelicenses](http://creativecommons.org/compatiblelicenses), approved by Creative Commons as essentially the equivalent of this Public License. 28 | 29 | d. __Copyright and Similar Rights__ means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. 30 | 31 | e. __Effective Technological Measures__ means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. 32 | 33 | f. __Exceptions and Limitations__ means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. 34 | 35 | g. __License Elements__ means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution, NonCommercial, and ShareAlike. 36 | 37 | h. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License. 38 | 39 | i. __Licensed Rights__ means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. 40 | 41 | j. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License. 42 | 43 | k. __NonCommercial__ means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange. 44 | 45 | l. __Share__ means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. 46 | 47 | m. __Sui Generis Database Rights__ means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. 48 | 49 | n. __You__ means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. 50 | 51 | ### Section 2 – Scope. 52 | 53 | a. ___License grant.___ 54 | 55 | 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: 56 | 57 | A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and 58 | 59 | B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only. 60 | 61 | 2. __Exceptions and Limitations.__ For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. 62 | 63 | 3. __Term.__ The term of this Public License is specified in Section 6(a). 64 | 65 | 4. __Media and formats; technical modifications allowed.__ The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. 66 | 67 | 5. __Downstream recipients.__ 68 | 69 | A. __Offer from the Licensor – Licensed Material.__ Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. 70 | 71 | B. __Additional offer from the Licensor – Adapted Material.__ Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter’s License You apply. 72 | 73 | C. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. 74 | 75 | 6. __No endorsement.__ Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). 76 | 77 | b. ___Other rights.___ 78 | 79 | 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. 80 | 81 | 2. Patent and trademark rights are not licensed under this Public License. 82 | 83 | 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes. 84 | 85 | ### Section 3 – License Conditions. 86 | 87 | Your exercise of the Licensed Rights is expressly made subject to the following conditions. 88 | 89 | a. ___Attribution.___ 90 | 91 | 1. If You Share the Licensed Material (including in modified form), You must: 92 | 93 | A. retain the following if it is supplied by the Licensor with the Licensed Material: 94 | 95 | i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); 96 | 97 | ii. a copyright notice; 98 | 99 | iii. a notice that refers to this Public License; 100 | 101 | iv. a notice that refers to the disclaimer of warranties; 102 | 103 | v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; 104 | 105 | B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and 106 | 107 | C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. 108 | 109 | 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. 110 | 111 | 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. 112 | 113 | b. ___ShareAlike.___ 114 | 115 | In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply. 116 | 117 | 1. The Adapter’s License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-NC-SA Compatible License. 118 | 119 | 2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material. 120 | 121 | 3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply. 122 | 123 | ### Section 4 – Sui Generis Database Rights. 124 | 125 | Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: 126 | 127 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only; 128 | 129 | b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and 130 | 131 | c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. 132 | 133 | For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. 134 | 135 | ### Section 5 – Disclaimer of Warranties and Limitation of Liability. 136 | 137 | a. __Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.__ 138 | 139 | b. __To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.__ 140 | 141 | c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. 142 | 143 | ### Section 6 – Term and Termination. 144 | 145 | a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. 146 | 147 | b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: 148 | 149 | 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or 150 | 151 | 2. upon express reinstatement by the Licensor. 152 | 153 | For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. 154 | 155 | c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. 156 | 157 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. 158 | 159 | ### Section 7 – Other Terms and Conditions. 160 | 161 | a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. 162 | 163 | b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. 164 | 165 | ### Section 8 – Interpretation. 166 | 167 | a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. 168 | 169 | b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. 170 | 171 | c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. 172 | 173 | d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. 174 | 175 | > Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. 176 | > 177 | > Creative Commons may be contacted at creativecommons.org 178 | --------------------------------------------------------------------------------