craftbeerpi4-pione/cbpi/controller/basic_controller2.py

152 lines
5.4 KiB
Python
Raw Normal View History

2021-01-22 23:25:20 +01:00
import logging
import os.path
import json
2021-02-16 20:37:51 +01:00
from cbpi.api.dataclasses import Actor, Props
2021-01-22 23:25:20 +01:00
import sys, os
import shortuuid
import asyncio
from tabulate import tabulate
class BasicController:
2021-02-16 20:37:51 +01:00
def __init__(self, cbpi, resource, file):
self.resource = resource
2021-01-24 22:14:57 +01:00
self.update_key = ""
2021-01-22 23:25:20 +01:00
self.name = self.__class__.__name__
self.cbpi = cbpi
self.cbpi.register(self)
self.service = self
self.types = {}
self.logger = logging.getLogger(__name__)
self.data = []
self.autostart = True
self._loop = asyncio.get_event_loop()
self.path = os.path.join(".", 'config', file)
self.cbpi.app.on_cleanup.append(self.shutdown)
async def init(self):
await self.load()
2021-02-16 20:37:51 +01:00
def create(self, data):
2021-01-22 23:25:20 +01:00
2021-02-16 20:37:51 +01:00
return self.resource(data.get("id"), data.get("name"), type=data.get("type"), props=Props(data.get("props", {})) )
2021-01-22 23:25:20 +01:00
async def load(self):
logging.info("{} Load ".format(self.name))
with open(self.path) as json_file:
data = json.load(json_file)
2021-02-16 20:37:51 +01:00
for i in data["data"]:
self.data.append(self.create(i))
2021-01-22 23:25:20 +01:00
if self.autostart is True:
2021-02-16 20:37:51 +01:00
for item in self.data:
2021-01-22 23:25:20 +01:00
logging.info("{} Starting ".format(self.name))
2021-02-16 20:37:51 +01:00
await self.start(item.id)
2021-01-30 22:29:33 +01:00
await self.push_udpate()
2021-01-22 23:25:20 +01:00
async def save(self):
logging.info("{} Save ".format(self.name))
2021-02-16 20:37:51 +01:00
data = dict(data=list(map(lambda actor: actor.to_dict(), self.data)))
2021-01-22 23:25:20 +01:00
with open(self.path, "w") as file:
json.dump(data, file, indent=4, sort_keys=True)
await self.push_udpate()
async def push_udpate(self):
2021-02-16 20:37:51 +01:00
self.cbpi.ws.send(dict(topic=self.update_key, data=list(map(lambda item: item.to_dict(), self.data))))
2021-01-22 23:25:20 +01:00
def find_by_id(self, id):
2021-02-16 20:37:51 +01:00
return next((item for item in self.data if item.id == id), None)
2021-01-22 23:25:20 +01:00
def get_index_by_id(self, id):
2021-02-16 20:37:51 +01:00
return next((i for i, item in enumerate(self.data) if item.id == id), None)
2021-01-22 23:25:20 +01:00
async def shutdown(self, app):
logging.info("{} Shutdown ".format(self.name))
tasks = []
for item in self.data:
2021-02-16 20:37:51 +01:00
if item.instance is not None and item.instance.running is True:
item.instance.task.cancel()
tasks.append(item.instance.task)
2021-01-22 23:25:20 +01:00
await asyncio.gather(*tasks)
await self.save()
async def stop(self, id):
logging.info("{} Stop Id {} ".format(self.name, id))
try:
2021-02-16 20:37:51 +01:00
print("STOP NOW")
2021-01-22 23:25:20 +01:00
item = self.find_by_id(id)
2021-02-16 20:37:51 +01:00
await item.instance.stop()
2021-01-30 22:29:33 +01:00
await self.push_udpate()
2021-01-22 23:25:20 +01:00
except Exception as e:
logging.error("{} Cant stop {} - {}".format(self.name, id, e))
async def start(self, id):
logging.info("{} Start Id {} ".format(self.name, id))
try:
item = self.find_by_id(id)
2021-02-16 20:37:51 +01:00
if item.instance is not None and item.instance.state is True:
2021-01-22 23:25:20 +01:00
logging.warning("{} already running {}".format(self.name, id))
return
2021-02-16 20:37:51 +01:00
if item.type is None:
logging.warning("{} No Type {}".format(self.name, id))
return
clazz = self.types[item.type]["class"]
item.instance = clazz(self.cbpi, item.id, item.props)
await item.instance.start()
item.instance.task = self._loop.create_task(item.instance._run())
2021-01-30 22:29:33 +01:00
logging.info("{} started {}".format(self.name, id))
2021-02-16 20:37:51 +01:00
await self.push_udpate()
2021-01-22 23:25:20 +01:00
except Exception as e:
logging.error("{} Cant start {} - {}".format(self.name, id, e))
def get_types(self):
logging.info("{} Get Types".format(self.name))
result = {}
for key, value in self.types.items():
result[key] = dict(name=value.get("name"), properties=value.get("properties"), actions=value.get("actions"))
return result
def get_state(self):
logging.info("{} Get State".format(self.name))
2021-02-16 20:37:51 +01:00
return {"data": list(map(lambda x: x.to_dict(), self.data)), "types":self.get_types()}
2021-01-22 23:25:20 +01:00
2021-02-16 20:37:51 +01:00
async def add(self, item):
2021-02-20 09:24:03 +01:00
print(item)
2021-01-22 23:25:20 +01:00
logging.info("{} Add".format(self.name))
2021-02-16 20:37:51 +01:00
item.id = shortuuid.uuid()
2021-01-22 23:25:20 +01:00
self.data.append(item)
if self.autostart is True:
2021-02-20 09:24:03 +01:00
await self.start(item.id)
2021-01-22 23:25:20 +01:00
await self.save()
return item
2021-02-16 20:37:51 +01:00
async def update(self, item):
2021-01-22 23:25:20 +01:00
logging.info("{} Get Update".format(self.name))
2021-02-16 20:37:51 +01:00
await self.stop(item.id)
self.data = list(map(lambda old_item: item if old_item.id == item.id else old_item, self.data))
2021-02-02 00:07:58 +01:00
if self.autostart is True:
2021-02-16 20:37:51 +01:00
await self.start(item.id)
2021-01-22 23:25:20 +01:00
await self.save()
2021-02-16 20:37:51 +01:00
return self.find_by_id(item.id)
2021-01-22 23:25:20 +01:00
async def delete(self, id) -> None:
logging.info("{} Delete".format(self.name))
await self.stop(id)
2021-02-16 20:37:51 +01:00
self.data = list(filter(lambda x: x.id != id, self.data))
2021-01-22 23:25:20 +01:00
await self.save()
async def call_action(self, id, action, parameter) -> None:
logging.info("{} call all Action {} {}".format(self.name, id, action))
try:
item = self.find_by_id(id)
2021-02-16 20:37:51 +01:00
await item.instance.__getattribute__(action)(**parameter)
2021-01-22 23:25:20 +01:00
except Exception as e:
logging.error("{} Faild to call action on {} {} {}".format(self.name, id, action, e))