diff options
author | pks <pks@pks.rocks> | 2021-05-10 19:34:52 +0200 |
---|---|---|
committer | pks <pks@pks.rocks> | 2021-05-10 19:34:52 +0200 |
commit | 4e89786a4436000dde7d82258210cd02268f86e0 (patch) | |
tree | e6044d4f8eadbf4549d9719f6fb06d602a5f8656 | |
parent | 958032b3193d684c78c3858b9e1a9b806244e1f0 (diff) |
refactor
-rw-r--r-- | config/config.yaml | 9 | ||||
-rwxr-xr-x | weather-logger-receiver | 88 |
2 files changed, 66 insertions, 31 deletions
diff --git a/config/config.yaml b/config/config.yaml index 332f6b9..6dc26a4 100644 --- a/config/config.yaml +++ b/config/config.yaml @@ -1,5 +1,8 @@ -log_file_path: /var/log/weather_logger/receiver.log -pid_file_path: /run/weather_logger/receiver.log +device_path: "/dev/ttyUSB0" +database_path: "/usr/local/share/weather_logger/weather.db" +log_file_path: "/var/log/weather_logger/receiver.log" +pid_file_path: "/run/weather_logger/pid" + locations: Berlin: @@ -17,4 +20,4 @@ locations: handle: "outside" type: "THGR810, THGN800" -active-location: Berlin +active_location: Berlin diff --git a/weather-logger-receiver b/weather-logger-receiver index 389a9de..fd0c8e4 100755 --- a/weather-logger-receiver +++ b/weather-logger-receiver @@ -11,8 +11,8 @@ import yaml from RFXtrx import PySerialTransport -def setup_database(path="weather.db"): - db_connection = sqlite3.connect(path) +def setup_database(database_path, logger): + db_connection = sqlite3.connect(database_path) db_cursor = db_connection.cursor() try: db_cursor.execute("CREATE TABLE weather( \ @@ -22,26 +22,19 @@ def setup_database(path="weather.db"): temperature FLOAT, \ humidity FLOAT);") except sqlite3.OperationalError: + logger.info("Not re-creating 'weather' table") pass return db_connection -def setup_serial(device="/dev/ttyUSB0"): - serial_connection = PySerialTransport(device) +def setup_serial(device_path): + serial_connection = PySerialTransport(device_path) serial_connection.reset() return serial_connection -def load_known_devices(location, path="known-devices.yaml"): - known_devices = None - with open(path, "r") as f: - known_devices = yaml.safe_load(f.read()) - - return known_devices[location] - - def add_data_to_db(data, handle, db_connection): db_cursor = db_connection.cursor() db_cursor.execute(f"INSERT INTO weather \ @@ -53,24 +46,25 @@ def add_data_to_db(data, handle, db_connection): db_connection.commit() -def loop(serial_connection, db_connection, logger): +def loop(config, serial_connection, db_connection, logger): + known_devices = config["known_devices"][config["active_location"]] while True: logger.info("(Re-)Starting receiver loop") data = serial_connection.receive_blocking() if data is None: - logger.info("Received no data") + logger.info("Didn't receive data") continue logger.info(data) try: if data.device.id_string not in known_devices: - logger.info(f"Unknown device with id {device_id} and type {device_type}, ignoring") + logger.info(f"Unknown device with id '{device_id}' and type '{device_type}', ignoring") continue except: - logger.info("Device ID not found, likely no SensorEvent, ignoring") + logger.info("Device ID not found, likely not a 'SensorEvent', ignoring") continue handle = known_devices[data.device.id_string]["handle"] @@ -78,35 +72,73 @@ def loop(serial_connection, db_connection, logger): add_data_to_db(data, handle, db_connection) +def write_pid_file(pid_file_path, logger): + if os.path.exists(pid_file_path): + with open(pid_file_path, "r") as pid_file: + pid = pid_file.read() + logger.error(f"Possibly already running with PID {pid}, exiting") + sys.exit(1) + with open(path, "w") as pid_file: + pid_file.write(str(os.getpid())) + + +def load_config(config_file_path, logger): + with open(config_file_path, "r") as f: + config = yaml.safe_load(f.read()) + logger.info(f"Loaded configuration from '{config_file_path}'") + + return config + + if __name__ == "__main__": - logger = logging.getLogger("weather-logger-receiver") + # logger setup logging.basicConfig(format='%(asctime)-2s %(levelname)-8s %(message)s', datefmt='%Y-%m-%dT%H:%M:%S', level=logging.INFO) + logger = logging.getLogger("weather-logger-receiver") - assert len(sys.argv) == 2 - location = sys.argv[1] - known_devices = load_known_devices(location=location) - logger.info(f"Loaded known devices for location {location}") + # load configuration + if len(sys.argv) != 2: + logger.error("Missing path to configuration file, exiting") + sys.exit(1) + config_file_path = sys.argv[1] + config = load_config(config_file_path, logger) - db_connection = setup_database() - logger.info("Set up database") + # get known devices + active_location = config["active_location"] + known_devices = config["locations"][active_location] + logger.info(f"Loaded known devices for location '{active_location}'") - serial_connection = setup_serial() - logger.info("Set up serial connection") + # write pid file + write_pid_file(config["pid_file_path"], logger) + logger.info("Wrote PID file to '{config{'pid_file_path']}'") + # database setup + db_connection = setup_database(config["database_path"], logger) + logger.info("Set up database '{config['database_path']}'") + + # serial connection setup + serial_connection = setup_serial(config["device_path"]) + logger.info("Set up serial connection to '{config['device_path']}'") + + # handle shutdown def shutdown(*args): logger.info("Shutting down") serial_connection.close() db_connection.close() + try: + os.remove(config["pid_file_path"]) + except FileNotFoundError: + pass sys.exit(0) signal.signal(signal.SIGINT, shutdown) signal.signal(signal.SIGTERM, shutdown) + # start main loop try: - loop(serial_connection, db_connection, logger) + loop(known_devices, serial_connection, db_connection, logger) except Exception as e: - logger.error(f"Exception: {e}") + logger.error(f"Exception: '{e}'") finally: - shutdown(serial_connection, db_connection, logger) + shutdown(config, serial_connection, db_connection, logger) |