added a way to query entities

This commit is contained in:
Ari Sosnovsky committed 2021-11-10 11:17:43 -05:00
1 parent 759a002bce
commit c794661e05
18 files changed
+252 -172

No files matched your search

View File
Whitespace-only changes.
+1
View File
@@ -0,0 +1 @@
from .app import app
+16
View File
@@ -0,0 +1,16 @@
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from ..env import ROOT_FOLDER
from . import ping, search
app = FastAPI()
app.mount(
"/web",
StaticFiles(
directory=ROOT_FOLDER / "web",
html=True,
),
name="web",
)
app.include_router(ping.router, prefix="/ping")
app.include_router(search.router, prefix="/search")
+14
View File
@@ -0,0 +1,14 @@
from fastapi import APIRouter
from datetime import datetime
from ..env import BUILD_VERSION
router = APIRouter()
@router.get("/ping")
def read_ping():
return {
"version": BUILD_VERSION,
"current_time": datetime.now(),
}
+33
View File
@@ -0,0 +1,33 @@
from typing import Dict, Optional
from fastapi import APIRouter
from pydantic.main import BaseModel
from src.db import entities, connection
router = APIRouter()
db_connection = connection.HassDatabase(
"sqlite:////home/asosnovsky/LinuxProjects/random/Shortumation/api/tests/samples/home-assistant_v2.db"
)
class EntityRequest(BaseModel):
domain: Optional[str] = None
attributes: Optional[dict] = None
@router.post("/entity_id")
def search(
search_text: str,
offset: int = 0,
limit: int = 30,
filter_objects: Optional[EntityRequest] = EntityRequest(),
):
return entities.search(
db_connection,
search_text=search_text,
domain_filter=filter_objects.domain,
attributes_filter=filter_objects.attributes,
offset=offset,
limit=limit,
)
+9
View File
@@ -0,0 +1,9 @@
from typing import Literal
SearchObjects = Literal[
"entity_id",
"device_id",
"domain",
"event_type",
"statistic_id",
]
-154
View File
@@ -1,154 +0,0 @@
"""
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
View File
Whitespace-only changes.
@@ -8,6 +8,7 @@ class HassDatabase:
self.entities = None
try:
self.engine = create_engine(db_url)
self.connection = self.engine.connect()
except Exception as exc:
if isinstance(exc, ImportError):
raise RuntimeError(
@@ -20,3 +21,13 @@ class HassDatabase:
@property
def db_type(self):
return self.url.scheme.split("+")[0]
def execute_sql(self, sql: str, **args):
resp = self.engine.execute(text(sql), **args)
return resp.fetchall()
def close(self):
self.connection.close()
def __del__(self):
self.close()
+59
View File
@@ -0,0 +1,59 @@
import json
from pydantic import BaseModel
from typing import Dict, Iterable, List, Optional, Union
from .connection import HassDatabase
class Entity(BaseModel):
entity_id: str
domain: str
attributes: dict
def search(
db_connection: HassDatabase,
search_text: str,
offset: int = 0,
limit: int = 100,
domain_filter: Optional[str] = None,
attributes_filter: Optional[Dict[str, Union[str, bool, int, float]]] = None,
) -> Iterable[Entity]:
filter_sql = f"entity_id like '%%{search_text}%%' AND old_state_id is NULL"
if domain_filter:
filter_sql += f" AND `domain` like '%%{domain_filter}%%'"
for entity_id, domain, attributes_str in db_connection.execute_sql(
f"""
SELECT
entity_id,
`domain` ,
`attributes`
FROM
states
WHERE
{filter_sql}
LIMIT {offset}, {limit}
"""
):
attributes: dict = json.loads(attributes_str)
if attributes_filter:
if not _compare_attr(attributes, attributes_filter):
continue
yield Entity(
entity_id=entity_id,
domain=domain,
attributes=attributes,
)
def _compare_attr(attributes: dict, attributes_filter: dict) -> bool:
for attr_name, attr_value in attributes_filter.items():
if attr_name not in attributes:
return False
if not type(attributes[attr_name]) == type(attr_value):
return False
if isinstance(attr_value, str):
if attributes[attr_name].find(attr_value) < 0:
return False
if attributes[attr_name] != attr_value:
return False
return True
+2
View File
@@ -1,4 +1,6 @@
from decouple import config
from pathlib import Path
ROOT_FOLDER = Path(__file__).parent.parent
BUILD_VERSION = config("BUILD_VERSION", "0.0.0")
-16
View File
@@ -1,16 +0,0 @@
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(),
}