initial api
This commit is contained in:
1 parent
899d78fba5
commit
e87c41f496
16 files changed
+458
-2
No files matched your search
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"python.formatting.provider": "black"
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
VENV_FOLDER=./venv
|
||||
VENV_BIN=$(VENV_FOLDER)/bin
|
||||
PIP=$(VENV_BIN)/pip
|
||||
PYTHON=$(VENV_BIN)/python
|
||||
|
||||
setup:
|
||||
rm -rf $(VENV_FOLDER)
|
||||
python3 -m venv $(VENV_FOLDER)
|
||||
$(PIP) install wheel==0.35.1
|
||||
$(PIP) install .[dev,boto]
|
||||
$(VENV_BIN)/pre-commit install
|
||||
|
||||
lint:
|
||||
$(VENV_BIN)/vulture --exclude src
|
||||
$(MAKE) lint-project
|
||||
$(MAKE) lint-tests
|
||||
|
||||
lint-project:
|
||||
$(VENV_BIN)/black src
|
||||
$(VENV_BIN)/isort --trailing-comma src
|
||||
$(VENV_BIN)/mypy src
|
||||
|
||||
|
||||
lint-tests:
|
||||
$(VENV_BIN)/black tests
|
||||
$(VENV_BIN)/isort --trailing-comma tests
|
||||
$(VENV_BIN)/mypy tests
|
||||
|
||||
security-checks:
|
||||
$(VENV_BIN)/bandit -r src
|
||||
|
||||
test:
|
||||
$(PYTHON) -m unittest discover tests
|
||||
|
||||
coverage:
|
||||
$(VENV_BIN)/coverage run -m unittest discover tests
|
||||
$(VENV_BIN)/coverage report -m --fail-under=90
|
||||
|
||||
clean:
|
||||
rm -rf dist *.sqlite *.egg-info build .mypy_cache .coverage
|
||||
find . -type d -name "__pycache__" -exec rm -r {} +
|
||||
find . -type d -name "*tmp" -exec rm -r {} +
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
import setuptools # type: ignore
|
||||
|
||||
setuptools.setup(
|
||||
python_requires=">=3.7",
|
||||
install_requires=[
|
||||
"ruamel.yaml==0.17.17",
|
||||
"SQLAlchemy==1.4.26",
|
||||
"fastapi==0.70.0",
|
||||
"pydantic==1.8.2",
|
||||
"uvicorn[standard]==0.15.0",
|
||||
"python-decouple==3.5",
|
||||
],
|
||||
extras_require={
|
||||
"dev": [
|
||||
"mypy==0.910",
|
||||
"mypy-extensions==0.4.3",
|
||||
"black==21.7b0",
|
||||
"bandit==1.7.0",
|
||||
"isort==5.9.3",
|
||||
"coverage==5.5",
|
||||
"pre-commit==2.13.0",
|
||||
"vulture==2.3",
|
||||
"types-requests==2.25.6",
|
||||
],
|
||||
},
|
||||
)
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,154 @@
|
||||
"""
|
||||
Helper functions for config.
|
||||
"""
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from ruamel.yaml import YAML
|
||||
from ruamel.yaml.constructor import SafeConstructor
|
||||
|
||||
|
||||
_CONFIGURATION_PATH: Optional[Path] = None
|
||||
|
||||
|
||||
def find_hass_config() -> Path:
|
||||
"""Try to find HASS config."""
|
||||
if "HASSIO_TOKEN" in os.environ:
|
||||
return Path("/config")
|
||||
|
||||
"""Put together the default configuration directory based on the OS."""
|
||||
data_dir = Path(
|
||||
os.getenv("APPDATA") if os.name == "nt" else os.path.expanduser("~")
|
||||
)
|
||||
config_dir = data_dir / ".homeassistant"
|
||||
|
||||
if config_dir.is_dir():
|
||||
return config_dir
|
||||
|
||||
raise ValueError(
|
||||
"Unable to automatically find the location of Home Assistant "
|
||||
"config. Please pass it in."
|
||||
)
|
||||
|
||||
|
||||
class HassSafeConstructor(SafeConstructor):
|
||||
"""Hass specific SafeConstructor."""
|
||||
|
||||
|
||||
def _secret_yaml(loader, node):
|
||||
"""Load secrets and embed it into the configuration YAML."""
|
||||
dirpath = Path(os.path.dirname(loader.name))
|
||||
|
||||
# Recursively search for the secrets.yaml file
|
||||
# this might be needed when a yaml file is included like
|
||||
# `!included folder/file.yaml`. Same rules as
|
||||
# https://www.home-assistant.io/docs/configuration/secrets/#debugging-secrets
|
||||
fname = dirpath / "secrets.yaml"
|
||||
for _ in range(len(dirpath.parts)):
|
||||
if fname.exists() or (
|
||||
_CONFIGURATION_PATH is not None
|
||||
and _CONFIGURATION_PATH.exists()
|
||||
and dirpath.samefile(_CONFIGURATION_PATH)
|
||||
):
|
||||
break
|
||||
dirpath = dirpath.parent
|
||||
fname = dirpath / "secrets.yaml"
|
||||
|
||||
try:
|
||||
with fname.open() as secret_file:
|
||||
secrets = YAML(typ="safe").load(secret_file)
|
||||
except FileNotFoundError:
|
||||
raise ValueError("Secrets file {} not found".format(fname)) from None
|
||||
|
||||
try:
|
||||
return secrets[node.value]
|
||||
except KeyError:
|
||||
raise ValueError("Secret {} not found".format(node.value)) from None
|
||||
|
||||
|
||||
def _include_yaml(loader, node):
|
||||
"""Load another YAML file and embeds it using the !include tag.
|
||||
|
||||
Example:
|
||||
device_tracker: !include device_tracker.yaml
|
||||
"""
|
||||
dirpath = Path(os.path.dirname(loader.name))
|
||||
fname = dirpath / node.value
|
||||
for _ in range(len(dirpath.parts)):
|
||||
if fname.exists() or (
|
||||
_CONFIGURATION_PATH is not None
|
||||
and _CONFIGURATION_PATH.exists()
|
||||
and dirpath.samefile(_CONFIGURATION_PATH)
|
||||
):
|
||||
break
|
||||
dirpath = dirpath.parent
|
||||
fname = dirpath / node.value
|
||||
|
||||
return load_yaml(os.path.join(dirpath, node.value))
|
||||
|
||||
|
||||
def _stub_tag(constructor, node):
|
||||
"""Stub a constructor with a dictionary."""
|
||||
seen = getattr(constructor, "_stub_seen", None)
|
||||
|
||||
if seen is None:
|
||||
seen = constructor._stub_seen = set()
|
||||
|
||||
if node.tag not in seen:
|
||||
print("YAML tag {} is not supported".format(node.tag))
|
||||
seen.add(node.tag)
|
||||
|
||||
return {}
|
||||
|
||||
|
||||
HassSafeConstructor.add_constructor("!include", _include_yaml)
|
||||
HassSafeConstructor.add_constructor("!env_var", _stub_tag)
|
||||
HassSafeConstructor.add_constructor("!secret", _secret_yaml)
|
||||
HassSafeConstructor.add_constructor("!include_dir_list", _stub_tag)
|
||||
HassSafeConstructor.add_constructor("!include_dir_merge_list", _stub_tag)
|
||||
HassSafeConstructor.add_constructor("!include_dir_named", _stub_tag)
|
||||
HassSafeConstructor.add_constructor("!include_dir_merge_named", _stub_tag)
|
||||
|
||||
|
||||
def load_hass_config(path):
|
||||
"""Load the HASS config."""
|
||||
return load_yaml(os.path.join(path, "configuration.yaml"))
|
||||
|
||||
|
||||
def load_yaml(fname):
|
||||
"""Load a YAML file."""
|
||||
yaml = YAML(typ="safe")
|
||||
# Compat with HASS
|
||||
yaml.allow_duplicate_keys = True
|
||||
# Stub HASS constructors
|
||||
HassSafeConstructor.name = fname
|
||||
yaml.Constructor = HassSafeConstructor
|
||||
|
||||
with open(fname, encoding="utf-8") as conf_file:
|
||||
# If configuration file is empty YAML returns None
|
||||
# We convert that to an empty dict
|
||||
return yaml.load(conf_file) or {}
|
||||
|
||||
|
||||
def db_url_from_hass_config(path):
|
||||
"""Find the recorder database url from a HASS config dir."""
|
||||
global _CONFIGURATION_PATH
|
||||
_CONFIGURATION_PATH = Path(path).resolve()
|
||||
config = load_hass_config(path)
|
||||
default_path = os.path.join(path, "home-assistant_v2.db")
|
||||
default_url = "sqlite:///{}".format(default_path)
|
||||
|
||||
recorder = config.get("recorder")
|
||||
|
||||
if recorder:
|
||||
db_url = recorder.get("db_url")
|
||||
if db_url is not None:
|
||||
return db_url
|
||||
|
||||
if not os.path.isfile(default_path):
|
||||
raise ValueError(
|
||||
"Unable to determine DB url from hass config at {}".format(path)
|
||||
)
|
||||
|
||||
return default_url
|
||||
@@ -0,0 +1,48 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
from .globals import CONFIGURATION_PATH
|
||||
from .configuration_parser import load_hass_config
|
||||
|
||||
|
||||
def find_hass_config() -> Path:
|
||||
"""Try to find HASS config."""
|
||||
if "HASSIO_TOKEN" in os.environ:
|
||||
return Path("/config")
|
||||
|
||||
"""Put together the default configuration directory based on the OS."""
|
||||
data_dir = Path(
|
||||
os.getenv("APPDATA") if os.name == "nt" else os.path.expanduser("~")
|
||||
)
|
||||
config_dir = data_dir / ".homeassistant"
|
||||
|
||||
if config_dir.is_dir():
|
||||
return config_dir
|
||||
|
||||
raise ValueError(
|
||||
"Unable to automatically find the location of Home Assistant "
|
||||
"config. Please pass it in."
|
||||
)
|
||||
|
||||
|
||||
def db_url_from_hass_config(path: Path):
|
||||
"""Find the recorder database url from a HASS config dir."""
|
||||
global CONFIGURATION_PATH
|
||||
CONFIGURATION_PATH = path.resolve()
|
||||
config = load_hass_config(path)
|
||||
|
||||
recorder = config.get("recorder")
|
||||
|
||||
if recorder:
|
||||
db_url = recorder.get("db_url")
|
||||
if db_url is not None:
|
||||
return db_url
|
||||
|
||||
default_path = path / "home-assistant_v2.db"
|
||||
default_url = f"sqlite:///{default_path.absolute()}"
|
||||
|
||||
if not os.path.isfile(default_path):
|
||||
raise ValueError(
|
||||
"Unable to determine DB url from hass config at {}".format(path)
|
||||
)
|
||||
|
||||
return default_url
|
||||
@@ -0,0 +1,105 @@
|
||||
import os
|
||||
|
||||
from pathlib import Path
|
||||
from ruamel.yaml import YAML
|
||||
from ruamel.yaml.constructor import SafeConstructor
|
||||
from .globals import CONFIGURATION_PATH
|
||||
|
||||
|
||||
class HassSafeConstructor(SafeConstructor):
|
||||
"""Hass specific SafeConstructor."""
|
||||
|
||||
|
||||
def _secret_yaml(loader, node):
|
||||
"""Load secrets and embed it into the configuration YAML."""
|
||||
dirpath = Path(os.path.dirname(loader.name))
|
||||
|
||||
# Recursively search for the secrets.yaml file
|
||||
# this might be needed when a yaml file is included like
|
||||
# `!included folder/file.yaml`. Same rules as
|
||||
# https://www.home-assistant.io/docs/configuration/secrets/#debugging-secrets
|
||||
fname = dirpath / "secrets.yaml"
|
||||
for _ in range(len(dirpath.parts)):
|
||||
if fname.exists() or (
|
||||
CONFIGURATION_PATH is not None
|
||||
and CONFIGURATION_PATH.exists()
|
||||
and dirpath.samefile(CONFIGURATION_PATH)
|
||||
):
|
||||
break
|
||||
dirpath = dirpath.parent
|
||||
fname = dirpath / "secrets.yaml"
|
||||
|
||||
try:
|
||||
with fname.open() as secret_file:
|
||||
secrets = YAML(typ="safe").load(secret_file)
|
||||
except FileNotFoundError:
|
||||
raise ValueError("Secrets file {} not found".format(fname)) from None
|
||||
|
||||
try:
|
||||
return secrets[node.value]
|
||||
except KeyError:
|
||||
raise ValueError("Secret {} not found".format(node.value)) from None
|
||||
|
||||
|
||||
def _include_yaml(loader, node):
|
||||
"""Load another YAML file and embeds it using the !include tag.
|
||||
|
||||
Example:
|
||||
device_tracker: !include device_tracker.yaml
|
||||
"""
|
||||
dirpath = Path(os.path.dirname(loader.name))
|
||||
fname = dirpath / node.value
|
||||
for _ in range(len(dirpath.parts)):
|
||||
if fname.exists() or (
|
||||
CONFIGURATION_PATH is not None
|
||||
and CONFIGURATION_PATH.exists()
|
||||
and dirpath.samefile(CONFIGURATION_PATH)
|
||||
):
|
||||
break
|
||||
dirpath = dirpath.parent
|
||||
fname = dirpath / node.value
|
||||
|
||||
return load_yaml(os.path.join(dirpath, node.value))
|
||||
|
||||
|
||||
def _stub_tag(constructor, node):
|
||||
"""Stub a constructor with a dictionary."""
|
||||
seen = getattr(constructor, "_stub_seen", None)
|
||||
|
||||
if seen is None:
|
||||
seen = constructor._stub_seen = set()
|
||||
|
||||
if node.tag not in seen:
|
||||
print("YAML tag {} is not supported".format(node.tag))
|
||||
seen.add(node.tag)
|
||||
|
||||
return {}
|
||||
|
||||
|
||||
HassSafeConstructor.add_constructor("!include", _include_yaml)
|
||||
HassSafeConstructor.add_constructor("!env_var", _stub_tag)
|
||||
HassSafeConstructor.add_constructor("!secret", _secret_yaml)
|
||||
HassSafeConstructor.add_constructor("!include_dir_list", _stub_tag)
|
||||
HassSafeConstructor.add_constructor("!include_dir_merge_list", _stub_tag)
|
||||
HassSafeConstructor.add_constructor("!include_dir_named", _stub_tag)
|
||||
HassSafeConstructor.add_constructor("!include_dir_merge_named", _stub_tag)
|
||||
|
||||
|
||||
def load_hass_config(dir_path: Path):
|
||||
"""Load the HASS config."""
|
||||
return load_yaml(dir_path / "configuration.yaml")
|
||||
|
||||
|
||||
def load_yaml(file_path: Path):
|
||||
"""Load a YAML file."""
|
||||
yaml = YAML(typ="safe")
|
||||
# Compat with HASS
|
||||
yaml.allow_duplicate_keys = True
|
||||
# Stub HASS constructors
|
||||
HassSafeConstructor.name = str(file_path.absolute())
|
||||
yaml.Constructor = HassSafeConstructor
|
||||
|
||||
with file_path.open(encoding="utf-8") as conf_file:
|
||||
# If configuration file is empty YAML returns None
|
||||
# We convert that to an empty dict
|
||||
return yaml.load(conf_file) or {}
|
||||
@@ -0,0 +1,6 @@
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
|
||||
# TODO: get rid of this
|
||||
CONFIGURATION_PATH: Optional[Path] = None
|
||||
@@ -0,0 +1,22 @@
|
||||
from sqlalchemy import create_engine, text
|
||||
from urllib.parse import urlparse
|
||||
|
||||
|
||||
class HassDatabase:
|
||||
def __init__(self, db_url: str) -> None:
|
||||
self.url = urlparse(db_url)
|
||||
self.entities = None
|
||||
try:
|
||||
self.engine = create_engine(db_url)
|
||||
except Exception as exc:
|
||||
if isinstance(exc, ImportError):
|
||||
raise RuntimeError(
|
||||
"The right dependency to connect to your database is "
|
||||
"missing. Please make sure that it is installed."
|
||||
) from exc
|
||||
|
||||
raise
|
||||
|
||||
@property
|
||||
def db_type(self):
|
||||
return self.url.scheme.split("+")[0]
|
||||
@@ -0,0 +1,4 @@
|
||||
from decouple import config
|
||||
|
||||
|
||||
BUILD_VERSION = config("BUILD_VERSION", "0.0.0")
|
||||
@@ -0,0 +1,16 @@
|
||||
from fastapi import FastAPI
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from datetime import datetime
|
||||
|
||||
from .env import BUILD_VERSION
|
||||
|
||||
app = FastAPI()
|
||||
app.mount("/web", StaticFiles(directory="web"), name="web")
|
||||
|
||||
|
||||
@app.get("/ping")
|
||||
def read_ping():
|
||||
return {
|
||||
"version": BUILD_VERSION,
|
||||
"current_time": datetime.now(),
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
- id: "1616887975473"
|
||||
alias: Home Assistant Off
|
||||
description: ""
|
||||
trigger:
|
||||
- platform: homeassistant
|
||||
event: shutdown
|
||||
condition: []
|
||||
action:
|
||||
- device_id: 2a98db84af7526c7ec3cc7aebd1a9e1c
|
||||
domain: mobile_app
|
||||
type: notify
|
||||
title: Hassio Status
|
||||
message: Hassio Is turning off...
|
||||
mode: single
|
||||
- id: "1616888026264"
|
||||
alias: Home Assistant On
|
||||
description: ""
|
||||
trigger:
|
||||
- platform: homeassistant
|
||||
event: start
|
||||
condition: []
|
||||
action:
|
||||
- device_id: 2a98db84af7526c7ec3cc7aebd1a9e1c
|
||||
domain: mobile_app
|
||||
type: notify
|
||||
title: Hassio Status
|
||||
message: Home assistant is up!
|
||||
+1
-1
@@ -32,7 +32,7 @@
|
||||
"scripts": {
|
||||
"develop": "concurrently -r \"npm:type-check:watch\" \"npm:start\"",
|
||||
"start": "parcel ./src/index.html",
|
||||
"build": "npm run type-check && parcel build ./src/index.html --public-url '/'",
|
||||
"build": "npm run type-check && parcel build ./src/index.html --public-url '/web'",
|
||||
"prettify": "prettier --write './src/**/*.{ts,tsx}'",
|
||||
"test": "jest",
|
||||
"test:watch": "jest --watch",
|
||||
|
||||
@@ -43,7 +43,7 @@ export default class ScriptDeviceState extends BaseState<DeviceScript> {
|
||||
<InputText
|
||||
textBoxFor="entity_id"
|
||||
label="Entity ID"
|
||||
value={state.entity_id}
|
||||
value={state.entity_id ?? ""}
|
||||
onChange={entity_id => this.setState({...state, entity_id, domain: entity_id.split('.')[0]})}
|
||||
/>
|
||||
</div>
|
||||
|
||||
Reference in new issue
Block a user