craftbeerpi4-pione/cbpi/controller/config_controller.py

61 lines
2.1 KiB
Python
Raw Normal View History

2021-02-16 20:37:51 +01:00
from cbpi.api.dataclasses import Config
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.utils import load_config
2021-02-16 20:37:51 +01:00
import json
2018-11-18 15:40:10 +01:00
2019-07-27 21:08:19 +02:00
class ConfigController:
2021-02-16 20:37:51 +01:00
2018-11-18 15:40:10 +01:00
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)
self.path = cbpi.config_folder.get_file_path("config.json")
self.path_static = cbpi.config_folder.get_file_path("config.yaml")
2019-01-07 22:05:52 +01:00
def get_state(self):
2021-02-16 20:37:51 +01:00
result = {}
for key, value in self.cache.items():
result[key] = value.to_dict()
return result
2019-01-07 22:05:52 +01:00
2018-12-29 00:27:19 +01:00
async def init(self):
2021-02-19 22:24:15 +01:00
self.static = load_config(self.path_static)
2021-02-16 20:37:51 +01:00
with open(self.path) as json_file:
data = json.load(json_file)
for key, value in data.items():
self.cache[key] = Config(name=value.get("name"), value=value.get("value"), description=value.get("description"), type=ConfigType(value.get("type", "string")), options=value.get("options", None) )
2018-12-29 00:27:19 +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))
if name in self.cache and self.cache[name].value is not None and 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):
if name in self.cache:
2021-02-16 20:37:51 +01:00
2018-12-29 00:27:19 +01:00
self.cache[name].value = value
2021-02-16 20:37:51 +01:00
data = {}
for key, value in self.cache.items():
data[key] = value.to_dict()
with open(self.path, "w") as file:
json.dump(data, file, indent=4, sort_keys=True)
2018-12-29 00:27:19 +01:00
async def add(self, name, value, type: ConfigType, description, options=None):
2021-02-16 20:37:51 +01:00
self.cache[name] = Config(name,value,description,type,options)
data = {}
for key, value in self.cache.items():
data[key] = value.to_dict()
with open(self.path, "w") as file:
json.dump(data, file, indent=4, sort_keys=True)