mirror of
https://github.com/PiBrewing/craftbeerpi4.git
synced 2024-11-25 00:18:17 +01:00
Merge pull request #8 from madhatguy/master
Changed paths to absolute paths
This commit is contained in:
commit
5f846ee2ad
4 changed files with 127 additions and 114 deletions
129
cbpi/cli.py
129
cbpi/cli.py
|
@ -17,61 +17,66 @@ import click
|
|||
|
||||
from jinja2 import Template
|
||||
|
||||
MAIN_DIR = os.sep.join(os.path.abspath(__file__).split(os.sep)[:-1])
|
||||
|
||||
|
||||
def create_config_file():
|
||||
import os.path
|
||||
if os.path.exists(os.path.join(".", 'config', "config.yaml")) is False:
|
||||
srcfile = os.path.join(os.path.dirname(__file__), "config", "config.yaml")
|
||||
destfile = os.path.join(".", 'config')
|
||||
if os.path.exists(os.path.join(MAIN_DIR, 'config', "config.yaml")) is False:
|
||||
srcfile = os.path.join(MAIN_DIR, "config", "config.yaml")
|
||||
destfile = os.path.join(MAIN_DIR, 'config')
|
||||
shutil.copy(srcfile, destfile)
|
||||
print("Config Folder created")
|
||||
|
||||
if os.path.exists(os.path.join(".", 'config', "actor.json")) is False:
|
||||
srcfile = os.path.join(os.path.dirname(__file__), "config", "actor.json")
|
||||
destfile = os.path.join(".", 'config')
|
||||
if os.path.exists(os.path.join(MAIN_DIR, 'config', "actor.json")) is False:
|
||||
srcfile = os.path.join(MAIN_DIR, "config", "actor.json")
|
||||
destfile = os.path.join(MAIN_DIR, 'config')
|
||||
shutil.copy(srcfile, destfile)
|
||||
|
||||
if os.path.exists(os.path.join(".", 'config', "sensor.json")) is False:
|
||||
srcfile = os.path.join(os.path.dirname(__file__), "config", "sensor.json")
|
||||
destfile = os.path.join(".", 'config')
|
||||
if os.path.exists(os.path.join(MAIN_DIR, 'config', "sensor.json")) is False:
|
||||
srcfile = os.path.join(MAIN_DIR, "config", "sensor.json")
|
||||
destfile = os.path.join(MAIN_DIR, 'config')
|
||||
shutil.copy(srcfile, destfile)
|
||||
|
||||
if os.path.exists(os.path.join(".", 'config', "kettle.json")) is False:
|
||||
srcfile = os.path.join(os.path.dirname(__file__), "config", "kettle.json")
|
||||
destfile = os.path.join(".", 'config')
|
||||
if os.path.exists(os.path.join(MAIN_DIR, 'config', "kettle.json")) is False:
|
||||
srcfile = os.path.join(MAIN_DIR, "config", "kettle.json")
|
||||
destfile = os.path.join(MAIN_DIR, 'config')
|
||||
shutil.copy(srcfile, destfile)
|
||||
|
||||
if os.path.exists(os.path.join(".", 'config', "step_data.json")) is False:
|
||||
srcfile = os.path.join(os.path.dirname(__file__), "config", "step_data.json")
|
||||
destfile = os.path.join(".", 'config')
|
||||
if os.path.exists(os.path.join(MAIN_DIR, 'config', "step_data.json")) is False:
|
||||
srcfile = os.path.join(MAIN_DIR, "config", "step_data.json")
|
||||
destfile = os.path.join(MAIN_DIR, 'config')
|
||||
shutil.copy(srcfile, destfile)
|
||||
|
||||
if os.path.exists(os.path.join(".", 'config', "dashboard", "cbpi_dashboard_1.json")) is False:
|
||||
srcfile = os.path.join(os.path.dirname(__file__), "config", "dashboard", "cbpi_dashboard_1.json")
|
||||
destfile = os.path.join(".", "config", "dashboard")
|
||||
if os.path.exists(os.path.join(MAIN_DIR, 'config', "dashboard", "cbpi_dashboard_1.json")) is False:
|
||||
srcfile = os.path.join(MAIN_DIR, "config", "dashboard", "cbpi_dashboard_1.json")
|
||||
destfile = os.path.join(MAIN_DIR, "config", "dashboard")
|
||||
shutil.copy(srcfile, destfile)
|
||||
|
||||
|
||||
def create_home_folder_structure():
|
||||
pathlib.Path(os.path.join(".", 'logs/sensors')).mkdir(parents=True, exist_ok=True)
|
||||
pathlib.Path(os.path.join(".", 'config')).mkdir(parents=True, exist_ok=True)
|
||||
pathlib.Path(os.path.join(".", 'config/dashboard')).mkdir(parents=True, exist_ok=True)
|
||||
pathlib.Path(os.path.join(".", 'config/dashboard/widgets')).mkdir(parents=True, exist_ok=True)
|
||||
pathlib.Path(os.path.join(MAIN_DIR, 'logs/sensors')).mkdir(parents=True, exist_ok=True)
|
||||
pathlib.Path(os.path.join(MAIN_DIR, 'config')).mkdir(parents=True, exist_ok=True)
|
||||
pathlib.Path(os.path.join(MAIN_DIR, 'config/dashboard')).mkdir(parents=True, exist_ok=True)
|
||||
pathlib.Path(os.path.join(MAIN_DIR, 'config/dashboard/widgets')).mkdir(parents=True, exist_ok=True)
|
||||
print("Folder created")
|
||||
|
||||
|
||||
def copy_splash():
|
||||
srcfile = os.path.join(os.path.dirname(__file__), "config", "splash.png")
|
||||
destfile = os.path.join(".", 'config')
|
||||
srcfile = os.path.join(MAIN_DIR, "config", "splash.png")
|
||||
destfile = os.path.join(MAIN_DIR, 'config')
|
||||
shutil.copy(srcfile, destfile)
|
||||
print("Splash Srceen created")
|
||||
|
||||
|
||||
def clear_db():
|
||||
import os.path
|
||||
if os.path.exists(os.path.join(".", "craftbeerpi.db")) is True:
|
||||
os.remove(os.path.join(".", "craftbeerpi.db"))
|
||||
if os.path.exists(os.path.join(MAIN_DIR, "craftbeerpi.db")) is True:
|
||||
os.remove(os.path.join(MAIN_DIR, "craftbeerpi.db"))
|
||||
print("database Cleared")
|
||||
|
||||
|
||||
def check_for_setup():
|
||||
if os.path.exists(os.path.join(".", "config", "config.yaml")) is False:
|
||||
if os.path.exists(os.path.join(MAIN_DIR, "config", "config.yaml")) is False:
|
||||
print("***************************************************")
|
||||
print("CraftBeerPi Config File not found: %s" % os.path.join(".", "config", "config.yaml"))
|
||||
print("Please run 'cbpi setup' before starting the server ")
|
||||
|
@ -86,7 +91,7 @@ def plugins_add(package_name):
|
|||
print("Pleaes provide a plugin Name")
|
||||
return
|
||||
try:
|
||||
with open(os.path.join(".", 'config', "config.yaml"), 'rt') as f:
|
||||
with open(os.path.join(MAIN_DIR, 'config', "config.yaml"), 'rt') as f:
|
||||
data = yaml.load(f, Loader=yaml.FullLoader)
|
||||
if package_name in data["plugins"]:
|
||||
print("")
|
||||
|
@ -94,7 +99,7 @@ def plugins_add(package_name):
|
|||
print("")
|
||||
return
|
||||
data["plugins"].append(package_name)
|
||||
with open(os.path.join(".", 'config', "config.yaml"), 'w') as outfile:
|
||||
with open(os.path.join(MAIN_DIR, 'config', "config.yaml"), 'w') as outfile:
|
||||
yaml.dump(data, outfile, default_flow_style=False)
|
||||
print("")
|
||||
print("Plugin {} activated".format(package_name))
|
||||
|
@ -104,33 +109,32 @@ def plugins_add(package_name):
|
|||
pass
|
||||
|
||||
|
||||
|
||||
def plugin_remove(package_name):
|
||||
if package_name is None:
|
||||
print("Pleaes provide a plugin Name")
|
||||
return
|
||||
try:
|
||||
with open(os.path.join(".", 'config', "config.yaml"), 'rt') as f:
|
||||
with open(os.path.join(MAIN_DIR, 'config', "config.yaml"), 'rt') as f:
|
||||
data = yaml.load(f, Loader=yaml.FullLoader)
|
||||
|
||||
|
||||
data["plugins"] = list(filter(lambda k: package_name not in k, data["plugins"]))
|
||||
with open(os.path.join(".", 'config', "config.yaml"), 'w') as outfile:
|
||||
with open(os.path.join(MAIN_DIR, 'config', "config.yaml"), 'w') as outfile:
|
||||
yaml.dump(data, outfile, default_flow_style=False)
|
||||
print("")
|
||||
print("")
|
||||
print("Plugin {} deactivated".format(package_name))
|
||||
print("")
|
||||
except Exception as e:
|
||||
print(e)
|
||||
pass
|
||||
|
||||
def plugins_list():
|
||||
|
||||
def plugins_list():
|
||||
print("--------------------------------------")
|
||||
print("List of active pluigins")
|
||||
try:
|
||||
with open(os.path.join(".", 'config', "config.yaml"), 'rt') as f:
|
||||
with open(os.path.join(MAIN_DIR, 'config', "config.yaml"), 'rt') as f:
|
||||
data = yaml.load(f, Loader=yaml.FullLoader)
|
||||
|
||||
|
||||
for p in data["plugins"]:
|
||||
print("- {}".format(p))
|
||||
except Exception as e:
|
||||
|
@ -138,9 +142,9 @@ def plugins_list():
|
|||
pass
|
||||
print("--------------------------------------")
|
||||
|
||||
def plugin_create(name):
|
||||
|
||||
if os.path.exists(os.path.join(".", name)) is True:
|
||||
def plugin_create(name):
|
||||
if os.path.exists(os.path.join(MAIN_DIR, name)) is True:
|
||||
print("Cant create Plugin. Folder {} already exists ".format(name))
|
||||
return
|
||||
|
||||
|
@ -152,47 +156,47 @@ def plugin_create(name):
|
|||
with ZipFile('temp.zip', 'r') as repo_zip:
|
||||
repo_zip.extractall()
|
||||
|
||||
|
||||
os.rename("./craftbeerpi4-plugin-template-main", os.path.join(".", name))
|
||||
os.rename(os.path.join(".", name, "src"), os.path.join(".", name, name))
|
||||
os.rename(MAIN_DIR + "/craftbeerpi4-plugin-template-main", os.path.join(MAIN_DIR, name))
|
||||
os.rename(os.path.join(MAIN_DIR, name, "src"), os.path.join(MAIN_DIR, name, name))
|
||||
|
||||
import jinja2
|
||||
|
||||
templateLoader = jinja2.FileSystemLoader(searchpath=os.path.join(".", name))
|
||||
templateLoader = jinja2.FileSystemLoader(searchpath=os.path.join(MAIN_DIR, name))
|
||||
templateEnv = jinja2.Environment(loader=templateLoader)
|
||||
TEMPLATE_FILE = "setup.py"
|
||||
template = templateEnv.get_template(TEMPLATE_FILE)
|
||||
outputText = template.render(name=name)
|
||||
|
||||
with open(os.path.join(".", name, "setup.py"), "w") as fh:
|
||||
outputText = template.render(name=name)
|
||||
|
||||
with open(os.path.join(MAIN_DIR, name, "setup.py"), "w") as fh:
|
||||
fh.write(outputText)
|
||||
|
||||
TEMPLATE_FILE = "MANIFEST.in"
|
||||
template = templateEnv.get_template(TEMPLATE_FILE)
|
||||
outputText = template.render(name=name)
|
||||
with open(os.path.join(".", name, "MANIFEST.in"), "w") as fh:
|
||||
outputText = template.render(name=name)
|
||||
with open(os.path.join(MAIN_DIR, name, "MANIFEST.in"), "w") as fh:
|
||||
fh.write(outputText)
|
||||
|
||||
TEMPLATE_FILE = os.path.join("/", name , "config.yaml")
|
||||
|
||||
TEMPLATE_FILE = os.path.join("/", name, "config.yaml")
|
||||
template = templateEnv.get_template(TEMPLATE_FILE)
|
||||
outputText = template.render(name=name)
|
||||
|
||||
with open(os.path.join(".", name, name, "config.yaml"), "w") as fh:
|
||||
outputText = template.render(name=name)
|
||||
|
||||
with open(os.path.join(MAIN_DIR, name, name, "config.yaml"), "w") as fh:
|
||||
fh.write(outputText)
|
||||
print("")
|
||||
print("")
|
||||
print("Plugin {} created! See https://craftbeerpi.gitbook.io/craftbeerpi4/development how to run your plugin ".format(name))
|
||||
print(
|
||||
"Plugin {} created! See https://craftbeerpi.gitbook.io/craftbeerpi4/development how to run your plugin ".format(
|
||||
name))
|
||||
print("")
|
||||
print("Happy Development! Cheers")
|
||||
print("")
|
||||
print("")
|
||||
|
||||
|
||||
|
||||
@click.group()
|
||||
def main():
|
||||
level =logging.INFO
|
||||
logging.basicConfig(level=level, format='%(asctime)s - %(levelname)s - %(name)s - %(message)s')
|
||||
def main():
|
||||
level = logging.INFO
|
||||
logging.basicConfig(level=level, format='%(asctime)s - %(levelname)s - %(name)s - %(message)s')
|
||||
pass
|
||||
|
||||
|
||||
|
@ -203,6 +207,7 @@ def setup():
|
|||
create_home_folder_structure()
|
||||
create_config_file()
|
||||
|
||||
|
||||
@click.command()
|
||||
def start():
|
||||
if check_for_setup() is False:
|
||||
|
@ -211,24 +216,27 @@ def start():
|
|||
cbpi = CraftBeerPi()
|
||||
cbpi.start()
|
||||
|
||||
|
||||
@click.command()
|
||||
def plugins():
|
||||
'''List active plugins'''
|
||||
plugins_list()
|
||||
return
|
||||
|
||||
|
||||
@click.command()
|
||||
@click.argument('name')
|
||||
def add(name):
|
||||
'''Activate Plugin'''
|
||||
plugins_add(name)
|
||||
|
||||
|
||||
@click.command()
|
||||
@click.argument('name')
|
||||
def remove(name):
|
||||
'''Deactivate Plugin'''
|
||||
plugin_remove(name)
|
||||
|
||||
|
||||
|
||||
@click.command()
|
||||
@click.argument('name')
|
||||
|
@ -236,6 +244,7 @@ def create(name):
|
|||
'''Deactivate Plugin'''
|
||||
plugin_create(name)
|
||||
|
||||
|
||||
main.add_command(setup)
|
||||
main.add_command(start)
|
||||
main.add_command(plugins)
|
||||
|
|
|
@ -23,8 +23,8 @@ class ConfigController:
|
|||
return self.cache
|
||||
|
||||
async def init(self):
|
||||
this_directory = os.path.dirname(__file__)
|
||||
self.static = load_config("./config/config.yaml")
|
||||
this_directory = os.sep.join(os.path.abspath(__file__).split(os.sep)[:-2])
|
||||
self.static = load_config("{}/config/config.yaml".format(this_directory))
|
||||
items = await self.model.get_all()
|
||||
for key, value in items.items():
|
||||
self.cache[value.name] = value
|
||||
|
|
|
@ -19,12 +19,12 @@ class PluginController():
|
|||
def __init__(self, cbpi):
|
||||
self.cbpi = cbpi
|
||||
|
||||
|
||||
def load_plugins(self):
|
||||
|
||||
this_directory = os.path.dirname(__file__)
|
||||
this_directory = os.sep.join(os.path.abspath(__file__).split(os.sep)[:-1])
|
||||
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__":
|
||||
if os.path.isdir(
|
||||
os.path.join(this_directory, "../extension/") + filename) is False or filename == "__pycache__":
|
||||
continue
|
||||
try:
|
||||
logger.info("Trying to load plugin %s" % filename)
|
||||
|
@ -35,7 +35,7 @@ class PluginController():
|
|||
self.modules[filename] = import_module(
|
||||
"cbpi.extension.%s" % (filename))
|
||||
self.modules[filename].setup(self.cbpi)
|
||||
#logger.info("Plugin %s loaded successful" % filename)
|
||||
# logger.info("Plugin %s loaded successful" % filename)
|
||||
else:
|
||||
logger.warning(
|
||||
"Plugin %s is not supporting version 4" % filename)
|
||||
|
@ -45,10 +45,9 @@ class PluginController():
|
|||
logger.error(e)
|
||||
|
||||
def load_plugins_from_evn(self):
|
||||
|
||||
|
||||
for p in self.cbpi.static_config.get("plugins",[]):
|
||||
|
||||
|
||||
for p in self.cbpi.static_config.get("plugins", []):
|
||||
|
||||
try:
|
||||
logger.info("Try to load plugin: %s " % p)
|
||||
self.modules[p] = import_module(p)
|
||||
|
@ -59,8 +58,6 @@ class PluginController():
|
|||
logger.error("FAILED to load plugin %s " % p)
|
||||
logger.error(e)
|
||||
|
||||
|
||||
|
||||
def register(self, name, clazz) -> None:
|
||||
'''
|
||||
Register a new actor type
|
||||
|
@ -69,30 +66,32 @@ class PluginController():
|
|||
:return: None
|
||||
'''
|
||||
logger.debug("Register %s Class %s" % (name, clazz.__name__))
|
||||
|
||||
|
||||
if issubclass(clazz, CBPiActor):
|
||||
self.cbpi.actor.types[name] = self._parse_step_props(clazz,name)
|
||||
self.cbpi.actor.types[name] = self._parse_step_props(clazz, name)
|
||||
|
||||
if issubclass(clazz, CBPiKettleLogic):
|
||||
self.cbpi.kettle.types[name] = self._parse_step_props(clazz,name)
|
||||
|
||||
self.cbpi.kettle.types[name] = self._parse_step_props(clazz, name)
|
||||
|
||||
if issubclass(clazz, CBPiSensor):
|
||||
self.cbpi.sensor.types[name] = self._parse_step_props(clazz,name)
|
||||
self.cbpi.sensor.types[name] = self._parse_step_props(clazz, name)
|
||||
|
||||
if issubclass(clazz, CBPiStep):
|
||||
self.cbpi.step.types[name] = self._parse_step_props(clazz,name)
|
||||
self.cbpi.step.types[name] = self._parse_step_props(clazz, name)
|
||||
|
||||
if issubclass(clazz, CBPiExtension):
|
||||
self.c = clazz(self.cbpi)
|
||||
|
||||
|
||||
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}
|
||||
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}
|
||||
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}
|
||||
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):
|
||||
|
@ -113,7 +112,7 @@ class PluginController():
|
|||
if hasattr(method, "action"):
|
||||
key = method.__getattribute__("key")
|
||||
parameters = []
|
||||
for p in method.__getattribute__("parameters"):
|
||||
for p in method.__getattribute__("parameters"):
|
||||
parameters.append(self._parse_property_object(p))
|
||||
result["actions"].append({"method": method_name, "label": key, "parameters": parameters})
|
||||
|
||||
|
@ -132,27 +131,33 @@ class PluginController():
|
|||
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})
|
||||
{"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})
|
||||
{"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})
|
||||
{"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)
|
||||
result["properties"].append(
|
||||
{"name": m, "label": t.label, "type": "actor", "configurable": t.configurable, "description": t.description})
|
||||
{"name": m, "label": t.label, "type": "actor", "configurable": t.configurable,
|
||||
"description": t.description})
|
||||
elif isinstance(tmpObj.__getattribute__(m), Property.Sensor):
|
||||
t = tmpObj.__getattribute__(m)
|
||||
result["properties"].append(
|
||||
{"name": m, "label": t.label, "type": "sensor", "configurable": t.configurable, "description": t.description})
|
||||
{"name": m, "label": t.label, "type": "sensor", "configurable": t.configurable,
|
||||
"description": t.description})
|
||||
elif isinstance(tmpObj.__getattribute__(m), Property.Kettle):
|
||||
t = tmpObj.__getattribute__(m)
|
||||
result["properties"].append(
|
||||
{"name": m, "label": t.label, "type": "kettle", "configurable": t.configurable, "description": t.description})
|
||||
{"name": m, "label": t.label, "type": "kettle", "configurable": t.configurable,
|
||||
"description": t.description})
|
||||
|
||||
for method_name, method in cls.__dict__.items():
|
||||
if hasattr(method, "action"):
|
||||
|
|
|
@ -30,7 +30,6 @@ from cbpi.utils import *
|
|||
from cbpi.websocket import CBPiWebSocket
|
||||
from cbpi.http_endpoints.http_actor import ActorHttpEndpoints
|
||||
|
||||
|
||||
from cbpi.http_endpoints.http_config import ConfigHttpEndpoints
|
||||
from cbpi.http_endpoints.http_dashboard import DashBoardHttpEndpoints
|
||||
from cbpi.http_endpoints.http_kettle import KettleHttpEndpoints
|
||||
|
@ -65,18 +64,20 @@ async def error_middleware(request, handler):
|
|||
|
||||
return web.json_response(status=500, data={'error': message})
|
||||
|
||||
class CraftBeerPi():
|
||||
|
||||
class CraftBeerPi:
|
||||
|
||||
def __init__(self):
|
||||
|
||||
self.path = os.sep.join(os.path.abspath(__file__).split(os.sep)[:-1]) # The path to the package dir
|
||||
self.version = __version__
|
||||
|
||||
self.static_config = load_config("./config/config.yaml")
|
||||
self.database_file = "./craftbeerpi.db"
|
||||
self.static_config = load_config("{}/config/config.yaml".format(self.path))
|
||||
self.database_file = "{}/craftbeerpi.db".format(self.path)
|
||||
logger.info("Init CraftBeerPI")
|
||||
|
||||
policy = auth.SessionTktAuthentication(urandom(32), 60, include_ip=True)
|
||||
middlewares = [web.normalize_path_middleware(), session_middleware(EncryptedCookieStorage(urandom(32))), auth.auth_middleware(policy), error_middleware]
|
||||
middlewares = [web.normalize_path_middleware(), session_middleware(EncryptedCookieStorage(urandom(32))),
|
||||
auth.auth_middleware(policy), error_middleware]
|
||||
self.app = web.Application(middlewares=middlewares)
|
||||
self.app["cbpi"] = self
|
||||
|
||||
|
@ -88,7 +89,6 @@ class CraftBeerPi():
|
|||
self.config = ConfigController(self)
|
||||
self.ws = CBPiWebSocket(self)
|
||||
|
||||
|
||||
self.actor = ActorController(self)
|
||||
self.sensor = SensorController(self)
|
||||
self.plugin = PluginController(self)
|
||||
|
@ -96,9 +96,8 @@ class CraftBeerPi():
|
|||
self.system = SystemController(self)
|
||||
self.kettle = KettleController(self)
|
||||
self.step = StepController(self)
|
||||
|
||||
self.dashboard = DashboardController(self)
|
||||
|
||||
self.dashboard = DashboardController(self)
|
||||
|
||||
self.http_step = StepHttpEndpoints(self)
|
||||
self.http_sensor = SensorHttpEndpoints(self)
|
||||
|
@ -120,10 +119,10 @@ class CraftBeerPi():
|
|||
|
||||
self.app.on_cleanup.append(on_cleanup)
|
||||
|
||||
|
||||
def register_on_startup(self, obj):
|
||||
|
||||
for method in [getattr(obj, f) for f in dir(obj) if callable(getattr(obj, f)) and hasattr(getattr(obj, f), "on_startup")]:
|
||||
for method in [getattr(obj, f) for f in dir(obj) if
|
||||
callable(getattr(obj, f)) and hasattr(getattr(obj, f), "on_startup")]:
|
||||
name = method.__getattribute__("name")
|
||||
order = method.__getattribute__("order")
|
||||
self.initializer.append(dict(name=name, method=method, order=order))
|
||||
|
@ -139,23 +138,25 @@ class CraftBeerPi():
|
|||
'''
|
||||
self.register_http_endpoints(obj, url_prefix, static)
|
||||
self.bus.register_object(obj)
|
||||
#self.ws.register_object(obj)
|
||||
# self.ws.register_object(obj)
|
||||
self.job.register_background_task(obj)
|
||||
self.register_on_startup(obj)
|
||||
|
||||
def register_http_endpoints(self, obj, url_prefix=None, static=None):
|
||||
|
||||
|
||||
if url_prefix is None:
|
||||
logger.debug("URL Prefix is None for %s. No endpoints will be registered. Please set / explicit if you want to add it to the root path" % obj)
|
||||
logger.debug(
|
||||
"URL Prefix is None for %s. No endpoints will be registered. Please set / explicit if you want to add it to the root path" % obj)
|
||||
return
|
||||
|
||||
routes = []
|
||||
for method in [getattr(obj, f) for f in dir(obj) if callable(getattr(obj, f)) and hasattr(getattr(obj, f), "route")]:
|
||||
for method in [getattr(obj, f) for f in dir(obj) if
|
||||
callable(getattr(obj, f)) and hasattr(getattr(obj, f), "route")]:
|
||||
http_method = method.__getattribute__("method")
|
||||
path = method.__getattribute__("path")
|
||||
class_name = method.__self__.__class__.__name__
|
||||
logger.debug("Register Endpoint : %s.%s %s %s%s " % (class_name, method.__name__, http_method, url_prefix, path))
|
||||
logger.debug(
|
||||
"Register Endpoint : %s.%s %s %s%s " % (class_name, method.__name__, http_method, url_prefix, path))
|
||||
|
||||
def add_post():
|
||||
routes.append(web.post(method.__getattribute__("path"), method))
|
||||
|
@ -178,19 +179,19 @@ class CraftBeerPi():
|
|||
switcher[http_method]()
|
||||
|
||||
if url_prefix != "/":
|
||||
logger.debug("URL Prefix: %s " % (url_prefix,))
|
||||
logger.debug("URL Prefix: %s " % (url_prefix,))
|
||||
sub = web.Application()
|
||||
sub.add_routes(routes)
|
||||
if static is not None:
|
||||
sub.add_routes([web.static('/static', static, show_index=True)])
|
||||
self.app.add_subapp(url_prefix, sub)
|
||||
else:
|
||||
|
||||
|
||||
self.app.add_routes(routes)
|
||||
|
||||
def _swagger_setup(self):
|
||||
'''
|
||||
Internatl method to expose REST API documentation by swagger
|
||||
Internal method to expose REST API documentation by swagger
|
||||
|
||||
:return:
|
||||
'''
|
||||
|
@ -223,23 +224,22 @@ class CraftBeerPi():
|
|||
def _print_logo(self):
|
||||
from pyfiglet import Figlet
|
||||
f = Figlet(font='big')
|
||||
logger.info("\n%s" % f.renderText("CraftBeerPi %s " % self.version))
|
||||
logger.info("\n%s" % f.renderText("CraftBeerPi %s " % self.version))
|
||||
logger.info("www.CraftBeerPi.com")
|
||||
logger.info("(c) 2021 Manuel Fritsch")
|
||||
|
||||
|
||||
def _setup_http_index(self):
|
||||
async def http_index(request):
|
||||
url = self.config.static.get("index_url")
|
||||
|
||||
|
||||
if url is not None:
|
||||
|
||||
raise web.HTTPFound(url)
|
||||
else:
|
||||
return web.Response(text="Hello from CraftbeerPi!")
|
||||
|
||||
|
||||
self.app.add_routes([web.get('/', http_index), web.static('/static', os.path.join(os.path.dirname(__file__),"static"), show_index=True)])
|
||||
self.app.add_routes([web.get('/', http_index),
|
||||
web.static('/static', os.path.join(os.path.dirname(__file__), "static"), show_index=True)])
|
||||
|
||||
async def init_serivces(self):
|
||||
|
||||
|
@ -261,6 +261,5 @@ class CraftBeerPi():
|
|||
|
||||
return self.app
|
||||
|
||||
|
||||
def start(self):
|
||||
web.run_app(self.init_serivces(), port=self.static_config.get("port", 2202))
|
||||
|
|
Loading…
Reference in a new issue