use json instead of ini: less readable, easier to work with

This commit is contained in:
Von Random 2017-12-16 02:55:28 +03:00
parent f5c49008ec
commit 5e17aca8e2
11 changed files with 108 additions and 82 deletions

View file

@ -1,23 +0,0 @@
[main]
format = i3
[network]
plugin = ping
hosts = de-ber-as20647.anchors.atlas.ripe.net,nl-ams-as1101.anchors.atlas.ripe.net,uk-boh-as196745.anchors.atlas.ripe.net
title = NET
hide_ok = false
[memory]
plugin = mem
[battery]
plugin = batt
[day]
plugin = date
color = #FF0000
format = %%A %%d
[time]
plugin = date
format = %%H:%%M

38
conf.json Normal file
View file

@ -0,0 +1,38 @@
{
"output_format": "i3",
"plugins": [
{
"name": "ping",
"hosts": [
"de-ber-as20647.anchors.atlas.ripe.net",
"nl-ams-as1101.anchors.atlas.ripe.net",
"uk-boh-as196745.anchors.atlas.ripe.net"
],
"title": "NET"
},
{
"name": "disk",
"partition": "/",
"problem": 80,
"hide_ok": false
},
{
"name": "disk",
"partition": "/home",
"problem": 90
},
{
"name": "pacman"
},
{
"name": "mem"
},
{
"name": "load"
},
{
"name": "date",
"format": "%a %d %H:%M"
}
]
}

View file

@ -2,17 +2,24 @@ import threading
import time import time
def parse_config(config, defaults):
result = dict()
for key in defaults:
result[key] = config[key] if key in config else defaults[key]
return result
class PluginThreadCommon: class PluginThreadCommon:
def __init__(self, section, config): def __init__(self, config, defaults=dict()):
if 'freq' not in defaults:
defaults['freq'] = 1
if 'hide_ok' not in defaults:
defaults['hide_ok'] = True
self.conf = parse_config(config, defaults)
self.status = dict() self.status = dict()
self.hide = False self.hide = False
self.thread = threading.Thread(target=self.run) self.thread = threading.Thread(target=self.run)
self.thread.daemon = True self.thread.daemon = True
self.freq = config.getint(section, 'freq', fallback=1)
self.problem_value = config.getint(section, 'problem', fallback=70)
self.hide_ok = config.getboolean(section, 'hide_ok', fallback=True)
if config.has_option(section, 'color'):
self.status['color'] = config.get(section, 'color')
def start(self): def start(self):
self.thread.start() self.thread.start()
@ -23,4 +30,4 @@ class PluginThreadCommon:
def run(self): def run(self):
while True: while True:
self.main() self.main()
time.sleep(self.freq) time.sleep(self.conf['freq'])

View file

@ -5,11 +5,12 @@ BATTERY_DIR = '/sys/class/power_supply/BAT0/'
class PluginThread(plugins.PluginThreadCommon): class PluginThread(plugins.PluginThreadCommon):
def __init__(self, section, config): def __init__(self, config):
super(PluginThread, self).__init__(section, config) super(PluginThread, self).__init__(config)
def main(self): def main(self):
with open(BATTERY_DIR + 'capacity', 'r') as capacity, \ with \
open(BATTERY_DIR + 'capacity', 'r') as capacity, \
open(BATTERY_DIR + 'status', 'r') as status: open(BATTERY_DIR + 'status', 'r') as status:
batt_stat = status.read().strip() batt_stat = status.read().strip()
batt_capacity = capacity.read().strip() batt_capacity = capacity.read().strip()

View file

@ -3,16 +3,14 @@ import plugins
class PluginThread(plugins.PluginThreadCommon): class PluginThread(plugins.PluginThreadCommon):
def __init__(self, section, config): def __init__(self, config):
super(PluginThread, self).__init__(section, config) defaults = {'format': '%c', 'tz': None}
self.date_format = config.get(section, 'format', fallback='%c') super(PluginThread, self).__init__(config, defaults)
tz = config.get(section, 'TZ', fallback=None) self.timezone = None
if tz: if self.conf['tz']:
import pytz import pytz
self.tz = pytz.timezone(tz) self.timezone = pytz.timezone(self.conf['tz'])
else:
self.tz = None
def main(self): def main(self):
now = datetime.datetime.now(tz=self.tz) now = datetime.datetime.now(tz=self.timezone)
self.status['full_text'] = now.strftime(self.date_format) self.status['full_text'] = now.strftime(self.conf['format'])

View file

@ -3,18 +3,18 @@ import psutil
class PluginThread(plugins.PluginThreadCommon): class PluginThread(plugins.PluginThreadCommon):
def __init__(self, section, config): def __init__(self, config):
super(PluginThread, self).__init__(section, config) defaults = {'partition': '/', 'problem': 80}
self.part = config.get(section, 'part') super(PluginThread, self).__init__(config, defaults)
def main(self): def main(self):
du_stat = psutil.disk_usage(self.part) du_stat = psutil.disk_usage(self.conf['partition'])
if du_stat.percent >= self.problem_value: if du_stat.percent >= self.conf['problem']:
self.hide = False self.hide = False
self.status['urgent'] = True self.status['urgent'] = True
else: else:
self.hide = True self.hide = True
self.status['urgent'] = False self.status['urgent'] = False
du_free = str(round(du_stat.free / 2**30, 2)) du_free = str(round(du_stat.free / 2**30, 2))
du = self.part + ': ' + du_free + 'G' disk_usage = self.conf['partition'] + ': ' + du_free + 'G'
self.status['full_text'] = du self.status['full_text'] = disk_usage

View file

@ -3,12 +3,13 @@ import plugins
class PluginThread(plugins.PluginThreadCommon): class PluginThread(plugins.PluginThreadCommon):
def __init__(self, section, config): def __init__(self, config):
super(PluginThread, self).__init__(section, config) defaults = {'problem': 1}
super(PluginThread, self).__init__(config, defaults)
def main(self): def main(self):
loads = os.getloadavg() loads = os.getloadavg()
if loads[0] >= self.problem_value: if loads[0] >= self.conf['problem']:
self.hide = False self.hide = False
self.status['urgent'] = True self.status['urgent'] = True
else: else:

View file

@ -3,8 +3,8 @@ import plugins
class PluginThread(plugins.PluginThreadCommon): class PluginThread(plugins.PluginThreadCommon):
def __init__(self, section, config): def __init__(self, config):
super(PluginThread, self).__init__(section, config) super(PluginThread, self).__init__(config)
def main(self): def main(self):
mem_stat = psutil.virtual_memory() mem_stat = psutil.virtual_memory()

View file

@ -3,9 +3,9 @@ import subprocess
class PluginThread(plugins.PluginThreadCommon): class PluginThread(plugins.PluginThreadCommon):
def __init__(self, section, config): def __init__(self, config):
super(PluginThread, self).__init__(section, config) defaults = {'freq': 15}
self.freq = config.getint(section, 'freq', fallback=15) super(PluginThread, self).__init__(config, defaults)
self.format_status(0) self.format_status(0)
def format_status(self, count): def format_status(self, count):

View file

@ -4,15 +4,13 @@ import plugins
class PluginThread(plugins.PluginThreadCommon): class PluginThread(plugins.PluginThreadCommon):
def __init__(self, section, config): def __init__(self, config):
super(PluginThread, self).__init__(section, config) defaults = {'hosts': list(), 'title': 'PING', 'timeout': 150}
self.hosts = config.get(section, 'hosts').split(',') super(PluginThread, self).__init__(config, defaults)
self.title = config.get(section, 'title')
self.timeout = config.get(section, 'timeout', fallback='150')
self.format_status('n/a') self.format_status('n/a')
def format_status(self, state): def format_status(self, state):
self.status['full_text'] = self.title + ': ' + state self.status['full_text'] = self.conf['title'] + ': ' + state
if state == 'on': if state == 'on':
self.status['urgent'] = False self.status['urgent'] = False
self.hide = True self.hide = True
@ -20,9 +18,10 @@ class PluginThread(plugins.PluginThreadCommon):
self.status['urgent'] = True self.status['urgent'] = True
def main(self): def main(self):
random.shuffle(self.hosts) random.shuffle(self.conf['hosts'])
for host in self.hosts: for host in self.conf['hosts']:
fping = 'fping -qc1t' + self.timeout + ' ' + host + ' &>/dev/null' fping = 'fping -qc1t' + str(self.conf['timeout'])\
+ ' ' + host + ' &>/dev/null'
response = os.system(fping) response = os.system(fping)
if response == 0: if response == 0:
self.format_status('on') self.format_status('on')

View file

@ -3,7 +3,6 @@
# TODO: add documentation / comments # TODO: add documentation / comments
# TODO: interactivity support # TODO: interactivity support
import argparse import argparse
import configparser
import importlib import importlib
import json import json
import os import os
@ -12,7 +11,7 @@ import time
import plugins import plugins
DEFAULT_CONFIG = os.path.join(os.environ['HOME'], '.config/vdstatus/conf.ini') DEFAULT_CONFIG = os.path.join(os.environ['HOME'], '.config/vdstatus/conf.json')
def parse_arguments(arguments=sys.argv[1:]): def parse_arguments(arguments=sys.argv[1:]):
@ -26,22 +25,25 @@ def parse_arguments(arguments=sys.argv[1:]):
class PluginRunner: class PluginRunner:
def __init__(self, config_file=DEFAULT_CONFIG): def __init__(self, config_file=DEFAULT_CONFIG):
self.config = configparser.ConfigParser() defaults = {
self.config.read(config_file) 'output_format': 'term',
self.output_format = self.config.get('main', 'format', fallback='term') 'output_freq': 1,
self.output_freq = self.config.getint('main', 'output_freq', fallback=1) 'hide_ok': True,
self.hide_ok = self.config.getboolean('main', 'hide_ok', fallback=True) 'plugins': [{'name': 'date'}]
}
config = dict()
with open(config_file) as config_data:
config = json.load(config_data)
self.conf = plugins.parse_config(config, defaults)
self.plugins_loaded = list() self.plugins_loaded = list()
self.config.remove_section('main')
self.format_output = self.format_term self.format_output = self.format_term
for section in self.config.sections(): for plugin in self.conf['plugins']:
plugin_name = self.config.get(section, 'plugin') mod = importlib.import_module('.' + plugin['name'], 'plugins')
mod = importlib.import_module('.' + plugin_name, 'plugins') thread_object = mod.PluginThread(plugin)
thread_object = mod.PluginThread(section, self.config)
self.plugins_loaded.append(thread_object) self.plugins_loaded.append(thread_object)
def start(self): def start(self):
if self.output_format == 'i3': if self.conf['output_format'] == 'i3':
print('{"version":1}\n[', flush=True) print('{"version":1}\n[', flush=True)
self.format_output = self.format_i3wm self.format_output = self.format_i3wm
for plugin in self.plugins_loaded: for plugin in self.plugins_loaded:
@ -50,7 +52,10 @@ class PluginRunner:
def query(self): def query(self):
outputs = list() outputs = list()
for plugin in self.plugins_loaded: for plugin in self.plugins_loaded:
if not self.hide_ok or not plugin.hide_ok or not plugin.hide: if \
not self.conf['hide_ok'] or \
not plugin.conf['hide_ok'] or \
not plugin.hide:
outputs.append(plugin.status) outputs.append(plugin.status)
print(self.format_output(outputs), flush=True) print(self.format_output(outputs), flush=True)
@ -58,7 +63,7 @@ class PluginRunner:
while True: while True:
try: try:
self.query() self.query()
time.sleep(self.output_freq) time.sleep(self.conf['output_freq'])
except (KeyboardInterrupt, SystemExit): except (KeyboardInterrupt, SystemExit):
sys.exit() sys.exit()