Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

VU Server Filesystem class #29

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 3 additions & 8 deletions database.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,14 @@
import sqlite3
import random
from dials.base_logger import logger
from vu_filesystem import VU_FileSystem

class DialsDB:
connection = None
database_changes = 0

def __init__(self, database_file='vudials.db', init_if_missing=False):
# database_path = os.path.join(os.path.expanduser('~'), 'KaranovicResearch', 'vudials')
database_path = os.path.join(os.path.dirname(__file__))

if not os.path.exists(database_path):
os.makedirs(database_path)

self.database_file = os.path.join(database_path, database_file)
def __init__(self, init_if_missing=False):
self.database_file = VU_FileSystem.get_database_file_path()
logger.info(f"VU1 Database file: {self.database_file}")

if not os.path.exists(self.database_file) and not init_if_missing:
Expand Down
13 changes: 2 additions & 11 deletions dials/base_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import logging
from logging.handlers import RotatingFileHandler
from functools import partial, partialmethod
from vu_filesystem import VU_FileSystem

def colorize(data, color):
colors = {'none': "0",
Expand Down Expand Up @@ -72,17 +73,7 @@ def set_logger_level(level='info'):
'''
# Basic logger setup
log_formatter = logging.Formatter('%(asctime)s %(levelname)s %(funcName)s(%(lineno)d) %(message)s')
# Linux
if sys.platform in ["linux", "linux2"]:
logFile = f'/home/{getpass.getuser()}/KaranovicResearch/vudials/server.log'

# MacOS
elif sys.platform == "darwin":
logFile = f'~/Library/Logs/KaranovicResearch/vudials/server.log'

# Windows
elif sys.platform == "win32":
logFile = os.path.join(os.path.expanduser(os.getenv('USERPROFILE')), 'KaranovicResearch', 'vudials', 'server.log')
logFile = VU_FileSystem.get_log_file_path();

os.makedirs(os.path.dirname(logFile), exist_ok=True)
log_file_handler = RotatingFileHandler(logFile, mode='a', maxBytes=1*1024*1024, backupCount=2, encoding=None, delay=0)
Expand Down
26 changes: 11 additions & 15 deletions server.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,22 @@
import time
import re
from mimetypes import guess_type
from dials.base_logger import logger, set_logger_level
from tornado.web import Application, RequestHandler, Finish, StaticFileHandler
from tornado.ioloop import IOLoop, PeriodicCallback
from dials.base_logger import logger, set_logger_level
from dial_driver import DialSerialDriver
from server_config import ServerConfig
from server_dial_handler import ServerDialHandler
from vu_notifications import show_error_msg, show_info_msg
from vu_filesystem import VU_FileSystem

BASEDIR_NAME = os.path.dirname(__file__)
BASEDIR_PATH = os.path.abspath(BASEDIR_NAME)
WEB_ROOT = os.path.join(BASEDIR_PATH, 'www')

def pid_lock(service_name, create=True):
file_name = "service.{}.pid.lock".format(service_name)
pid_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), file_name)
pid_file = os.path.join(VU_FileSystem.get_pid_lock_file_path(), file_name)

if create:
pid = os.getpid()
Expand All @@ -34,7 +35,7 @@ class BaseHandler(RequestHandler):
def initialize(self, handler, config):
self.handler = handler # pylint: disable=attribute-defined-outside-init
self.config = config # pylint: disable=attribute-defined-outside-init
self.upload_path = os.path.join(os.path.dirname(__file__), 'upload') # pylint: disable=attribute-defined-outside-init
self.upload_path = VU_FileSystem.get_upload_directory_path() # pylint: disable=attribute-defined-outside-init

def set_default_headers(self):
self.set_header("Access-Control-Allow-Origin", "*")
Expand Down Expand Up @@ -186,7 +187,6 @@ def post(self, dial_uid):
return self.send_response(status='ok', message='Image CRC already maches existing one. Skipping update.')

def handle_image_upload(self, dial_uid):
self.make_upload_folder()
image_data = self.request.files.get('imgfile', None)
if image_data is None:
logger.error("imgfile field missing from request.")
Expand All @@ -205,22 +205,18 @@ def different_image_uploaded(self, old, new):
return True
return False

def make_upload_folder(self):
if not os.path.exists(self.upload_path):
os.makedirs(self.upload_path)

class Dial_Get_Image(BaseHandler):
def get(self, gaugeUID):
self.set_header("Content-Type", "image/png")

logger.debug("Request: GET_IMAGE")
dial_image = os.path.join(os.path.dirname(__file__), 'upload', f'img_{gaugeUID}')
dial_image = os.path.join(VU_FileSystem.get_upload_directory_path(), f'img_{gaugeUID}')

if os.path.exists(dial_image):
filepath = dial_image
logger.debug(f"Serving image from {filepath}")
else:
filepath = os.path.join(os.path.dirname(__file__), 'upload', 'img_blank')
filepath = os.path.join(VU_FileSystem.get_upload_directory_path(), 'img_blank')
logger.debug(f"Serving DEFAULT image from {filepath}")

try:
Expand All @@ -236,7 +232,7 @@ class Dial_Get_Image_CRC(BaseHandler):
def get(self, gaugeUID):
logger.debug("Request: GET_IMAGE_CRC")

img_file = os.path.join(os.path.dirname(__file__), 'upload', f'img_{gaugeUID}')
img_file = os.path.join(VU_FileSystem.get_upload_directory_path(), f'img_{gaugeUID}')

crc = self.get_file_crc(img_file)
return self.send_response(status='ok', data=crc)
Expand Down Expand Up @@ -392,7 +388,6 @@ def get(self, gaugeUID):
if not self.is_valid_api_key():
return self.send_response(status='fail', message='Unauthorized', status_code=401)

# TODO: Implement in dial handler
return self.send_response(status='ok', message="not supported yet")

# -- Keys --
Expand Down Expand Up @@ -525,7 +520,7 @@ def __init__(self):
signal.signal(signal.SIGINT, self.signal_handler)

logger.info("Loading server config...")
self.config = ServerConfig('config.yaml')
self.config = ServerConfig()

# If config contains COM port, use it. Otherwise try to find it
hardware_config = self.config.get_hardware_config()
Expand Down Expand Up @@ -638,7 +633,7 @@ def run_forever(self):
show_error_msg(title='Key missing from config', message='Entry "master_key" is missing from the "config.yaml"!')
logger.error("Master Key is MISSING from config.yaml")
logger.error("Check your 'config.yaml' or add it manually under 'server' section.")
sys.exit(0)
sys.exit(-1)

pc = PeriodicCallback(self.dial_handler.periodic_dial_update, dial_update_period)
pc.start()
Expand All @@ -656,7 +651,8 @@ def main(cmd_args=None):
except Exception:
logger.exception("VU Dials API service crashed during setup.")
show_error_msg("Crashed", "VU Server has crashed unexpectedly!\r\nPlease check log files for more information.")
os._exit(0)
sys.exit(-1)
sys.exit(0)

if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Karanovic Research - VU Dials API service')
Expand Down
5 changes: 3 additions & 2 deletions server_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
# import yaml
from dials.base_logger import logger
from vu_notifications import show_error_msg, show_warning_msg
from vu_filesystem import VU_FileSystem
import database as db

class ServerConfig:
Expand All @@ -16,8 +17,8 @@ class ServerConfig:
api_keys = {}
database = None

def __init__(self, config_file='config.yaml'):
self.config_path = os.path.join(os.path.dirname(__file__), config_file)
def __init__(self):
self.config_path = VU_FileSystem.get_config_file_path()
logger.info(f"VU1 config yaml file: {self.config_path}")
self.database = db.DialsDB(init_if_missing=True)
self._load_config() # Load configuration from .yaml file
Expand Down
Loading
Loading