step change add oder for new

This commit is contained in:
manuel83 2019-01-21 22:33:29 +01:00
parent 017b7373e3
commit 6cc7f5ad77
14 changed files with 353 additions and 564 deletions

File diff suppressed because it is too large Load diff

View file

@ -47,6 +47,7 @@ class CBPiSimpleStep(metaclass=ABCMeta):
''' '''
while self.running(): while self.running():
try: try:
await self.run_cycle() await self.run_cycle()
except Exception as e: except Exception as e:

View file

@ -1,3 +1,4 @@
import argparse
import logging import logging
from cbpi.craftbeerpi import CraftBeerPi from cbpi.craftbeerpi import CraftBeerPi
@ -24,18 +25,33 @@ def create_home_folder_structure():
pathlib.Path(os.path.join(".", 'logs/sensors')).mkdir(parents=True, exist_ok=True) 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')).mkdir(parents=True, exist_ok=True)
def copy_splash():
srcfile = os.path.join(os.path.dirname(__file__), "config", "splash.png")
destfile = os.path.join(".", 'config')
shutil.copy(srcfile, destfile)
def main(): def main():
parser = argparse.ArgumentParser(description='Welcome to CraftBeerPi 4')
parser.add_argument("action", type=str, help="start,stop,restart,setup")
args = parser.parse_args()
logging.basicConfig(level=logging.INFO, filename='./logs/app.log', filemode='a', format='%(asctime)s - %(levelname)s - %(name)s - %(message)s')
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(name)s - %(message)s')
if args.action == "setup":
create_home_folder_structure() create_home_folder_structure()
create_plugin_file() create_plugin_file()
create_config_file() create_config_file()
copy_splash()
#logging.basicConfig(level=logging.INFO, filename='./logs/app.log', filemode='a', format='%(asctime)s - %(levelname)s - %(name)s - %(message)s') if args.action == "start":
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(name)s - %(message)s')
cbpi = CraftBeerPi() cbpi = CraftBeerPi()
cbpi.start() cbpi.start()
parser.print_help()

BIN
cbpi/config/splash.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 MiB

View file

@ -35,7 +35,7 @@ class ActorController(CRUDController):
return dict(items=self.cache,types=self.types) return dict(items=self.cache,types=self.types)
async def _init_actor(self, actor): async def _init_actor(self, actor):
print("INit ACTOR")
try: try:
if actor.type in self.types: if actor.type in self.types:
cfg = actor.config.copy() cfg = actor.config.copy()

View file

@ -204,3 +204,16 @@ class StepController(CRUDController):
await self.model.reset_all_steps() await self.model.reset_all_steps()
async def sort(self, data):
await self.model.sort(data)
async def _pre_add_callback(self, data):
order = await self.model.get_max_order()
data["order"] = 1 if order is None else order + 1
data["state"] = "I"
return await super()._pre_add_callback(data)

View file

@ -53,7 +53,7 @@ async def error_middleware(request, handler):
return web.json_response(status=500, data={'error': message}) return web.json_response(status=500, data={'error': message})
except MultipleInvalid as ex: except MultipleInvalid as ex:
return web.json_response(status=500, data={'error': str(ex)}) return web.json_response(status=500, data={'error': str(ex)})
return web.json_response({'error': message}) return web.json_response(status=500, data={'error': message})
class CraftBeerPi(): class CraftBeerPi():
@ -160,7 +160,7 @@ class CraftBeerPi():
} }
switcher[http_method]() switcher[http_method]()
print("ADDD ", routes)
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()
@ -169,7 +169,7 @@ class CraftBeerPi():
sub.add_routes([web.static('/static', static, show_index=False)]) sub.add_routes([web.static('/static', static, show_index=False)])
self.app.add_subapp(url_prefix, sub) self.app.add_subapp(url_prefix, sub)
else: else:
print("ADDD ", routes)
self.app.add_routes(routes) self.app.add_routes(routes)
def _swagger_setup(self): def _swagger_setup(self):

View file

@ -81,11 +81,35 @@ class StepModel(DBModel):
@classmethod @classmethod
async def reset_all_steps(cls): async def reset_all_steps(cls):
print("RESET ALL STEPS NOW")
async with aiosqlite.connect(DATABASE_FILE) as db: async with aiosqlite.connect(DATABASE_FILE) as db:
await db.execute("UPDATE %s SET state = 'I', stepstate = NULL , start = NULL, end = NULL " % cls.__table_name__) await db.execute("UPDATE %s SET state = 'I', stepstate = NULL , start = NULL, end = NULL " % cls.__table_name__)
await db.commit() await db.commit()
@classmethod
async def sort(cls, new_order):
async with aiosqlite.connect(DATABASE_FILE) as db:
for key, value in new_order.items():
print("ORDER", key, value)
await db.execute("UPDATE %s SET '%s' = ? WHERE id = ?" % (cls.__table_name__, "order"), (value, key))
await db.commit()
@classmethod
async def get_max_order(cls):
async with aiosqlite.connect(DATABASE_FILE) as db:
db.row_factory = aiosqlite.Row
db.row_factory = DBModel.dict_factory
async with db.execute("SELECT max(step.'order') as 'order' FROM %s" % cls.__table_name__) as cursor:
row = await cursor.fetchone()
if row is not None:
return row.get("order")
else:
return 0
class DashboardModel(DBModel): class DashboardModel(DBModel):
__fields__ = ["name"] __fields__ = ["name"]
__table_name__ = "dashboard" __table_name__ = "dashboard"

View file

@ -16,9 +16,13 @@ class CustomStepCBPi(CBPiSimpleStep):
async def run_cycle(self): async def run_cycle(self):
print("RUN", self.name) print("RUN", self.name)
self.i = self.i + 1 self.i = self.i + 1
if self.i == 5: await asyncio.sleep(5)
# print("NEXT") print("WAIT")
self.next() self.next()
#if self.i == 5:
# print("NEXT")
#self.cbpi.notify(key="step", message="HELLO FROM STEP") #self.cbpi.notify(key="step", message="HELLO FROM STEP")

View file

@ -32,7 +32,7 @@ class HttpCrudEndpoints():
@request_mapping(path="/", method="POST", auth_required=False) @request_mapping(path="/", method="POST", auth_required=False)
async def http_add(self, request): async def http_add(self, request):
data = await request.json() data = await request.json()
print(data)
obj = await self.controller.add(**data) obj = await self.controller.add(**data)
return web.json_response(obj, dumps=json_dumps) return web.json_response(obj, dumps=json_dumps)

View file

@ -224,3 +224,10 @@ class StepHttpEndpoints(HttpCrudEndpoints):
""" """
await self.cbpi.bus.fire("step/stop") await self.cbpi.bus.fire("step/stop")
return web.Response(status=204) return web.Response(status=204)
@request_mapping(path="/sort", method="POST", auth_required=False)
async def http_sort(self, request):
data = await request.json()
print(data)
await self.cbpi.step.sort(data)
return web.Response(status=204)

View file

@ -2,7 +2,7 @@
name: CraftBeerPi name: CraftBeerPi
version: 4.0 version: 4.0
index_url: /api/doc index_url: /ui/static/index.html
port: 8080 port: 8080

BIN
config/splash.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 MiB

Binary file not shown.