Skip to content
Snippets Groups Projects
Commit 5673b4c3 authored by David Huss's avatar David Huss :speech_balloon:
Browse files

Try logging instead of print

parent 306a5cb5
No related branches found
No related tags found
No related merge requests found
...@@ -18,6 +18,7 @@ import ioctl_opt ...@@ -18,6 +18,7 @@ import ioctl_opt
import fcntl import fcntl
import ctypes import ctypes
import struct import struct
import logging
from config import initialize_config from config import initialize_config
from keycode import KEYCODE from keycode import KEYCODE
...@@ -144,11 +145,11 @@ def process_request(output_queue, config=None): ...@@ -144,11 +145,11 @@ def process_request(output_queue, config=None):
success = send_request(verified_id, config) success = send_request(verified_id, config)
if success: if success:
if not config["client"]["silent"]: if not config["client"]["silent"]:
print("Success") logging.info("Server Response: Success")
dispatch_led("success", config) dispatch_led("success", config)
else: else:
if not config["client"]["silent"]: if not config["client"]["silent"]:
print("Failed") logging.info("Server Response: Failed")
dispatch_led("failure", config) dispatch_led("failure", config)
...@@ -163,7 +164,7 @@ def send_request(verified_id, config) -> bool: ...@@ -163,7 +164,7 @@ def send_request(verified_id, config) -> bool:
target_address = 'http://{}:{}/'.format(config["server"]["address"], config["server"]["port"]) target_address = 'http://{}:{}/'.format(config["server"]["address"], config["server"]["port"])
if not config["client"]["silent"]: if not config["client"]["silent"]:
print("Posting {} to {}".format(verified_id, target_address)) logging.info("Posting {} to {}".format(verified_id, target_address))
payload = { payload = {
"location" : config["client"]["location"], "location" : config["client"]["location"],
...@@ -175,14 +176,14 @@ def send_request(verified_id, config) -> bool: ...@@ -175,14 +176,14 @@ def send_request(verified_id, config) -> bool:
try: try:
r = requests.post(target_address, json=payload, timeout=config["server"]["timeout"], verify=config["server"]["verify_cert"]) r = requests.post(target_address, json=payload, timeout=config["server"]["timeout"], verify=config["server"]["verify_cert"])
except Exception as e: except Exception as e:
print(e, file=sys.stderr) logging.error(e)
return False return False
return r.ok return r.ok
else: else:
# Always return true on dry run # Always return true on dry run
if not config["client"]["silent"]: if not config["client"]["silent"]:
print("Dryrun: Would post request to {}".format(target_address)) logging.info("Dryrun: Would post request to {}".format(target_address))
print("Dryrun: Payload: {}".format(str(payload))) logging.info("Dryrun: Payload: {}".format(str(payload)))
return True return True
...@@ -217,22 +218,22 @@ def open_cardreader(config) -> '_io.BufferedReader': ...@@ -217,22 +218,22 @@ def open_cardreader(config) -> '_io.BufferedReader':
# If no device found, exit # If no device found, exit
if len(devices) == 0: if len(devices) == 0:
print("Error: No Cardreader connected? Found no device with vendor ID {} and model ID {}. Exiting.".format(config["reader"]["vendor_id"], config["reader"]["model_id"]), file=sys.stderr) logging.criticial("Error: No Cardreader connected? Found no device with vendor ID {} and model ID {}. Exiting.".format(config["reader"]["vendor_id"], config["reader"]["model_id"]))
exit(0) exit(0)
# Select the first device that matches the specs # Select the first device that matches the specs
device = devices[0] device = devices[0]
if not config["client"]["silent"]: if not config["client"]["silent"]:
print("Using cardreader device: {}".format(device)) logging.info("Using cardreader device: {}".format(device))
try: try:
fd = open(device.device_node, 'rb') fd = open(device.device_node, 'rb')
except FileNotFoundError: except FileNotFoundError:
print("No such device, is it connected?", file=sys.stderr) logging.criticial("No such device, is it connected?")
exit(0) exit(0)
except PermissionError: except PermissionError:
print("Insufficent permission to read, run me as root!", file=sys.stderr) logging.criticial("Insufficent permission to read, run me as root!")
exit(0) exit(0)
# from input.h: # from input.h:
...@@ -245,7 +246,7 @@ def open_cardreader(config) -> '_io.BufferedReader': ...@@ -245,7 +246,7 @@ def open_cardreader(config) -> '_io.BufferedReader':
# Grab exclusive Access for fd # Grab exclusive Access for fd
if not config["client"]["silent"]: if not config["client"]["silent"]:
print("Grabbing device {} for exclusive access".format(name.value.decode('UTF-8'))) logging.info("Grabbing device {} for exclusive access".format(name.value.decode('UTF-8')))
fcntl.ioctl(fd, EVIOCGRAB(1), True) fcntl.ioctl(fd, EVIOCGRAB(1), True)
# Return file descriptor # Return file descriptor
...@@ -268,7 +269,7 @@ def read_key_input(input_queue, config): ...@@ -268,7 +269,7 @@ def read_key_input(input_queue, config):
e_val = "" # keydown = 1, keyup = 0 e_val = "" # keydown = 1, keyup = 0
if not config["client"]["silent"]: if not config["client"]["silent"]:
print("Listening for Input...") logging.info("Listening for Input...")
# Buffer to store incoming keys till ENTER (keycode 28) is received # Buffer to store incoming keys till ENTER (keycode 28) is received
keybuffer = [] keybuffer = []
...@@ -292,7 +293,7 @@ def read_key_input(input_queue, config): ...@@ -292,7 +293,7 @@ def read_key_input(input_queue, config):
key = KEYCODE[str(e_code)] key = KEYCODE[str(e_code)]
keybuffer.append(key) keybuffer.append(key)
else: else:
print("Received invalid Keycode: {}".format(e_code), file=sys.stderr) logging.warning("Received invalid Keycode: {}".format(e_code))
else: else:
# When enter is received put the joined string to the imput # When enter is received put the joined string to the imput
# buffer where it will be processed by the requests thread # buffer where it will be processed by the requests thread
...@@ -301,11 +302,13 @@ def read_key_input(input_queue, config): ...@@ -301,11 +302,13 @@ def read_key_input(input_queue, config):
keybuffer = [] keybuffer = []
except (KeyboardInterrupt, SystemExit, OSError) as e: except (KeyboardInterrupt, SystemExit, OSError) as e:
cardreader.close() cardreader.close()
print("Exiting because of {}".format(e), file=sys.stderr) logging.critical("Exiting because of {}".format(e))
exit(0) exit(0)
def main(): def main():
logging.info('Starting main() in {}'.format(APPLICATION_NAME))
# Initialize the configuration (create a default one if needed) # Initialize the configuration (create a default one if needed)
config = initialize_config(APPLICATION_NAME, DEFAULT_CONFIG) config = initialize_config(APPLICATION_NAME, DEFAULT_CONFIG)
...@@ -335,7 +338,7 @@ def main(): ...@@ -335,7 +338,7 @@ def main():
output_queue.put(verified_id) output_queue.put(verified_id)
else: else:
if not config["client"]["silent"]: if not config["client"]["silent"]:
print("Didn't register as a valid ID: {}".format(potential_id[:1024]), file=sys.stderr) logging.warning("Didn't register as a valid ID: {}".format(potential_id[:1024]))
dispatch_led("failure", config) dispatch_led("failure", config)
......
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
#-*- coding: utf-8 -*- #-*- coding: utf-8 -*-
import os, sys, ast, getpass import os, sys, ast, getpass
import logging
import toml import toml
from pathlib import Path from pathlib import Path
...@@ -67,28 +68,28 @@ def initialize_config(application_name: str, default_config: str) -> dict: ...@@ -67,28 +68,28 @@ def initialize_config(application_name: str, default_config: str) -> dict:
if not Path.is_dir(Path(config_dir)): if not Path.is_dir(Path(config_dir)):
try: try:
Path(config_dir).mkdir(parents=True, exist_ok=True) Path(config_dir).mkdir(parents=True, exist_ok=True)
print("Config directory didn't exist, created directory: {}".format(config_dir)) logging.info("Config directory didn't exist, created directory: {}".format(config_dir))
except PermissionError as e: except PermissionError as e:
print("Error: Not sufficient permissions to create config directory at {} (Running {} as user {})".format(config_dir, application_name, getpass.getuser()), file=sys.stderr) logging.error("Error: Not sufficient permissions to create config directory at {} (Running {} as user {})".format(config_dir, application_name, getpass.getuser()))
print("Consider creating {} manually with write permissions for {}. After initial write of default config.toml on the first run {} won't write that file ever again".format(config_dir, getpass.getuser(), application_name), file=sys.stderr) logging.error("Consider creating {} manually with write permissions for {}. After initial write of default config.toml on the first run {} won't write that file ever again".format(config_dir, getpass.getuser(), application_name), file=sys.stderr)
exit(1) exit(1)
# Create a default config if it does exist # Create a default config if it does exist
if not Path.is_file(Path(config_path)): if not Path.is_file(Path(config_path)):
try: try:
write_config(config_path, default_strconfig) write_config(config_path, default_strconfig)
print("Created new default config.toml at:\n{}".format(config_path)) logging.info("Created new default config.toml at:\n{}".format(config_path))
config = read_config(config_path) config = read_config(config_path)
except PermissionError as e: except PermissionError as e:
print("Error: Not sufficient permissions to write default config.toml into directory {} (as user {})".format(config_dir, getpass.getuser()), file=sys.stderr) logging.error("Error: Not sufficient permissions to write default config.toml into directory {} (as user {})".format(config_dir, getpass.getuser()))
print("Consider changing permissions on {} manually so writing is allowed for user {}. After initial write of default config.toml on the first run {} won't write that file ever again. so you can make it read only for {} after that".format(config_dir, getpass.getuser(), application_name, getpass.getuser()), file=sys.stderr) logging.error("Consider changing permissions on {} manually so writing is allowed for user {}. After initial write of default config.toml on the first run {} won't write that file ever again. so you can make it read only for {} after that".format(config_dir, getpass.getuser(), application_name, getpass.getuser()))
exit(1) exit(1)
else: else:
config = read_config(config_path) config = read_config(config_path)
if config_has_missing_keys(config, default_config, default_strconfig): if config_has_missing_keys(config, default_config, default_strconfig):
print("Error: there are keys missing in the config. Delete to let {} create a new one, or add the missing keys manually".format(application_name), file=sys.stderr) logging.error("Error: there are keys missing in the config. Delete to let {} create a new one, or add the missing keys manually".format(application_name))
exit(1) exit(1)
print("Read config from: {}".format(config_path)) logging.info("Read config from: {}".format(config_path))
return config return config
...@@ -101,17 +102,17 @@ def config_has_missing_keys(config, default_config, default_strconfig) -> bool: ...@@ -101,17 +102,17 @@ def config_has_missing_keys(config, default_config, default_strconfig) -> bool:
missing = [] missing = []
for default_key in default_config.keys(): for default_key in default_config.keys():
if not default_key in config.keys(): if not default_key in config.keys():
print("Your config.toml is missing the [{}] section!".format(default_key)) logging.error("Your config.toml is missing the [{}] section!".format(default_key))
missing.append(True) missing.append(True)
else: else:
for sub_key in default_config[default_key].keys(): for sub_key in default_config[default_key].keys():
if not sub_key in config[default_key].keys(): if not sub_key in config[default_key].keys():
print("Your config.toml is missing the key \"{}\" in the [{}] section!".format(sub_key, default_key)) logging.error("Your config.toml is missing the key \"{}\" in the [{}] section!".format(sub_key, default_key))
missing.append(True) missing.append(True)
if any(missing): if any(missing):
print("The default config looks like this:") logging.error("The default config looks like this:")
print(default_strconfig) logging.error(default_strconfig)
return True return True
else: else:
return False return False
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment