Skip to content

Commit

Permalink
Fixed get_plugin_api
Browse files Browse the repository at this point in the history
  • Loading branch information
jsl12 committed Jan 26, 2025
1 parent b458b5b commit 22718e5
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 56 deletions.
9 changes: 7 additions & 2 deletions appdaemon/adapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def __init__(self, ad: AppDaemon, config_model: "AppConfig"):
self.config_model = config_model

self.config = self.AD.config.model_dump(by_alias=True, exclude_unset=True)
self.args = self.config_model.model_dump(by_alias=True, exclude_unset=True)
self.args = config_model.model_dump(by_alias=True, exclude_unset=True)

self.dashboard_dir = None

Expand Down Expand Up @@ -118,6 +118,11 @@ def _get_namespace(self, **kwargs):
#
# Properties
#
@property
def app_config(self) -> dict:
"""Full set of loaded app configurations."""
return self.AD.app_management.app_config.model_dump(by_alias=True, exclude_unset=True)

@property
def app_dir(self) -> Path:
return self.AD.app_dir
Expand All @@ -127,7 +132,7 @@ def config_dir(self) -> Path:
return self.AD.config_dir

@property
def global_vars(self):
def global_vars(self) -> dict:
return self.AD.global_vars

@property
Expand Down
15 changes: 4 additions & 11 deletions appdaemon/adbase.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,17 +145,10 @@ def name(self) -> str:
def get_ad_api(self) -> adapi.ADAPI:
return adapi.ADAPI(self.AD, self.config_model)

@utils.sync_decorator
async def get_plugin_api(self, plugin_name: str) -> Callable:
return await self.AD.plugins.get_plugin_api(
plugin_name,
self.name,
self._logging,
self.args,
self.config_model,
self.app_config,
self.global_vars,
)
def get_plugin_api(self, plugin_name: str):
app_cfg = self.app_config.root[self.name]
plugin_api = self.AD.plugins.get_plugin_api(plugin_name, app_cfg)
return plugin_api

#
# Constraints
Expand Down
22 changes: 16 additions & 6 deletions appdaemon/models/config/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,12 @@ class PluginConfig(BaseModel, extra="allow"):
"""Delay between refreshes of the complete plugin state in the utility loop"""
refresh_timeout: int = 30
use_dictionary_unpacking: bool = True
module_name: str = None
class_name: str = None

# Used by the AppDaemon internals to import the plugins.
plugin_module: str = None
plugin_class: str = None
api_module: str = None
api_class: str = None

connect_timeout: int | float = 1.0
reconnect_delay: int | float = 5.0
Expand All @@ -36,11 +40,17 @@ def lower(cls, v: str, info: ValidationInfo):

@model_validator(mode="after")
def custom_validator(self):
if "module_name" not in self.model_fields_set:
self.module_name = f"appdaemon.plugins.{self.type}.{self.type}plugin"
if "plugin_module" not in self.model_fields_set:
self.plugin_module = f"appdaemon.plugins.{self.type}.{self.type}plugin"

if "plugin_class" not in self.model_fields_set:
self.plugin_class = f"{self.type.capitalize()}Plugin"

if "api_module" not in self.model_fields_set:
self.api_module = f"appdaemon.plugins.{self.type}.{self.type}api"

if "class_name" not in self.model_fields_set:
self.class_name = f"{self.type.capitalize()}Plugin"
if "api_classname" not in self.model_fields_set:
self.api_class = f"{self.type.capitalize()}"

return self

Expand Down
31 changes: 13 additions & 18 deletions appdaemon/plugin_management.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,11 @@
from . import utils
from .app_management import UpdateMode
from .models.config.plugin import PluginConfig
from .models.config import AppConfig

if TYPE_CHECKING:
from appdaemon.appdaemon import AppDaemon
from .adapi import ADAPI
from .appdaemon import AppDaemon


class PluginBase(abc.ABC):
Expand Down Expand Up @@ -282,13 +284,13 @@ def __init__(self, ad: "AppDaemon", config: dict[str, PluginConfig]):
self.logger.info(
msg,
name,
cfg.class_name,
cfg.module_name,
cfg.plugin_class,
cfg.plugin_module,
)

try:
module = importlib.import_module(cfg.module_name)
plugin_class: Type[PluginBase] = getattr(module, cfg.class_name)
module = importlib.import_module(cfg.plugin_module)
plugin_class: Type[PluginBase] = getattr(module, cfg.plugin_class)
plugin: PluginBase = plugin_class(self.AD, name, self.config[name])
namespace = plugin.config.namespace

Expand Down Expand Up @@ -486,19 +488,12 @@ def required_meta_check(self):
OK = False
return OK

async def get_plugin_api(self, plugin_name, name, _logging, args, config, app_config, global_vars):
if plugin_name in self.config:
plugin = self.config[plugin_name]
module_name = "{}api".format(plugin["type"])
mod = __import__(module_name, globals(), locals(), [module_name], 0)
app_class = getattr(mod, plugin["type"].title())
api = app_class(self.AD, name, _logging, args, config, app_config, global_vars)
if "namespace" in plugin:
api.set_namespace(plugin["namespace"])
else:
api.set_namespace("default")
def get_plugin_api(self, plugin_name: str, app_cfg: AppConfig) -> "ADAPI":
if plugin_cfg := self.config.get(plugin_name):
module = importlib.import_module(plugin_cfg.api_module)
api_class: Type["ADAPI"] = getattr(module, plugin_cfg.api_class)
api = api_class(self.AD, app_cfg)
api.set_namespace(plugin_cfg.namespace)
return api

else:
self.logger.warning("Unknown Plugin Configuration in get_plugin_api()")
return None
29 changes: 10 additions & 19 deletions appdaemon/plugins/mqtt/mqttapi.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
from typing import Any, Callable, Optional, Union
from typing import TYPE_CHECKING, Any, Callable, Optional, Union

import appdaemon.adapi as adapi
import appdaemon.adbase as adbase
import appdaemon.utils as utils
from appdaemon.appdaemon import AppDaemon
from appdaemon.models.config.app import AppConfig
from appdaemon.plugins.mqtt.mqttplugin import MqttPlugin

from ...appdaemon import AppDaemon

if TYPE_CHECKING:
from ...models.config import AppConfig
from .mqttplugin import MqttPlugin


class Mqtt(adbase.ADBase, adapi.ADAPI):
Expand Down Expand Up @@ -54,21 +57,9 @@ def initialize(self):
an more readable. These are documented in the following section.
"""

_plugin: MqttPlugin

def __init__(self, ad: AppDaemon, config_model: AppConfig):
"""Constructor for the app.
_plugin: "MqttPlugin"

Args:
ad: AppDaemon object.
name: name of the app.
logging: reference to logging object.
args: app arguments.
config: AppDaemon config.
app_config: config for all apps.
global_vars: reference to global variables dict.
"""
def __init__(self, ad: AppDaemon, config_model: "AppConfig"):
# Call Super Classes
adbase.ADBase.__init__(self, ad, config_model)
adapi.ADAPI.__init__(self, ad, config_model)
Expand Down Expand Up @@ -154,7 +145,7 @@ async def listen_event(self, callback: Callable, event: str = None, **kwargs: Op
"""

namespace = self._get_namespace(**kwargs)
plugin: MqttPlugin = self.AD.plugins.get_plugin_object(namespace)
plugin: "MqttPlugin" = self.AD.plugins.get_plugin_object(namespace)
topic = kwargs.get("topic", kwargs.get("wildcard"))

if plugin is not None:
Expand Down

0 comments on commit 22718e5

Please sign in to comment.