2018-12-29 00:27:19 +01:00
|
|
|
import logging
|
|
|
|
import os
|
|
|
|
|
2019-01-05 20:43:48 +01:00
|
|
|
from cbpi.api.config import ConfigType
|
|
|
|
from cbpi.database.model import ConfigModel
|
|
|
|
from cbpi.utils import load_config
|
2019-01-02 00:48:36 +01:00
|
|
|
|
2018-11-18 15:40:10 +01:00
|
|
|
|
2019-07-27 21:08:19 +02:00
|
|
|
class ConfigController:
|
2018-11-18 15:40:10 +01:00
|
|
|
'''
|
|
|
|
The main actor controller
|
|
|
|
'''
|
|
|
|
model = ConfigModel
|
|
|
|
|
|
|
|
def __init__(self, cbpi):
|
2018-12-29 00:27:19 +01:00
|
|
|
self.cache = {}
|
|
|
|
self.logger = logging.getLogger(__name__)
|
2018-11-18 15:40:10 +01:00
|
|
|
self.cbpi = cbpi
|
2019-01-02 21:20:44 +01:00
|
|
|
self.cbpi.register(self)
|
2018-11-18 15:40:10 +01:00
|
|
|
|
2019-01-07 22:05:52 +01:00
|
|
|
|
|
|
|
def get_state(self):
|
|
|
|
return self.cache
|
|
|
|
|
2018-12-29 00:27:19 +01:00
|
|
|
async def init(self):
|
2021-02-01 01:38:04 +01:00
|
|
|
this_directory = os.sep.join(os.path.abspath(__file__).split(os.sep)[:-2])
|
2021-02-02 21:22:59 +01:00
|
|
|
|
2021-02-01 01:38:04 +01:00
|
|
|
self.static = load_config("{}/config/config.yaml".format(this_directory))
|
2018-12-29 00:27:19 +01:00
|
|
|
items = await self.model.get_all()
|
|
|
|
for key, value in items.items():
|
|
|
|
self.cache[value.name] = value
|
|
|
|
|
2018-12-31 00:22:00 +01:00
|
|
|
def get(self, name, default=None):
|
2019-07-27 21:08:19 +02:00
|
|
|
self.logger.debug("GET CONFIG VALUE %s (default %s)" % (name, default))
|
2018-12-29 00:27:19 +01:00
|
|
|
if name in self.cache and self.cache[name].value is not None:
|
2021-02-06 00:40:55 +01:00
|
|
|
print("name", self.cache[name].value)
|
2018-12-29 00:27:19 +01:00
|
|
|
return self.cache[name].value
|
|
|
|
else:
|
|
|
|
return default
|
|
|
|
|
|
|
|
async def set(self, name, value):
|
|
|
|
self.logger.debug("SET %s = %s" % (name, value))
|
|
|
|
if name in self.cache:
|
|
|
|
self.cache[name].value = value
|
2019-01-02 21:20:44 +01:00
|
|
|
await self.model.update(**self.cache[name].__dict__)
|
2018-12-29 00:27:19 +01:00
|
|
|
await self.cbpi.bus.fire(topic="config/%s/update" % name, name=name, value=value)
|
|
|
|
|
|
|
|
async def add(self, name, value, type: ConfigType, description, options=None):
|
2019-01-02 21:20:44 +01:00
|
|
|
await self.model.insert(name=name, value=value, type=type.value, description=description, options=options)
|
2018-12-29 00:27:19 +01:00
|
|
|
await self.cbpi.bus.fire(topic="config/%s/add" % name, name=name, value=value)
|