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
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,17 +109,16 @@ 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("Plugin {} deactivated".format(package_name))
@ -123,12 +127,12 @@ def plugin_remove(package_name):
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"]:
@ -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,46 +156,46 @@ 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:
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:
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:
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
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,18 +216,21 @@ 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):
@ -236,6 +244,7 @@ def create(name):
'''Deactivate Plugin'''
plugin_create(name)
main.add_command(setup)
main.add_command(start)
main.add_command(plugins)

View file

@ -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

View file

@ -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)
@ -46,8 +46,7 @@ class PluginController():
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)
@ -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
@ -71,28 +68,30 @@ class PluginController():
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):
@ -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"):

View file

@ -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)
@ -99,7 +99,6 @@ class CraftBeerPi():
self.dashboard = DashboardController(self)
self.http_step = StepHttpEndpoints(self)
self.http_sensor = SensorHttpEndpoints(self)
self.http_config = ConfigHttpEndpoints(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))
@ -190,7 +191,7 @@ class CraftBeerPi():
def _swagger_setup(self):
'''
Internatl method to expose REST API documentation by swagger
Internal method to expose REST API documentation by swagger
:return:
'''
@ -227,7 +228,6 @@ class CraftBeerPi():
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")
@ -238,8 +238,8 @@ class CraftBeerPi():
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))