craftbeerpi4-pione/cbpi/controller/basic_controller2.py

180 lines
6.9 KiB
Python
Raw Normal View History

2021-01-22 23:25:20 +01:00
import logging
import os.path
import json
from cbpi.api.dataclasses import Fermenter, Actor, Props, NotificationType
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 = ""
2022-04-23 20:32:32 +02:00
self.sorting = False
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 = self.cbpi.config_folder.get_file_path(file)
2021-01-22 23:25:20 +01:00
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):
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):
try:
logging.info("{} Load ".format(self.name))
with open(self.path) as json_file:
data = json.load(json_file)
data['data'].sort(key=lambda x: x.get('name').upper())
2021-02-16 20:37:51 +01:00
for i in data["data"]:
self.data.append(self.create(i))
2021-02-16 20:37:51 +01:00
if self.autostart is True:
for item in self.data:
logging.info("{} Starting ".format(self.name))
await self.start(item.id)
await self.push_udpate()
except Exception as e:
#logging.error(e)
logging.warning("Invalid {} file - Creating empty file".format(self.path))
os.remove(self.path)
with open(self.path, "w") as file:
json.dump(dict( data=[]), file, indent=4, sort_keys=True)
with open(self.path) as json_file:
data = json.load(json_file)
data['data'].sort(key=lambda x: x.get('name').upper())
for i in data["data"]:
self.data.append(self.create(i))
if self.autostart is True:
for item in self.data:
logging.info("{} Starting ".format(self.name))
await self.start(item.id)
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()
2021-03-14 11:52:46 +01:00
2021-01-22 23:25:20 +01:00
async def push_udpate(self):
2022-04-23 20:32:32 +02:00
self.cbpi.ws.send(dict(topic=self.update_key, data=list(map(lambda item: item.to_dict(), self.data))),self.sorting)
#self.cbpi.push_update("cbpi/{}".format(self.update_key), list(map(lambda item: item.to_dict(), self.data)))
for item in self.data:
self.cbpi.push_update("cbpi/{}/{}".format(self.update_key,item.id), item.to_dict())
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:
item = self.find_by_id(id)
2021-02-16 20:37:51 +01:00
await item.instance.stop()
item.instance.running = False
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)
if item.instance is not None and item.instance.running 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.running = True
item.instance.task = asyncio.get_event_loop().create_task(item.instance._run())
#item.instance.task = self._loop.create_task(item.instance._run())
2021-02-16 20:37:51 +01:00
2021-01-30 22:29:33 +01:00
logging.info("{} started {}".format(self.name, id))
# await self.push_udpate()
2021-01-22 23:25:20 +01:00
except Exception as e:
line="{} Cant start {} - {}".format(self.name, id, e)
logging.error(line)
self.cbpi.notify("Error", line, NotificationType.ERROR)
2021-01-22 23:25:20 +01:00
def get_types(self):
# logging.info("{} Get Types".format(self.name))
2021-01-22 23:25:20 +01:00
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-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:
2022-04-02 16:27:09 +02:00
logging.error("{} Failed to call action on {} {} {}".format(self.name, id, action, e))