Skip to content

Commit

Permalink
- Moved configuration to EasyCo
Browse files Browse the repository at this point in the history
- MQTT has listen_only switch, too
  • Loading branch information
spacemanspiff2007 committed Oct 5, 2019
1 parent 763aa19 commit 916058d
Show file tree
Hide file tree
Showing 10 changed files with 105 additions and 243 deletions.
72 changes: 28 additions & 44 deletions HABApp/config/_conf_mqtt.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from voluptuous import All, Invalid, Length
import typing

from .configentry import ConfigEntry, ConfigEntryContainer
from EasyCo import ConfigContainer, ConfigEntry
from voluptuous import Invalid


def MqttTopicValidator(msg=None):
Expand Down Expand Up @@ -32,54 +33,37 @@ def f(v):
return f


class MqttConnection(ConfigEntry):
def __init__(self):
super().__init__()
self._entry_name = 'connection'
self.client_id = 'HABApp'
self.host = ''
self.port = 8883
self.user = ''
self.password = ''
self.tls = True
self.tls_insecure = False
class Connection(ConfigContainer):
client_id: str = 'HABApp'
host: str = ''
port: int = 8883
user: str = ''
password: str = ''
tls: bool = True
tls_insecure: bool = False

self._entry_validators['client_id'] = All(str, Length(min=1))

self._entry_kwargs['password'] = {'default': ''}
self._entry_kwargs['tls_insecure'] = {'default': False}

class Subscribe(ConfigContainer):
qos: int = ConfigEntry(default=0, description='Default QoS for subscribing')
topics: typing.List[typing.Union[str, int]] = ConfigEntry(
default_factory=lambda: list(('#', 0)), validator=MqttTopicValidator
)

class Subscribe(ConfigEntry):
def __init__(self):
super().__init__()
self.qos = 0
self.topics = ['#', 0]

self._entry_validators['topics'] = MqttTopicValidator()
self._entry_kwargs['topics'] = {'default': [('#', 0)]}
self._entry_kwargs['default_qos'] = {'default': 0}
class Publish(ConfigContainer):
qos: int = ConfigEntry(default=0, description='Default QoS when publishing values')
retain: bool = ConfigEntry(default=False, description='Default retain flag when publishing values')


class Publish(ConfigEntry):
def __init__(self):
super().__init__()
self.qos = 0
self.retain = False
class General(ConfigContainer):
listen_only: bool = ConfigEntry(
False, description='If True HABApp will not publish any value to the broker'
)


class mqtt(ConfigEntry):
def __init__(self):
super().__init__()
self.client_id = ''
self.tls = True
self.tls_insecure = False

self._entry_kwargs['tls_insecure'] = {'default': False}


class Mqtt(ConfigEntryContainer):
def __init__(self):
self.connection = MqttConnection()
self.subscribe = Subscribe()
self.publish = Publish()
class Mqtt(ConfigContainer):
connection = Connection()
subscribe = Subscribe()
publish = Publish()
general = General()
46 changes: 20 additions & 26 deletions HABApp/config/_conf_openhab.py
Original file line number Diff line number Diff line change
@@ -1,34 +1,28 @@
from .configentry import ConfigEntry, ConfigEntryContainer
from EasyCo import ConfigContainer, ConfigEntry


class Ping(ConfigEntry):
def __init__(self):
super().__init__()
self.enabled = False
self.item = ''
self.interval = 10
class Ping(ConfigContainer):
enabled: bool = ConfigEntry(True, description='If enabled the configured item will show how long it takes to send '
'an update from HABApp and get the updated value back from openhab'
'in milliseconds')
item: str = ConfigEntry('HABApp_Ping', description='Name of the item')
interval: int = ConfigEntry(10, description='Seconds between two pings')


class General(ConfigEntry):
def __init__(self):
super().__init__()
self.listen_only = False
class General(ConfigContainer):
listen_only: bool = ConfigEntry(
False, description='If True HABApp will not change anything on the openhab instance.'
)


class Connection(ConfigEntry):
def __init__(self):
super().__init__()
self.host = 'localhost'
self.port = 8080
self.user = ''
self.password = ''
class Connection(ConfigContainer):
host: str = 'localhost'
port: int = 8080
user: str = ''
password: str = ''

self._entry_kwargs['user'] = {'default': ''}
self._entry_kwargs['password'] = {'default': ''}


class Openhab(ConfigEntryContainer):
def __init__(self):
self.ping = Ping()
self.connection = Connection()
self.general = General()
class Openhab(ConfigContainer):
ping = Ping()
connection = Connection()
general = General()
103 changes: 32 additions & 71 deletions HABApp/config/config.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,19 @@
import codecs
import logging
import logging.config
import sys
import time
from pathlib import Path
import sys

import ruamel.yaml
from voluptuous import MultipleInvalid, Schema
from EasyCo import ConfigFile, PathContainer

from HABApp.__version__ import __VERSION__
from HABApp.runtime import FileEventTarget
from ._conf_mqtt import Mqtt
from ._conf_openhab import Openhab
from .configentry import ConfigEntry
from .default_logfile import get_default_logfile

from HABApp.runtime import FileEventTarget

_yaml_param = ruamel.yaml.YAML(typ='safe')
_yaml_param.default_flow_style = False
_yaml_param.default_style = False
Expand All @@ -35,13 +33,26 @@ class InvalidConfigException(Exception):
pass


class Directories(ConfigEntry):
def __init__(self):
super().__init__()
self.logging: Path = 'log'
self.rules: Path = 'rules'
self.lib: Path = 'lib'
self.param: Path = 'param'
class Directories(PathContainer):
logging: Path = 'log'
rules: Path = 'rules'
lib: Path = 'lib'
param: Path = 'param'

def on_all_values_set(self):
try:
if not self.rules.is_dir():
self.rules.mkdir()
if not self.logging.is_dir():
self.logging.mkdir()
except Exception as e:
log.error(e)


class HABAppConfigFile(ConfigFile):
directories = Directories()
mqtt = Mqtt()
openhab = Openhab()


class Config(FileEventTarget):
Expand All @@ -59,12 +70,12 @@ def __init__(self, runtime, config_folder : Path):
self.file_conf_logging = self.folder_conf / 'logging.yml'

# these are the accessible config entries
self.directories = Directories()
self.mqtt = Mqtt()
self.openhab = Openhab()
self.config = HABAppConfigFile()
self.directories = self.config.directories
self.mqtt = self.config.mqtt
self.openhab = self.config.openhab

# if the config does not exist it will be created
self.__check_create_config()
self.__check_create_logging()

# folder watcher
Expand Down Expand Up @@ -97,31 +108,6 @@ def reload_file(self, path: Path):
def remove_file(self, path: Path):
pass

def __check_create_config(self):
if self.file_conf_habapp.is_file():
return None

cfg = {}
self.directories.insert_data(cfg)
self.openhab.insert_data(cfg)
self.mqtt.insert_data(cfg)

print( f'Creating {self.file_conf_habapp.name} in {self.file_conf_habapp.parent}')
with self.file_conf_habapp.open('w', encoding='utf-8') as file:
_yaml_param.dump(cfg, file)

# Create default folder for rules, too
# Logging directories will get created elsewhere
# Param files are optional
if isinstance(self.directories.rules, str):
(self.file_conf_habapp.parent / self.directories.rules).resolve().mkdir()
if isinstance(self.directories.logging, str):
(self.file_conf_habapp.parent / self.directories.logging).resolve().mkdir()

time.sleep(0.1)
return None


def __check_create_logging(self):
if self.file_conf_logging.is_file():
return None
Expand All @@ -134,37 +120,12 @@ def __check_create_logging(self):
return None

def load_cfg(self):
# File has to exist - check because we also get FileDelete events
if not self.file_conf_habapp.is_file():
return
# We always try to create the dummy config
# # File has to exist - check because we also get FileDelete events
# if not self.file_conf_habapp.is_file():
# return

with self.file_conf_habapp.open('r', encoding='utf-8') as file:
cfg = _yaml_param.load(file)
try:
_s = {}
self.directories.update_schema(_s)
self.openhab.update_schema(_s)
self.mqtt.update_schema(_s)
cfg = Schema(_s)(cfg)
except MultipleInvalid as e:
log.error(f'Error while loading {self.file_conf_habapp.name}:')
log.error(e)
raise InvalidConfigException()

self.directories.load_data(cfg)
self.openhab.load_data(cfg)
self.mqtt.load_data(cfg)

# make Path absolute for all directory entries
for k, v in self.directories.iter_entry():
__entry = Path(v)
if not __entry.is_absolute():
__entry = self.folder_conf / __entry
self.directories.__dict__[k] = __entry.resolve()

if not self.directories.logging.is_dir():
print( f'Creating log-dir: {self.directories.logging}')
self.directories.logging.mkdir()
self.config.load(self.file_conf_habapp)

# Set path for libraries
if self.directories.lib.is_dir():
Expand Down
97 changes: 0 additions & 97 deletions HABApp/config/configentry.py

This file was deleted.

Loading

0 comments on commit 916058d

Please sign in to comment.