Skip to content
This repository has been archived by the owner on Oct 26, 2023. It is now read-only.

Commit

Permalink
Black reformat (#100)
Browse files Browse the repository at this point in the history
  • Loading branch information
zewelor authored Sep 6, 2019
1 parent adc7737 commit 144839f
Show file tree
Hide file tree
Showing 21 changed files with 1,745 additions and 1,299 deletions.
2 changes: 1 addition & 1 deletion const.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
DEFAULT_COMMAND_TIMEOUT = 35 # In seconds
PER_DEVICE_TIMEOUT = 6 # In seconds
PER_DEVICE_TIMEOUT = 6 # In seconds
4 changes: 2 additions & 2 deletions exceptions.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
class WorkerTimeoutError(Exception):
pass
pass


class DeviceTimeoutError(Exception):
pass
pass
78 changes: 53 additions & 25 deletions gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@
from exceptions import WorkerTimeoutError

if sys.version_info < (3, 5):
print("To use this script you need python 3.5 or newer! got %s" % sys.version_info)
sys.exit(1)
print("To use this script you need python 3.5 or newer! got %s" % sys.version_info)
sys.exit(1)

import logger

logger.setup()

import logging
Expand All @@ -23,41 +24,68 @@

parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument('-d', '--debug', action='store_true', default=False, help='Set logging to output debug information')
group.add_argument('-q', '--quiet', action='store_true', default=False, help='Set logging to just output warnings and errors')
parser.add_argument('-s', '--suppress-update-failures', dest='suppress', action='store_true', default=False, help='Suppress any errors regarding failed device updates')
group.add_argument(
"-d",
"--debug",
action="store_true",
default=False,
help="Set logging to output debug information",
)
group.add_argument(
"-q",
"--quiet",
action="store_true",
default=False,
help="Set logging to just output warnings and errors",
)
parser.add_argument(
"-s",
"--suppress-update-failures",
dest="suppress",
action="store_true",
default=False,
help="Suppress any errors regarding failed device updates",
)
parsed = parser.parse_args()

_LOGGER = logger.get()
if parsed.quiet:
_LOGGER.setLevel(logging.WARNING)
_LOGGER.setLevel(logging.WARNING)
elif parsed.debug:
_LOGGER.setLevel(logging.DEBUG)
logger.enable_debug_formatter()
_LOGGER.setLevel(logging.DEBUG)
logger.enable_debug_formatter()
else:
_LOGGER.setLevel(logging.INFO)
_LOGGER.setLevel(logging.INFO)
logger.suppress_update_failures(parsed.suppress)

_LOGGER.info('Starting')
_LOGGER.info("Starting")

global_topic_prefix = settings['mqtt'].get('topic_prefix')
global_topic_prefix = settings["mqtt"].get("topic_prefix")

mqtt = MqttClient(settings['mqtt'])
manager = WorkersManager(settings['manager'])
mqtt = MqttClient(settings["mqtt"])
manager = WorkersManager(settings["manager"])
manager.register_workers(global_topic_prefix).start(mqtt)

running = True

while running:
try:
mqtt.publish(_WORKERS_QUEUE.get(timeout=10).execute())
except queue.Empty: # Allow for SIGINT processing
pass
except WorkerTimeoutError as e:
logger.log_exception(_LOGGER, str(e) if str(e) else 'Timeout while executing worker command', suppress=True)
except (KeyboardInterrupt, SystemExit):
running = False
_LOGGER.info('Finish current jobs and shut down. If you need force exit use kill')
except Exception as e:
logger.log_exception(_LOGGER, "Fatal error while executing worker command: %s", type(e).__name__)
raise e
try:
mqtt.publish(_WORKERS_QUEUE.get(timeout=10).execute())
except queue.Empty: # Allow for SIGINT processing
pass
except WorkerTimeoutError as e:
logger.log_exception(
_LOGGER,
str(e) if str(e) else "Timeout while executing worker command",
suppress=True,
)
except (KeyboardInterrupt, SystemExit):
running = False
_LOGGER.info(
"Finish current jobs and shut down. If you need force exit use kill"
)
except Exception as e:
logger.log_exception(
_LOGGER, "Fatal error while executing worker command: %s", type(e).__name__
)
raise e
52 changes: 27 additions & 25 deletions logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,49 +2,51 @@
import logging.config
import yaml

APP_ROOT = 'bt-mqtt-gw'
APP_ROOT = "bt-mqtt-gw"
SUPPRESSION_ENABLED = False


def setup():
with open('logger.yaml', 'rt') as f:
config = yaml.safe_load(f.read())
logging.config.dictConfig(config)
with open("logger.yaml", "rt") as f:
config = yaml.safe_load(f.read())
logging.config.dictConfig(config)


def get(name=None):
if name:
logger_name = '{}.{}'.format(APP_ROOT, name)
else:
logger_name = APP_ROOT
return logging.getLogger(logger_name)
if name:
logger_name = "{}.{}".format(APP_ROOT, name)
else:
logger_name = APP_ROOT
return logging.getLogger(logger_name)


def enable_debug_formatter():
logging.getLogger().handlers[0].setFormatter(logging.getLogger('dummy_debug').handlers[0].formatter)
logging.getLogger().handlers[0].setFormatter(
logging.getLogger("dummy_debug").handlers[0].formatter
)


def reset():
app_level = get().getEffectiveLevel()
app_level = get().getEffectiveLevel()

root = logging.getLogger()
map(root.removeHandler, root.handlers[:])
map(root.removeFilter, root.filters[:])
root = logging.getLogger()
map(root.removeHandler, root.handlers[:])
map(root.removeFilter, root.filters[:])

setup()
get().setLevel(app_level)
if app_level <= logging.DEBUG:
enable_debug_formatter()
setup()
get().setLevel(app_level)
if app_level <= logging.DEBUG:
enable_debug_formatter()


def suppress_update_failures(suppress):
global SUPPRESSION_ENABLED
SUPPRESSION_ENABLED = suppress
global SUPPRESSION_ENABLED
SUPPRESSION_ENABLED = suppress


def log_exception(logger, message, *args, **kwargs):
if not ('suppress' in kwargs and kwargs.pop('suppress') and SUPPRESSION_ENABLED):
if logger.isEnabledFor(logging.DEBUG):
logger.exception(message, *args, **kwargs)
elif logger.isEnabledFor(logging.WARNING):
logger.warning(message, *args, **kwargs)
if not ("suppress" in kwargs and kwargs.pop("suppress") and SUPPRESSION_ENABLED):
if logger.isEnabledFor(logging.DEBUG):
logger.exception(message, *args, **kwargs)
elif logger.isEnabledFor(logging.WARNING):
logger.warning(message, *args, **kwargs)
Loading

0 comments on commit 144839f

Please sign in to comment.