feat: add Home Assistant and NodeRED adapters (#764)

Adapters for Home Assistant and NodeRED integration are added.
Akkudoktor-EOS can now be run as Home Assistant add-on and standalone.

As Home Assistant add-on EOS uses ingress to fully integrate the EOSdash dashboard
in Home Assistant.

The fix includes several bug fixes that are not directly related to the adapter
implementation but are necessary to keep EOS running properly and to test and
document the changes.

* fix: development version scheme

  The development versioning scheme is adaptet to fit to docker and
  home assistant expectations. The new scheme is x.y.z and x.y.z.dev<hash>.
  Hash is only digits as expected by home assistant. Development version
  is appended by .dev as expected by docker.

* fix: use mean value in interval on resampling for array

  When downsampling data use the mean value of all values within the new
  sampling interval.

* fix: default battery ev soc and appliance wh

  Make the genetic simulation return default values for the
  battery SoC, electric vehicle SoC and appliance load if these
  assets are not used.

* fix: import json string

  Strip outer quotes from JSON strings on import to be compliant to json.loads()
  expectation.

* fix: default interval definition for import data

  Default interval must be defined in lowercase human definition to
  be accepted by pendulum.

* fix: clearoutside schema change

* feat: add adapters for integrations

  Adapters for Home Assistant and NodeRED integration are added.
  Akkudoktor-EOS can now be run as Home Assistant add-on and standalone.

  As Home Assistant add-on EOS uses ingress to fully integrate the EOSdash dashboard
  in Home Assistant.

* feat: allow eos to be started with root permissions and drop priviledges

  Home assistant starts all add-ons with root permissions. Eos now drops
  root permissions if an applicable user is defined by paramter --run_as_user.
  The docker image defines the user eos to be used.

* feat: make eos supervise and monitor EOSdash

  Eos now not only starts EOSdash but also monitors EOSdash during runtime
  and restarts EOSdash on fault. EOSdash logging is captured by EOS
  and forwarded to the EOS log to provide better visibility.

* feat: add duration to string conversion

  Make to_duration to also return the duration as string on request.

* chore: Use info logging to report missing optimization parameters

  In parameter preparation for automatic optimization an error was logged for missing paramters.
  Log is now down using the info level.

* chore: make EOSdash use the EOS data directory for file import/ export

  EOSdash use the EOS data directory for file import/ export by default.
  This allows to use the configuration import/ export function also
  within docker images.

* chore: improve EOSdash config tab display

  Improve display of JSON code and add more forms for config value update.

* chore: make docker image file system layout similar to home assistant

  Only use /data directory for persistent data. This is handled as a
  docker volume. The /data volume is mapped to ~/.local/share/net.akkudoktor.eos
  if using docker compose.

* chore: add home assistant add-on development environment

  Add VSCode devcontainer and task definition for home assistant add-on
  development.

* chore: improve documentation
This commit is contained in:
Bobby Noelte
2025-12-30 22:08:21 +01:00
committed by GitHub
parent 02c794460f
commit 58d70e417b
111 changed files with 6815 additions and 1199 deletions
+179 -51
View File
@@ -6,25 +6,37 @@ from pathlib import Path
import psutil
import uvicorn
from fasthtml.common import FileResponse, JSONResponse
from fasthtml.common import Base, FileResponse, JSONResponse
from loguru import logger
from monsterui.core import FastHTML, Theme
from starlette.middleware import Middleware
from starlette.requests import Request
from akkudoktoreos.config.config import get_config
from akkudoktoreos.core.logabc import LOGGING_LEVELS
from akkudoktoreos.core.logging import track_logging_config
from akkudoktoreos.core.logging import logging_track_config
from akkudoktoreos.core.version import __version__
from akkudoktoreos.server.dash.about import About
# Pages
from akkudoktoreos.server.dash.about import About
from akkudoktoreos.server.dash.admin import Admin
# helpers
from akkudoktoreos.server.dash.bokeh import BokehJS
from akkudoktoreos.server.dash.components import Page
from akkudoktoreos.server.dash.configuration import ConfigKeyUpdate, Configuration
from akkudoktoreos.server.dash.configuration import Configuration
from akkudoktoreos.server.dash.context import (
IngressMiddleware,
safe_asset_path,
)
from akkudoktoreos.server.dash.footer import Footer
from akkudoktoreos.server.dash.plan import Plan
from akkudoktoreos.server.dash.prediction import Prediction
from akkudoktoreos.server.server import get_default_host, wait_for_port_free
from akkudoktoreos.server.server import (
drop_root_privileges,
get_default_host,
wait_for_port_free,
)
from akkudoktoreos.utils.stringutil import str2bool
config_eos = get_config()
@@ -35,8 +47,8 @@ config_eos = get_config()
# ------------------------------------
logger.remove()
track_logging_config(config_eos, "logging", None, None)
config_eos.track_nested_value("/logging", track_logging_config)
logging_track_config(config_eos, "logging", None, None)
config_eos.track_nested_value("/logging", logging_track_config)
# ----------------------------
@@ -83,6 +95,12 @@ parser.add_argument(
default=False,
help="Enable or disable auto-reload. Useful for development. Options: True or False (default: False)",
)
parser.add_argument(
"--run_as_user",
type=str,
help="The unprivileged user account the EOSdash server shall run if started in root-level.",
)
# Command line arguments
args: argparse.Namespace
@@ -110,7 +128,7 @@ else:
# Ensure log_level from command line is in config settings
if config_eosdash["log_level"] in LOGGING_LEVELS:
# Setup console logging level using nested value
# - triggers logging configuration by track_logging_config
# - triggers logging configuration by logging_track_config
config_eos.set_nested_value("logging/console_level", config_eosdash["log_level"])
logger.debug(
f"logging/console_level configuration set by argument to {config_eosdash['log_level']}"
@@ -180,9 +198,11 @@ hdrs = (
# The EOSdash application
app: FastHTML = FastHTML(
title="EOSdash",
hdrs=hdrs,
secret_key=os.getenv("EOS_SERVER__EOSDASH_SESSKEY"),
title="EOSdash", # Default page title
hdrs=hdrs, # Additional FT elements to add to <HEAD>
# htmx=True, # Include HTMX header?
middleware=[Middleware(IngressMiddleware)],
secret_key=os.getenv("EOS_SERVER__EOSDASH_SESSKEY"), # Signing key for sessions
)
@@ -199,37 +219,60 @@ def eos_server() -> tuple[str, int]:
return config_eosdash["eos_host"], config_eosdash["eos_port"]
# -------------------------------------------------------------------
# Routes
# -------------------------------------------------------------------
@app.get("/favicon.ico")
def get_eosdash_favicon(): # type: ignore
"""Get favicon."""
def get_eosdash_favicon(request: Request): # type: ignore
"""Get the EOSdash favicon.
Args:
request (Request): The incoming FastHTML request.
Returns:
FileResponse: The favicon file.
"""
return FileResponse(path=favicon_filepath)
@app.get("/")
def get_eosdash(): # type: ignore
"""Serves the main EOSdash page.
def get_eosdash(request: Request): # type: ignore
"""Serve the main EOSdash page with navigation links.
Args:
request (Request): The incoming FastHTML request.
Returns:
Page: The main dashboard page with navigation links and footer.
"""
return Page(
None,
{
"Plan": "/eosdash/plan",
"Prediction": "/eosdash/prediction",
"Config": "/eosdash/configuration",
"Admin": "/eosdash/admin",
"About": "/eosdash/about",
},
About(),
Footer(*eos_server()),
"/eosdash/footer",
root_path: str = request.scope.get("root_path", "")
return (
Base(href=f"{root_path}/") if root_path else None,
Page(
None,
{
"Plan": "/eosdash/plan",
"Prediction": "/eosdash/prediction",
"Config": "/eosdash/configuration",
"Admin": "/eosdash/admin",
"About": "/eosdash/about",
},
About(),
Footer(*eos_server()),
"/eosdash/footer",
),
)
@app.get("/eosdash/footer")
def get_eosdash_footer(): # type: ignore
"""Serves the EOSdash Foooter information.
def get_eosdash_footer(request: Request): # type: ignore
"""Serve the EOSdash Footer information.
Args:
request (Request): The incoming FastHTML request.
Returns:
Footer: The Footer component.
@@ -238,8 +281,11 @@ def get_eosdash_footer(): # type: ignore
@app.get("/eosdash/about")
def get_eosdash_about(): # type: ignore
"""Serves the EOSdash About page.
def get_eosdash_about(request: Request): # type: ignore
"""Serve the EOSdash About page.
Args:
request (Request): The incoming FastHTML request.
Returns:
About: The About page component.
@@ -248,8 +294,11 @@ def get_eosdash_about(): # type: ignore
@app.get("/eosdash/admin")
def get_eosdash_admin(): # type: ignore
"""Serves the EOSdash Admin page.
def get_eosdash_admin(request: Request): # type: ignore
"""Serve the EOSdash Admin page.
Args:
request (Request): The incoming FastHTML request.
Returns:
Admin: The Admin page component.
@@ -258,10 +307,12 @@ def get_eosdash_admin(): # type: ignore
@app.post("/eosdash/admin")
def post_eosdash_admin(data: dict): # type: ignore
def post_eosdash_admin(request: Request, data: dict): # type: ignore
"""Provide control data to the Admin page.
This endpoint is called from within the Admin page on user actions.
Args:
request (Request): The incoming FastHTML request.
data (dict): User-submitted data from the Admin page.
Returns:
Admin: The Admin page component.
@@ -270,8 +321,11 @@ def post_eosdash_admin(data: dict): # type: ignore
@app.get("/eosdash/configuration")
def get_eosdash_configuration(): # type: ignore
"""Serves the EOSdash Configuration page.
def get_eosdash_configuration(request: Request): # type: ignore
"""Serve the EOSdash Configuration page.
Args:
request (Request): The incoming FastHTML request.
Returns:
Configuration: The Configuration page component.
@@ -280,13 +334,40 @@ def get_eosdash_configuration(): # type: ignore
@app.put("/eosdash/configuration")
def put_eosdash_configuration(data: dict): # type: ignore
return ConfigKeyUpdate(*eos_server(), data["key"], data["value"])
def put_eosdash_configuration(request: Request, data: dict): # type: ignore
"""Update a configuration key/value pair.
Args:
request (Request): The incoming FastHTML request.
data (dict): Dictionary containing 'key' and 'value' to trigger configuration update.
Returns:
Configuration: The Configuration page component with updated configuration.
"""
return Configuration(*eos_server(), data)
@app.post("/eosdash/configuration")
def post_eosdash_configuration(request: Request, data: dict): # type: ignore
"""Provide control data to the configuration page.
Args:
request (Request): The incoming FastHTML request.
data (dict): User-submitted data from the configuration page.
Returns:
Configuration: The Configuration page component with updated configuration.
"""
return Configuration(*eos_server(), data)
@app.get("/eosdash/plan")
def get_eosdash_plan(data: dict): # type: ignore
"""Serves the EOSdash Plan page.
def get_eosdash_plan(request: Request, data: dict): # type: ignore
"""Serve the EOSdash Plan page.
Args:
request (Request): The incoming FastHTML request.
data (dict): Optional query data.
Returns:
Plan: The Plan page component.
@@ -295,10 +376,12 @@ def get_eosdash_plan(data: dict): # type: ignore
@app.post("/eosdash/plan")
def post_eosdash_plan(data: dict): # type: ignore
def post_eosdash_plan(request: Request, data: dict): # type: ignore
"""Provide control data to the Plan page.
This endpoint is called from within the Plan page on user actions.
Args:
request (Request): The incoming FastHTML request.
data (dict): User-submitted data from the Plan page.
Returns:
Plan: The Plan page component.
@@ -307,8 +390,12 @@ def post_eosdash_plan(data: dict): # type: ignore
@app.get("/eosdash/prediction")
def get_eosdash_prediction(data: dict): # type: ignore
"""Serves the EOSdash Prediction page.
def get_eosdash_prediction(request: Request, data: dict): # type: ignore
"""Serve the EOSdash Prediction page.
Args:
request (Request): The incoming FastHTML request.
data (dict): Optional query data.
Returns:
Prediction: The Prediction page component.
@@ -317,8 +404,15 @@ def get_eosdash_prediction(data: dict): # type: ignore
@app.get("/eosdash/health")
def get_eosdash_health(): # type: ignore
"""Health check endpoint to verify that the EOSdash server is alive."""
def get_eosdash_health(request: Request): # type: ignore
"""Health check endpoint to verify the EOSdash server is alive.
Args:
request (Request): The incoming FastHTML request.
Returns:
JSONResponse: Server status including PID and version.
"""
return JSONResponse(
{
"status": "alive",
@@ -328,13 +422,37 @@ def get_eosdash_health(): # type: ignore
)
@app.get("/eosdash/assets/{fname:path}.{ext:static}")
def get_eosdash_assets(fname: str, ext: str): # type: ignore
"""Get assets."""
asset_filepath = Path(__file__).parent.joinpath(f"dash/assets/{fname}.{ext}")
@app.get("/eosdash/assets/{filepath:path}")
def get_eosdash_assets(request: Request, filepath: str): # type: ignore
"""Serve static assets for EOSdash safely.
Args:
request (Request): The incoming FastHTML request.
filepath (str): Relative path of the asset under dash/assets/.
Returns:
FileResponse: The requested asset file if it exists.
Raises:
404: If the file does not exist.
403: If the file path is forbidden (directory traversal attempt).
"""
try:
asset_filepath = safe_asset_path(filepath)
except ValueError:
return {"error": "Forbidden"}, 403
if not asset_filepath.exists() or not asset_filepath.is_file():
return {"error": "File not found"}, 404
return FileResponse(path=asset_filepath)
# ----------------------
# Run the EOSdash server
# ----------------------
def run_eosdash() -> None:
"""Run the EOSdash server with the specified configurations.
@@ -348,6 +466,14 @@ def run_eosdash() -> None:
Returns:
None
"""
if args:
run_as_user = args.run_as_user
else:
run_as_user = None
# Drop root privileges if running as root
drop_root_privileges(run_as_user=run_as_user)
# Wait for EOSdash port to be free - e.g. in case of restart
wait_for_port_free(config_eosdash["eosdash_port"], timeout=120, waiting_app_name="EOSdash")
@@ -359,6 +485,8 @@ def run_eosdash() -> None:
log_level=config_eosdash["log_level"].lower(),
access_log=config_eosdash["access_log"],
reload=config_eosdash["reload"],
proxy_headers=True,
forwarded_allow_ips="*",
)
except Exception as e:
logger.error(