Changed paths to absolute paths

This commit is contained in:
thehatguy 2021-02-01 02:38:04 +02:00
parent bf8bea3027
commit 23eb12ef28
4 changed files with 127 additions and 114 deletions

View file

@ -17,61 +17,66 @@ import click
from jinja2 import Template from jinja2 import Template
MAIN_DIR = os.sep.join(os.path.abspath(__file__).split(os.sep)[:-1])
def create_config_file(): def create_config_file():
import os.path if os.path.exists(os.path.join(MAIN_DIR, 'config', "config.yaml")) is False:
if os.path.exists(os.path.join(".", 'config', "config.yaml")) is False: srcfile = os.path.join(MAIN_DIR, "config", "config.yaml")
srcfile = os.path.join(os.path.dirname(__file__), "config", "config.yaml") destfile = os.path.join(MAIN_DIR, 'config')
destfile = os.path.join(".", 'config')
shutil.copy(srcfile, destfile) shutil.copy(srcfile, destfile)
print("Config Folder created") print("Config Folder created")
if os.path.exists(os.path.join(".", 'config', "actor.json")) is False: if os.path.exists(os.path.join(MAIN_DIR, 'config', "actor.json")) is False:
srcfile = os.path.join(os.path.dirname(__file__), "config", "actor.json") srcfile = os.path.join(MAIN_DIR, "config", "actor.json")
destfile = os.path.join(".", 'config') destfile = os.path.join(MAIN_DIR, 'config')
shutil.copy(srcfile, destfile) shutil.copy(srcfile, destfile)
if os.path.exists(os.path.join(".", 'config', "sensor.json")) is False: if os.path.exists(os.path.join(MAIN_DIR, 'config', "sensor.json")) is False:
srcfile = os.path.join(os.path.dirname(__file__), "config", "sensor.json") srcfile = os.path.join(MAIN_DIR, "config", "sensor.json")
destfile = os.path.join(".", 'config') destfile = os.path.join(MAIN_DIR, 'config')
shutil.copy(srcfile, destfile) shutil.copy(srcfile, destfile)
if os.path.exists(os.path.join(".", 'config', "kettle.json")) is False: if os.path.exists(os.path.join(MAIN_DIR, 'config', "kettle.json")) is False:
srcfile = os.path.join(os.path.dirname(__file__), "config", "kettle.json") srcfile = os.path.join(MAIN_DIR, "config", "kettle.json")
destfile = os.path.join(".", 'config') destfile = os.path.join(MAIN_DIR, 'config')
shutil.copy(srcfile, destfile) shutil.copy(srcfile, destfile)
if os.path.exists(os.path.join(".", 'config', "step_data.json")) is False: if os.path.exists(os.path.join(MAIN_DIR, 'config', "step_data.json")) is False:
srcfile = os.path.join(os.path.dirname(__file__), "config", "step_data.json") srcfile = os.path.join(MAIN_DIR, "config", "step_data.json")
destfile = os.path.join(".", 'config') destfile = os.path.join(MAIN_DIR, 'config')
shutil.copy(srcfile, destfile) shutil.copy(srcfile, destfile)
if os.path.exists(os.path.join(".", 'config', "dashboard", "cbpi_dashboard_1.json")) is False: if os.path.exists(os.path.join(MAIN_DIR, 'config', "dashboard", "cbpi_dashboard_1.json")) is False:
srcfile = os.path.join(os.path.dirname(__file__), "config", "dashboard", "cbpi_dashboard_1.json") srcfile = os.path.join(MAIN_DIR, "config", "dashboard", "cbpi_dashboard_1.json")
destfile = os.path.join(".", "config", "dashboard") destfile = os.path.join(MAIN_DIR, "config", "dashboard")
shutil.copy(srcfile, destfile) shutil.copy(srcfile, destfile)
def create_home_folder_structure(): def create_home_folder_structure():
pathlib.Path(os.path.join(".", 'logs/sensors')).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(".", 'config')).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(".", 'config/dashboard')).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(".", 'config/dashboard/widgets')).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") print("Folder created")
def copy_splash(): def copy_splash():
srcfile = os.path.join(os.path.dirname(__file__), "config", "splash.png") srcfile = os.path.join(MAIN_DIR, "config", "splash.png")
destfile = os.path.join(".", 'config') destfile = os.path.join(MAIN_DIR, 'config')
shutil.copy(srcfile, destfile) shutil.copy(srcfile, destfile)
print("Splash Srceen created") print("Splash Srceen created")
def clear_db(): def clear_db():
import os.path import os.path
if os.path.exists(os.path.join(".", "craftbeerpi.db")) is True: if os.path.exists(os.path.join(MAIN_DIR, "craftbeerpi.db")) is True:
os.remove(os.path.join(".", "craftbeerpi.db")) os.remove(os.path.join(MAIN_DIR, "craftbeerpi.db"))
print("database Cleared") print("database Cleared")
def check_for_setup(): 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("***************************************************")
print("CraftBeerPi Config File not found: %s" % os.path.join(".", "config", "config.yaml")) print("CraftBeerPi Config File not found: %s" % os.path.join(".", "config", "config.yaml"))
print("Please run 'cbpi setup' before starting the server ") print("Please run 'cbpi setup' before starting the server ")
@ -86,7 +91,7 @@ def plugins_add(package_name):
print("Pleaes provide a plugin Name") print("Pleaes provide a plugin Name")
return return
try: 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 = yaml.load(f, Loader=yaml.FullLoader)
if package_name in data["plugins"]: if package_name in data["plugins"]:
print("") print("")
@ -94,7 +99,7 @@ def plugins_add(package_name):
print("") print("")
return return
data["plugins"].append(package_name) 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) yaml.dump(data, outfile, default_flow_style=False)
print("") print("")
print("Plugin {} activated".format(package_name)) print("Plugin {} activated".format(package_name))
@ -104,33 +109,32 @@ def plugins_add(package_name):
pass pass
def plugin_remove(package_name): def plugin_remove(package_name):
if package_name is None: if package_name is None:
print("Pleaes provide a plugin Name") print("Pleaes provide a plugin Name")
return return
try: 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 = yaml.load(f, Loader=yaml.FullLoader)
data["plugins"] = list(filter(lambda k: package_name not in k, data["plugins"])) 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) yaml.dump(data, outfile, default_flow_style=False)
print("") print("")
print("Plugin {} deactivated".format(package_name)) print("Plugin {} deactivated".format(package_name))
print("") print("")
except Exception as e: except Exception as e:
print(e) print(e)
pass pass
def plugins_list():
def plugins_list():
print("--------------------------------------") print("--------------------------------------")
print("List of active pluigins") print("List of active pluigins")
try: 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 = yaml.load(f, Loader=yaml.FullLoader)
for p in data["plugins"]: for p in data["plugins"]:
print("- {}".format(p)) print("- {}".format(p))
except Exception as e: except Exception as e:
@ -138,9 +142,9 @@ def plugins_list():
pass pass
print("--------------------------------------") 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)) print("Cant create Plugin. Folder {} already exists ".format(name))
return return
@ -152,47 +156,47 @@ def plugin_create(name):
with ZipFile('temp.zip', 'r') as repo_zip: with ZipFile('temp.zip', 'r') as repo_zip:
repo_zip.extractall() repo_zip.extractall()
os.rename(MAIN_DIR + "/craftbeerpi4-plugin-template-main", os.path.join(MAIN_DIR, name))
os.rename("./craftbeerpi4-plugin-template-main", os.path.join(".", name)) os.rename(os.path.join(MAIN_DIR, name, "src"), os.path.join(MAIN_DIR, name, name))
os.rename(os.path.join(".", name, "src"), os.path.join(".", name, name))
import jinja2 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) templateEnv = jinja2.Environment(loader=templateLoader)
TEMPLATE_FILE = "setup.py" TEMPLATE_FILE = "setup.py"
template = templateEnv.get_template(TEMPLATE_FILE) template = templateEnv.get_template(TEMPLATE_FILE)
outputText = template.render(name=name) outputText = template.render(name=name)
with open(os.path.join(".", name, "setup.py"), "w") as fh: with open(os.path.join(MAIN_DIR, name, "setup.py"), "w") as fh:
fh.write(outputText) fh.write(outputText)
TEMPLATE_FILE = "MANIFEST.in" TEMPLATE_FILE = "MANIFEST.in"
template = templateEnv.get_template(TEMPLATE_FILE) template = templateEnv.get_template(TEMPLATE_FILE)
outputText = template.render(name=name) outputText = template.render(name=name)
with open(os.path.join(".", name, "MANIFEST.in"), "w") as fh: with open(os.path.join(MAIN_DIR, name, "MANIFEST.in"), "w") as fh:
fh.write(outputText) 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) template = templateEnv.get_template(TEMPLATE_FILE)
outputText = template.render(name=name) outputText = template.render(name=name)
with open(os.path.join(".", name, name, "config.yaml"), "w") as fh: with open(os.path.join(MAIN_DIR, name, name, "config.yaml"), "w") as fh:
fh.write(outputText) fh.write(outputText)
print("") print("")
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("")
print("Happy Development! Cheers") print("Happy Development! Cheers")
print("") print("")
print("") print("")
@click.group() @click.group()
def main(): def main():
level =logging.INFO level = logging.INFO
logging.basicConfig(level=level, format='%(asctime)s - %(levelname)s - %(name)s - %(message)s') logging.basicConfig(level=level, format='%(asctime)s - %(levelname)s - %(name)s - %(message)s')
pass pass
@ -203,6 +207,7 @@ def setup():
create_home_folder_structure() create_home_folder_structure()
create_config_file() create_config_file()
@click.command() @click.command()
def start(): def start():
if check_for_setup() is False: if check_for_setup() is False:
@ -211,24 +216,27 @@ def start():
cbpi = CraftBeerPi() cbpi = CraftBeerPi()
cbpi.start() cbpi.start()
@click.command() @click.command()
def plugins(): def plugins():
'''List active plugins''' '''List active plugins'''
plugins_list() plugins_list()
return return
@click.command() @click.command()
@click.argument('name') @click.argument('name')
def add(name): def add(name):
'''Activate Plugin''' '''Activate Plugin'''
plugins_add(name) plugins_add(name)
@click.command() @click.command()
@click.argument('name') @click.argument('name')
def remove(name): def remove(name):
'''Deactivate Plugin''' '''Deactivate Plugin'''
plugin_remove(name) plugin_remove(name)
@click.command() @click.command()
@click.argument('name') @click.argument('name')
@ -236,6 +244,7 @@ def create(name):
'''Deactivate Plugin''' '''Deactivate Plugin'''
plugin_create(name) plugin_create(name)
main.add_command(setup) main.add_command(setup)
main.add_command(start) main.add_command(start)
main.add_command(plugins) main.add_command(plugins)

View file

@ -23,8 +23,8 @@ class ConfigController:
return self.cache return self.cache
async def init(self): async def init(self):
this_directory = os.path.dirname(__file__) this_directory = os.sep.join(os.path.abspath(__file__).split(os.sep)[:-2])
self.static = load_config("./config/config.yaml") self.static = load_config("{}/config/config.yaml".format(this_directory))
items = await self.model.get_all() items = await self.model.get_all()
for key, value in items.items(): for key, value in items.items():
self.cache[value.name] = value self.cache[value.name] = value

View file

@ -19,12 +19,12 @@ class PluginController():
def __init__(self, cbpi): def __init__(self, cbpi):
self.cbpi = cbpi self.cbpi = cbpi
def load_plugins(self): 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")): 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 continue
try: try:
logger.info("Trying to load plugin %s" % filename) logger.info("Trying to load plugin %s" % filename)
@ -35,7 +35,7 @@ class PluginController():
self.modules[filename] = import_module( self.modules[filename] = import_module(
"cbpi.extension.%s" % (filename)) "cbpi.extension.%s" % (filename))
self.modules[filename].setup(self.cbpi) self.modules[filename].setup(self.cbpi)
#logger.info("Plugin %s loaded successful" % filename) # logger.info("Plugin %s loaded successful" % filename)
else: else:
logger.warning( logger.warning(
"Plugin %s is not supporting version 4" % filename) "Plugin %s is not supporting version 4" % filename)
@ -45,10 +45,9 @@ class PluginController():
logger.error(e) logger.error(e)
def load_plugins_from_evn(self): 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: try:
logger.info("Try to load plugin: %s " % p) logger.info("Try to load plugin: %s " % p)
self.modules[p] = import_module(p) self.modules[p] = import_module(p)
@ -59,8 +58,6 @@ class PluginController():
logger.error("FAILED to load plugin %s " % p) logger.error("FAILED to load plugin %s " % p)
logger.error(e) logger.error(e)
def register(self, name, clazz) -> None: def register(self, name, clazz) -> None:
''' '''
Register a new actor type Register a new actor type
@ -69,30 +66,32 @@ class PluginController():
:return: None :return: None
''' '''
logger.debug("Register %s Class %s" % (name, clazz.__name__)) logger.debug("Register %s Class %s" % (name, clazz.__name__))
if issubclass(clazz, CBPiActor): 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): 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): 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): 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): if issubclass(clazz, CBPiExtension):
self.c = clazz(self.cbpi) self.c = clazz(self.cbpi)
def _parse_property_object(self, p): def _parse_property_object(self, p):
if isinstance(p, Property.Number): 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): 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): 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): elif isinstance(p, Property.Actor):
return {"label": p.label, "type": "actor", "configurable": p.configurable, "description": p.description} return {"label": p.label, "type": "actor", "configurable": p.configurable, "description": p.description}
elif isinstance(p, Property.Sensor): elif isinstance(p, Property.Sensor):
@ -113,7 +112,7 @@ class PluginController():
if hasattr(method, "action"): if hasattr(method, "action"):
key = method.__getattribute__("key") key = method.__getattribute__("key")
parameters = [] parameters = []
for p in method.__getattribute__("parameters"): for p in method.__getattribute__("parameters"):
parameters.append(self._parse_property_object(p)) parameters.append(self._parse_property_object(p))
result["actions"].append({"method": method_name, "label": key, "parameters": parameters}) result["actions"].append({"method": method_name, "label": key, "parameters": parameters})
@ -132,27 +131,33 @@ class PluginController():
if isinstance(tmpObj.__getattribute__(m), Property.Number): if isinstance(tmpObj.__getattribute__(m), Property.Number):
t = tmpObj.__getattribute__(m) t = tmpObj.__getattribute__(m)
result["properties"].append( 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): elif isinstance(tmpObj.__getattribute__(m), Property.Text):
t = tmpObj.__getattribute__(m) t = tmpObj.__getattribute__(m)
result["properties"].append( 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): elif isinstance(tmpObj.__getattribute__(m), Property.Select):
t = tmpObj.__getattribute__(m) t = tmpObj.__getattribute__(m)
result["properties"].append( 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): elif isinstance(tmpObj.__getattribute__(m), Property.Actor):
t = tmpObj.__getattribute__(m) t = tmpObj.__getattribute__(m)
result["properties"].append( 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): elif isinstance(tmpObj.__getattribute__(m), Property.Sensor):
t = tmpObj.__getattribute__(m) t = tmpObj.__getattribute__(m)
result["properties"].append( 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): elif isinstance(tmpObj.__getattribute__(m), Property.Kettle):
t = tmpObj.__getattribute__(m) t = tmpObj.__getattribute__(m)
result["properties"].append( 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(): for method_name, method in cls.__dict__.items():
if hasattr(method, "action"): if hasattr(method, "action"):

View file

@ -30,7 +30,6 @@ from cbpi.utils import *
from cbpi.websocket import CBPiWebSocket from cbpi.websocket import CBPiWebSocket
from cbpi.http_endpoints.http_actor import ActorHttpEndpoints from cbpi.http_endpoints.http_actor import ActorHttpEndpoints
from cbpi.http_endpoints.http_config import ConfigHttpEndpoints from cbpi.http_endpoints.http_config import ConfigHttpEndpoints
from cbpi.http_endpoints.http_dashboard import DashBoardHttpEndpoints from cbpi.http_endpoints.http_dashboard import DashBoardHttpEndpoints
from cbpi.http_endpoints.http_kettle import KettleHttpEndpoints 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}) return web.json_response(status=500, data={'error': message})
class CraftBeerPi():
class CraftBeerPi:
def __init__(self): 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.version = __version__
self.static_config = load_config("./config/config.yaml") self.static_config = load_config("{}/config/config.yaml".format(self.path))
self.database_file = "./craftbeerpi.db" self.database_file = "{}/craftbeerpi.db".format(self.path)
logger.info("Init CraftBeerPI") logger.info("Init CraftBeerPI")
policy = auth.SessionTktAuthentication(urandom(32), 60, include_ip=True) 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 = web.Application(middlewares=middlewares)
self.app["cbpi"] = self self.app["cbpi"] = self
@ -88,7 +89,6 @@ class CraftBeerPi():
self.config = ConfigController(self) self.config = ConfigController(self)
self.ws = CBPiWebSocket(self) self.ws = CBPiWebSocket(self)
self.actor = ActorController(self) self.actor = ActorController(self)
self.sensor = SensorController(self) self.sensor = SensorController(self)
self.plugin = PluginController(self) self.plugin = PluginController(self)
@ -96,9 +96,8 @@ class CraftBeerPi():
self.system = SystemController(self) self.system = SystemController(self)
self.kettle = KettleController(self) self.kettle = KettleController(self)
self.step = StepController(self) self.step = StepController(self)
self.dashboard = DashboardController(self)
self.dashboard = DashboardController(self)
self.http_step = StepHttpEndpoints(self) self.http_step = StepHttpEndpoints(self)
self.http_sensor = SensorHttpEndpoints(self) self.http_sensor = SensorHttpEndpoints(self)
@ -120,10 +119,10 @@ class CraftBeerPi():
self.app.on_cleanup.append(on_cleanup) self.app.on_cleanup.append(on_cleanup)
def register_on_startup(self, obj): 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") name = method.__getattribute__("name")
order = method.__getattribute__("order") order = method.__getattribute__("order")
self.initializer.append(dict(name=name, method=method, order=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.register_http_endpoints(obj, url_prefix, static)
self.bus.register_object(obj) self.bus.register_object(obj)
#self.ws.register_object(obj) # self.ws.register_object(obj)
self.job.register_background_task(obj) self.job.register_background_task(obj)
self.register_on_startup(obj) self.register_on_startup(obj)
def register_http_endpoints(self, obj, url_prefix=None, static=None): def register_http_endpoints(self, obj, url_prefix=None, static=None):
if url_prefix is 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 return
routes = [] 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") http_method = method.__getattribute__("method")
path = method.__getattribute__("path") path = method.__getattribute__("path")
class_name = method.__self__.__class__.__name__ 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(): def add_post():
routes.append(web.post(method.__getattribute__("path"), method)) routes.append(web.post(method.__getattribute__("path"), method))
@ -178,19 +179,19 @@ class CraftBeerPi():
switcher[http_method]() switcher[http_method]()
if url_prefix != "/": if url_prefix != "/":
logger.debug("URL Prefix: %s " % (url_prefix,)) logger.debug("URL Prefix: %s " % (url_prefix,))
sub = web.Application() sub = web.Application()
sub.add_routes(routes) sub.add_routes(routes)
if static is not None: if static is not None:
sub.add_routes([web.static('/static', static, show_index=True)]) sub.add_routes([web.static('/static', static, show_index=True)])
self.app.add_subapp(url_prefix, sub) self.app.add_subapp(url_prefix, sub)
else: else:
self.app.add_routes(routes) self.app.add_routes(routes)
def _swagger_setup(self): def _swagger_setup(self):
''' '''
Internatl method to expose REST API documentation by swagger Internal method to expose REST API documentation by swagger
:return: :return:
''' '''
@ -223,23 +224,22 @@ class CraftBeerPi():
def _print_logo(self): def _print_logo(self):
from pyfiglet import Figlet from pyfiglet import Figlet
f = Figlet(font='big') 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("www.CraftBeerPi.com")
logger.info("(c) 2021 Manuel Fritsch") logger.info("(c) 2021 Manuel Fritsch")
def _setup_http_index(self): def _setup_http_index(self):
async def http_index(request): async def http_index(request):
url = self.config.static.get("index_url") url = self.config.static.get("index_url")
if url is not None: if url is not None:
raise web.HTTPFound(url) raise web.HTTPFound(url)
else: else:
return web.Response(text="Hello from CraftbeerPi!") return web.Response(text="Hello from CraftbeerPi!")
self.app.add_routes([web.get('/', http_index),
self.app.add_routes([web.get('/', http_index), web.static('/static', os.path.join(os.path.dirname(__file__),"static"), show_index=True)]) web.static('/static', os.path.join(os.path.dirname(__file__), "static"), show_index=True)])
async def init_serivces(self): async def init_serivces(self):
@ -261,6 +261,5 @@ class CraftBeerPi():
return self.app return self.app
def start(self): def start(self):
web.run_app(self.init_serivces(), port=self.static_config.get("port", 2202)) web.run_app(self.init_serivces(), port=self.static_config.get("port", 2202))