chuwi-minibook-tablet-mode/sysmoded
Richard Neumann 359fecb027 Refac.
2019-05-21 15:26:30 +02:00

84 lines
2 KiB
Python
Executable file

#! /usr/bin/env python3
"""System mode daemon."""
from argparse import ArgumentParser
from json import load
from logging import DEBUG, INFO, basicConfig, getLogger
from pathlib import Path
from subprocess import Popen
CONFIG_FILE = Path('/etc/tablet-mode.json')
DESCRIPTION = 'Setup system for laptop or tablet mode.'
EVTEST = '/usr/bin/evtest'
LOG_FORMAT = '[%(levelname)s] %(name)s: %(message)s'
LOGGER = getLogger(__file__)
def get_arguments():
"""Parses the CLI arguments."""
parser = ArgumentParser(description=DESCRIPTION)
parser.add_argument(
'-v', '--verbose', action='store_true',
help='turn on verbose logging')
subparsers = parser.add_subparsers(dest='mode')
subparsers.add_parser('laptop', help='enable laptop mode')
subparsers.add_parser('tablet', help='enable tablet mode')
return parser.parse_args()
def load_configuration():
"""Returns the configuration."""
try:
with CONFIG_FILE.open('r') as cfg:
return load(cfg)
except FileNotFoundError:
LOGGER.warning('Config file %s does not exist.', CONFIG_FILE)
return {}
def disable_device(device):
"""Disables the respective device via evtest."""
return Popen((EVTEST, '--grab', device))
def disable_devices(devices):
"""Disables the given devices."""
subprocesses = []
for device in devices:
subprocess = disable_device(device)
subprocesses.append(subprocess)
for subprocess in subprocesses:
subprocess.wait()
def get_devices(mode):
"""Reads the device from the config file."""
configuration = load_configuration()
devices = configuration.get(mode) or ()
if not devices:
LOGGER.info('No devices configured to disable.')
return devices
def main():
"""Runs the main program."""
arguments = get_arguments()
level = DEBUG if arguments.verbose else INFO
basicConfig(level=level, format=LOG_FORMAT)
devices = get_devices(arguments.mode)
disable_devices(devices)
if __name__ == '__main__':
main()