craftbeerpi4-pione/cbpi/controller/plugin_controller.py

228 lines
10 KiB
Python
Raw Normal View History

2018-11-04 00:47:26 +01:00
import logging
import os
from importlib import import_module
2019-07-31 07:58:54 +02:00
import datetime
2018-11-04 00:47:26 +01:00
import aiohttp
import yaml
2019-07-27 21:08:19 +02:00
import subprocess
import sys
2019-07-31 07:58:54 +02:00
from cbpi.api import *
from cbpi.utils.utils import load_config
2018-12-29 00:27:19 +01:00
2019-07-31 07:58:54 +02:00
logger = logging.getLogger(__name__)
2018-11-04 00:47:26 +01:00
2021-01-17 22:49:18 +01:00
2018-11-04 00:47:26 +01:00
class PluginController():
modules = {}
2018-11-16 20:35:59 +01:00
types = {}
2018-11-04 00:47:26 +01:00
def __init__(self, cbpi):
self.cbpi = cbpi
2019-07-31 07:58:54 +02:00
self.plugins = load_config("./config/plugin_list.txt")
2021-01-22 23:25:20 +01:00
if self.plugins is None:
self.plugins = {}
2019-07-31 07:58:54 +02:00
2018-11-04 00:47:26 +01:00
async def load_plugin_list(self):
async with aiohttp.ClientSession() as session:
2019-07-31 07:58:54 +02:00
async with session.get('http://localhost:2202/list') as resp:
2019-07-27 21:08:19 +02:00
if (resp.status == 200):
2018-11-04 00:47:26 +01:00
data = yaml.load(await resp.text())
2019-07-31 07:58:54 +02:00
self.plugins = data
2018-11-04 00:47:26 +01:00
return data
2019-07-31 07:58:54 +02:00
def installed_plugins(self):
return self.plugins
async def install(self, package_name):
async def install(cbpi, plugins, package_name):
2021-01-17 22:49:18 +01:00
data = subprocess.check_output(
[sys.executable, "-m", "pip", "install", package_name])
2019-07-31 07:58:54 +02:00
data = data.decode('UTF-8')
if package_name not in self.plugins:
now = datetime.datetime.now()
2021-01-17 22:49:18 +01:00
self.plugins[package_name] = dict(
version="1.0", installation_date=now.strftime("%Y-%m-%d %H:%M:%S"))
2019-07-31 07:58:54 +02:00
with open('./config/plugin_list.txt', 'w') as outfile:
yaml.dump(self.plugins, outfile, default_flow_style=False)
if data.startswith('Requirement already satisfied'):
2021-01-17 22:49:18 +01:00
self.cbpi.notify(
key="p", message="Plugin already installed ", type="warning")
2019-07-31 07:58:54 +02:00
else:
2021-01-17 22:49:18 +01:00
self.cbpi.notify(
key="p", message="Plugin installed ", type="success")
2019-07-31 07:58:54 +02:00
async with aiohttp.ClientSession() as session:
async with session.get('http://localhost:2202/get/%s' % package_name) as resp:
if (resp.status == 200):
data = await resp.json()
await self.cbpi.job.start_job(install(self.cbpi, self.plugins, data["package_name"]), data["package_name"], "plugins_install")
return True
else:
2021-01-17 22:49:18 +01:00
self.cbpi.notify(
key="p", message="Failed to install Plugin %s " % package_name, type="danger")
2019-07-31 07:58:54 +02:00
return False
async def uninstall(self, package_name):
async def uninstall(cbpi, plugins, package_name):
print("try to uninstall", package_name)
try:
2021-01-17 22:49:18 +01:00
data = subprocess.check_output(
[sys.executable, "-m", "pip", "uninstall", "-y", package_name])
2019-07-31 07:58:54 +02:00
data = data.decode('UTF-8')
if data.startswith("Successfully uninstalled"):
2021-01-17 22:49:18 +01:00
cbpi.notify(key="p", message="Plugin %s Uninstalled" %
package_name, type="success")
2019-07-31 07:58:54 +02:00
else:
cbpi.notify(key="p", message=data, type="success")
except Exception as e:
print(e)
if package_name in self.plugins:
print("Uninstall", self.plugins[package_name])
await self.cbpi.job.start_job(uninstall(self.cbpi, self.plugins, package_name), package_name, "plugins_uninstall")
2018-12-07 00:18:35 +01:00
def load_plugins(self):
2018-11-04 00:47:26 +01:00
2019-01-05 20:43:48 +01:00
this_directory = os.path.dirname(__file__)
for filename in os.listdir(os.path.join(this_directory, "../extension")):
if os.path.isdir(os.path.join(this_directory, "../extension/") + filename) is False or filename == "__pycache__":
2018-11-04 00:47:26 +01:00
continue
try:
logger.info("Trying to load plugin %s" % filename)
2021-01-17 22:49:18 +01:00
data = load_config(os.path.join(
this_directory, "../extension/%s/config.yaml" % filename))
2019-08-05 20:51:20 +02:00
if (data.get("active") is True and data.get("version") == 4):
2021-01-17 22:49:18 +01:00
self.modules[filename] = import_module(
"cbpi.extension.%s" % (filename))
2018-11-16 20:35:59 +01:00
self.modules[filename].setup(self.cbpi)
2021-01-22 23:25:20 +01:00
#logger.info("Plugin %s loaded successful" % filename)
2018-11-04 00:47:26 +01:00
else:
2021-01-17 22:49:18 +01:00
logger.warning(
"Plugin %s is not supporting version 4" % filename)
2018-11-04 00:47:26 +01:00
except Exception as e:
2019-07-27 21:08:19 +02:00
print(e)
2018-11-04 00:47:26 +01:00
logger.error(e)
2018-12-29 00:27:19 +01:00
def load_plugins_from_evn(self):
2019-07-31 07:58:54 +02:00
for p in self.plugins:
logger.debug("Load Plugin %s" % p)
try:
logger.info("Try to load plugin: %s " % p)
self.modules[p] = import_module(p)
self.modules[p].setup(self.cbpi)
2021-01-22 23:25:20 +01:00
#logger.info("Plugin %s loaded successfully" % p)
except Exception as e:
logger.error("FAILED to load plugin %s " % p)
logger.error(e)
2018-12-29 00:27:19 +01:00
2018-11-01 21:25:42 +01:00
def register(self, name, clazz) -> None:
'''
Register a new actor type
:param name: actor name
:param clazz: actor class
:return: None
'''
2021-01-22 23:25:20 +01:00
logger.debug("Register %s Class %s" % (name, clazz.__name__))
2021-01-23 14:41:26 +01:00
if issubclass(clazz, CBPiActor):
2021-01-22 23:25:20 +01:00
self.cbpi.actor.types[name] = self._parse_step_props(clazz,name)
2018-11-18 15:40:10 +01:00
2021-01-23 14:41:26 +01:00
if issubclass(clazz, CBPiKettleLogic):
2021-01-22 23:25:20 +01:00
self.cbpi.kettle.types[name] = self._parse_step_props(clazz,name)
2021-01-23 14:41:26 +01:00
if issubclass(clazz, CBPiSensor):
2021-01-22 23:25:20 +01:00
self.cbpi.sensor.types[name] = self._parse_step_props(clazz,name)
2018-12-29 00:27:19 +01:00
2021-01-17 22:49:18 +01:00
if issubclass(clazz, CBPiStep):
2021-01-22 23:25:20 +01:00
self.cbpi.step.types[name] = self._parse_step_props(clazz,name)
2021-01-17 22:49:18 +01:00
if issubclass(clazz, CBPiExtension):
2019-07-27 21:08:19 +02:00
self.c = clazz(self.cbpi)
2018-11-01 19:50:04 +01:00
2021-01-17 22:49:18 +01:00
def _parse_property_object(self, p):
if isinstance(p, Property.Number):
return {"label": p.label, "type": "number", "configurable": p.configurable, "description": p.description, "default_value": p.default_value}
elif isinstance(p, Property.Text):
return {"label": p.label, "type": "text", "configurable": p.configurable, "default_value": p.default_value, "description": p.description}
elif isinstance(p, Property.Select):
return {"label": p.label, "type": "select", "configurable": True, "options": p.options, "description": p.description}
elif isinstance(p, Property.Actor):
return {"label": p.label, "type": "actor", "configurable": p.configurable, "description": p.description}
elif isinstance(p, Property.Sensor):
return {"label": p.label, "type": "sensor", "configurable": p.configurable, "description": p.description}
elif isinstance(p, Property.Kettle):
return {"label": p.label, "type": "kettle", "configurable": p.configurable, "description": p.description}
def _parse_step_props(self, cls, name):
2021-01-22 23:25:20 +01:00
result = {"name": name, "class": cls, "properties": [], "actions": []}
2021-01-17 22:49:18 +01:00
if hasattr(cls, "cbpi_parameters"):
parameters = []
for p in cls.cbpi_parameters:
parameters.append(self._parse_property_object(p))
result["properties"] = parameters
for method_name, method in cls.__dict__.items():
2021-01-22 23:25:20 +01:00
2021-01-17 22:49:18 +01:00
if hasattr(method, "action"):
2021-01-22 23:25:20 +01:00
print(method_name)
2021-01-17 22:49:18 +01:00
key = method.__getattribute__("key")
parameters = []
for p in method.__getattribute__("parameters"):
parameters.append(self._parse_property_object(p))
result["actions"].append({"method": method_name, "label": key, "parameters": parameters})
return result
2018-11-01 19:50:04 +01:00
def _parse_props(self, cls):
2018-12-29 00:27:19 +01:00
2018-11-01 19:50:04 +01:00
name = cls.__name__
result = {"name": name, "class": cls, "properties": [], "actions": []}
2019-07-27 21:08:19 +02:00
tmpObj = cls(cbpi=None, managed_fields=None)
2021-01-17 22:49:18 +01:00
members = [attr for attr in dir(tmpObj) if not callable(
getattr(tmpObj, attr)) and not attr.startswith("__")]
2018-11-01 19:50:04 +01:00
for m in members:
if isinstance(tmpObj.__getattribute__(m), Property.Number):
t = tmpObj.__getattribute__(m)
result["properties"].append(
{"name": m, "label": t.label, "type": "number", "configurable": t.configurable, "description": t.description, "default_value": t.default_value})
elif isinstance(tmpObj.__getattribute__(m), Property.Text):
t = tmpObj.__getattribute__(m)
result["properties"].append(
{"name": m, "label": t.label, "type": "text", "configurable": t.configurable, "default_value": t.default_value, "description": t.description})
elif isinstance(tmpObj.__getattribute__(m), Property.Select):
t = tmpObj.__getattribute__(m)
result["properties"].append(
{"name": m, "label": t.label, "type": "select", "configurable": True, "options": t.options, "description": t.description})
elif isinstance(tmpObj.__getattribute__(m), Property.Actor):
t = tmpObj.__getattribute__(m)
2021-01-17 22:49:18 +01:00
result["properties"].append(
{"name": m, "label": t.label, "type": "actor", "configurable": t.configurable, "description": t.description})
2018-11-01 19:50:04 +01:00
elif isinstance(tmpObj.__getattribute__(m), Property.Sensor):
t = tmpObj.__getattribute__(m)
2021-01-17 22:49:18 +01:00
result["properties"].append(
{"name": m, "label": t.label, "type": "sensor", "configurable": t.configurable, "description": t.description})
2018-11-01 19:50:04 +01:00
elif isinstance(tmpObj.__getattribute__(m), Property.Kettle):
t = tmpObj.__getattribute__(m)
2021-01-17 22:49:18 +01:00
result["properties"].append(
{"name": m, "label": t.label, "type": "kettle", "configurable": t.configurable, "description": t.description})
2018-11-01 19:50:04 +01:00
for method_name, method in cls.__dict__.items():
2018-11-01 21:25:42 +01:00
if hasattr(method, "action"):
key = method.__getattribute__("key")
parameters = method.__getattribute__("parameters")
2021-01-17 22:49:18 +01:00
result["actions"].append(
{"method": method_name, "label": key, "parameters": parameters})
2018-12-29 00:27:19 +01:00
2019-07-27 21:08:19 +02:00
return result