Beispiel #1
0
    def __init__(self, **kwargs):
        super(PlasmaProcesses, self).__init__()
        # determine what database to connect to.  Support types are:
        
        # stop data load processing if in designer
        if IN_DESIGNER:
            return
        
        # open DB and expose the DB type and if relevant the
        # connection string to the environment.  This makes for a simple
        # measn to unform the tool DB prog and the filter prog.
        if kwargs["db_type"] != "sqlite":
            self._engine = create_engine(kwargs["connect_string"], echo=False)
        else:
            self._persistence_file = normalizePath(path='plasma_table.db',
                                              base=os.getenv('CONFIG_DIR', '~/'))
            self._engine = create_engine('sqlite:///'+self._persistence_file, echo=False)
            os.environ['PLASMA_DB'] = 'sqlite'


        # create the database for anything not already in place
        BASE.metadata.create_all(self._engine)
        # create and hold session for use of transactions
        self._session_maker = sessionmaker(bind=self._engine)
        self._session = self._session_maker()
Beispiel #2
0
    def __init__(self, persistence_file='.settings.json'):
        super(Settings, self).__init__()

        self.channels = SETTINGS
        self.settings = {}

        self.persistence_file = normalizePath(path=persistence_file,
                                              base=os.getenv(
                                                  'CONFIG_DIR', '~/'))
Beispiel #3
0
    def __init__(self, persistence_file='.settings.json'):
        super(Settings, self).__init__()

        self.channels = SETTINGS
        self.settings = {}

        # load settings defined in YAML file
        for setting_name, kwargs in CONFIG['settings'].items():
            addSetting(setting_name, **kwargs)

        self.persistence_file = normalizePath(path=persistence_file,
                                              base=os.getenv('CONFIG_DIR', '~/'))
Beispiel #4
0
    def __init__(self, enabled=True, mode="native", persistent=True, persistent_file='.qtpyvcp_messages.json'):
        super(Notifications, self).__init__()

        self.enabled = enabled
        self.mode = mode

        self.error_channel = linuxcnc.error_channel()

        self.messages = []
        self.notification_dispatcher = None

        self.persistant = persistent
        self.persistent_file = normalizePath(path=persistent_file,
                                             base=os.getenv('CONFIG_DIR', '~/'))
Beispiel #5
0
    def __init__(self,
                 persistent=True,
                 persistent_file='.qtpyvcp_messages.json'):
        super(Notifications, self).__init__()

        self.error_channel = linuxcnc.error_channel()

        self.messages = []

        self.persistant = persistent
        self.persistent_file = normalizePath(path=persistent_file,
                                             base=os.getenv(
                                                 'CONFIG_DIR', '~/'))

        self.timer = QTimer()
        self.timer.timeout.connect(self.onTimeout)

        self._count = 0
Beispiel #6
0
    def __init__(self, serialization_method='pickle', persistence_file=None):
        super(PersistentDataManager, self).__init__()

        self.serialization_method = serialization_method

        if not persistence_file:
            persistence_file = '.vcp_persistent_data.' + serialization_method

        if serialization_method == 'json':
            import json
            self.serializer = json
        else:
            import pickle
            self.serializer = pickle

        self.data = {}
        self.persistence_file = normalizePath(path=persistence_file,
                                              base=os.getenv('CONFIG_DIR', '~/'))
Beispiel #7
0
def initBaseLogger(name, log_file=None, log_level="DEBUG"):

    global BASE_LOGGER_NAME
    if BASE_LOGGER_NAME is not None:
        return getLogger(name)

    BASE_LOGGER_NAME = name

    log_file = normalizePath(log_file, CONFIG_DIR
                             or os.getenv('HOME')) or DEFAULT_LOG_FILE

    # Clear the previous sessions log file
    with open(log_file, 'w') as fh:
        pass

    # Create base logger
    base_log = logging.getLogger(BASE_LOGGER_NAME)

    try:
        base_log.setLevel(logLevelFromName(log_level))
    except KeyError:
        raise ValueError("Log level '{}' is not valid.".format(log_level))

    # Add console handler
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    cf = ColoredFormatter(TERM_FORMAT)
    ch.setFormatter(cf)
    base_log.addHandler(ch)

    # Add file handler
    fh = logging.FileHandler(log_file)
    fh.setLevel(logging.DEBUG)
    ff = logging.Formatter(FILE_FORMAT)
    fh.setFormatter(ff)
    base_log.addHandler(fh)

    # Get logger for logger
    log = getLogger(__name__)
    base_log.info('Logging to yellow<{}>'.format(log_file))

    return base_log
Beispiel #8
0
    def __init__(self, pref_file='~/.qtpyvcp.pref'):
        ConfigParser.RawConfigParser.__init__(self)

        self.pref_file = normalizePath(pref_file, CONFIG_DIR) or '/dev/null'

        self.getters = {
            bool: self.getBool,
            float: self.getFloat,
            int: self.getInt,
            list: self.getList,
            dict: self.getDict,
            str: self.getStr,
        }

        self.optionxform = str  # Needed to maintain options case

        if not os.path.isfile(self.pref_file):
            log.info("No preference file exists, creating: {}".format(
                self.pref_file))

        self.read(self.pref_file)
Beispiel #9
0
    def __init__(self,
                 persistent=True,
                 persistent_file='.qtpyvcp_messages.json'):
        super(Notifications, self).__init__()

        self.error_channel = linuxcnc.error_channel()

        self.messages = []

        self.desktop_notifier = Notification("Demo")
        self.desktop_notifier.setUrgency(Urgency.NORMAL)
        self.desktop_notifier.setCategory("device")

        self.persistant = persistent
        self.persistent_file = normalizePath(path=persistent_file,
                                             base=os.getenv(
                                                 'CONFIG_DIR', '~/'))

        self.timer = QTimer()
        self.timer.timeout.connect(self.onTimeout)

        self._count = 0
Beispiel #10
0
def parse_opts(doc=__doc__,
               vcp_name='NotSpecified',
               vcp_cmd='notspecified',
               vcp_version=None):
    # LinuxCNC passes the INI file as `-ini=inifile` which docopt sees as a
    # short argument which does not support an equals sign, so we loop thru
    # and add another dash to the ini argument if needed.
    for index, item in enumerate(sys.argv):
        if item.startswith('-ini'):
            sys.argv[index] = '-' + item
            break

    version_str = 'QtPyVCP {}'.format(QTPYVCP_VERSION)
    if vcp_version is not None:
        version_str += ', {} v{}'.format(vcp_name, vcp_version)

    doc = doc.format(vcp_name=vcp_name, vcp_cmd=vcp_cmd)

    raw_args = docopt(doc, version=version_str)

    def convType(val):
        if isinstance(val, basestring):
            if val.lower() in ['true', 'on', 'yes', 'false', 'off', 'no']:
                return val.lower() in ['true', 'on', 'yes']

            try:
                return int(val)
            except ValueError:
                pass

            try:
                return float(val)
            except ValueError:
                pass

        return val

    # convert raw argument dict keys to valid python attribute names
    opts = DotDict({
        arg.strip('-<>').replace('-', '_'): convType(value)
        for arg, value in raw_args.items()
    })

    # read options from INI file and merge with cmd line options
    ini_file = ini(
        normalizePath(opts.ini, os.path.expanduser('~/linuxcnc/configs')))
    for k, v in opts.iteritems():
        ini_val = ini_file.find('DISPLAY', k.upper().replace('-', '_'))
        if ini_val is None:
            continue

        # convert str values to bool
        if type(v) == bool:
            # TODO: Find a way to prefer cmd line values over INI values
            ini_val = ini_val.lower() in ['true', 'on', 'yes', '1']

        # if its a non bool value and it was specified on the cmd line
        # then prefer the cmd line value
        elif v is not None:
            continue

        opts[k] = convType(ini_val)

    # Check if LinuxCNC is running
    if not os.path.isfile('/tmp/linuxcnc.lock'):
        # LinuxCNC is not running.
        # TODO: maybe launch LinuxCNC using subprocess?
        print 'LinuxCNC must be running to launch a VCP'
        sys.exit()

    # setup the environment variables
    ini_file = os.environ.get('INI_FILE_NAME') or opts.ini
    if ini_file is None:
        print 'LinuxCNC is running, but you must specify the INI file'
        sys.exit()

    if not os.getenv('INI_FILE_NAME'):
        base_path = os.path.expanduser('~/linuxcnc/configs')
        ini_file = os.path.realpath(normalizePath(ini_file, base_path))
        if not os.path.isfile(ini_file):
            print 'Specified INI file does not exist: {}'.format(ini_file)
            sys.exit()
        os.environ['INI_FILE_NAME'] = ini_file
        os.environ['CONFIG_DIR'] = os.path.dirname(ini_file)

    if opts.qt_api:
        os.environ['QT_API'] = opts.qt_api

    if opts.config_file is not None:
        # cmd line config file should be relative to INI file
        config_dir = os.getenv('CONFIG_DIR', '')
        config_file_path = normalizePath(opts.config_file, config_dir)
        if not os.path.isfile(config_file_path):
            print 'Specified YAML file does not exist: {}'.format(
                config_file_path)
            sys.exit()
        opts.config_file = config_file_path

    # show the chooser if the --chooser flag was specified
    if opts.chooser or not opts.get('vcp', True):
        from qtpyvcp.vcp_chooser import VCPChooser
        from qtpy.QtWidgets import QApplication, qApp
        app = QApplication([])
        result = VCPChooser(opts).exec_()
        if result == VCPChooser.Rejected:
            sys.exit()

        # destroy the evidence
        qApp.deleteLater()
        del app

    # normalize log file path
    log_file = normalizePath(opts.log_file,
                             os.getenv('CONFIG_DIR') or os.getenv('HOME'))

    if log_file is None or os.path.isdir(log_file):
        log_file = os.path.expanduser('~/qtpyvcp.log')

    opts.log_file = log_file

    # init the logger
    from qtpyvcp.utilities import logger
    LOG = logger.initBaseLogger('qtpyvcp',
                                log_file=opts.log_file,
                                log_level=opts.log_level or "INFO")

    LOG.info("QtPyVCP Version: %s", QTPYVCP_VERSION)

    if LOG.getEffectiveLevel() == logger.LOG_LEVEL_MAPPING['DEBUG']:
        import qtpy
        LOG.debug("Qt Version: %s", qtpy.QT_VERSION)
        LOG.debug("Qt API: %s", qtpy.QT_API)
        LOG.debug("QtPy Version: %s", qtpy.__version__)

        LOG.debug("Command line options:\n%s",
                  json.dumps(opts, sort_keys=True, indent=4))

    return opts
Beispiel #11
0
def apply_opts(opts):

    # read options from INI file and merge with cmd line options
    ini_file = normalizePath(opts.ini, os.path.expanduser('~/linuxcnc/configs'))
    ini_obj = ini(ini_file)
    for k, v in opts.iteritems():
        ini_val = ini_obj.find('DISPLAY', k.upper().replace('-', '_'))
        if ini_val is None:
            continue

        # convert str values to bool
        if type(v) == bool:
            # TODO: Find a way to prefer cmd line values over INI values
            ini_val = ini_val.lower() in ['true', 'on', 'yes', '1']

        # if its a non bool value and it was specified on the cmd line
        # then prefer the cmd line value
        elif v is not None:
            continue

        # If a VCP is specified in the INI as a .ui or .yaml file the path
        # should be relative to the config dir rather then the $PWD.
        if k.lower() == 'vcp' and ini_val.lower().split('.')[-1] in ['ui', 'yml', 'yaml']:
            ini_val = normalizePath(ini_val, os.path.dirname(ini_file))

        opts[k] = convType(ini_val)

    # Check if LinuxCNC is running
    if not os.path.isfile('/tmp/linuxcnc.lock'):
        # LinuxCNC is not running.
        # TODO: maybe launch LinuxCNC using subprocess?
        print 'LinuxCNC must be running to launch a VCP'
        sys.exit()

    # setup the environment variables
    ini_file = os.environ.get('INI_FILE_NAME') or opts.ini
    if ini_file is None:
        print 'LinuxCNC is running, but you must specify the INI file'
        sys.exit()

    if not os.getenv('INI_FILE_NAME'):
        base_path = os.path.expanduser('~/linuxcnc/configs')
        ini_file = os.path.realpath(normalizePath(ini_file, base_path))
        if not os.path.isfile(ini_file):
            print 'Specified INI file does not exist: {}'.format(ini_file)
            sys.exit()
        os.environ['INI_FILE_NAME'] = ini_file
        os.environ['CONFIG_DIR'] = os.path.dirname(ini_file)

    if opts.qt_api:
        os.environ['QT_API'] = opts.qt_api

    if opts.config_file is not None:
        # cmd line config file should be relative to INI file
        config_dir = os.getenv('CONFIG_DIR', '')
        config_file_path = normalizePath(opts.config_file, config_dir)
        if not os.path.isfile(config_file_path):
            print 'Specified YAML file does not exist: {}'.format(config_file_path)
            sys.exit()
        opts.config_file = config_file_path

    # show the chooser if the --chooser flag was specified
    if opts.chooser or not opts.get('vcp', True):
        from qtpyvcp.vcp_chooser import VCPChooser
        from qtpy.QtWidgets import QApplication, qApp
        app = QApplication([])
        result = VCPChooser(opts).exec_()
        if result == VCPChooser.Rejected:
            sys.exit()

        # destroy the evidence
        qApp.deleteLater()
        del app

    # normalize log file path
    log_file = normalizePath(opts.log_file,
                             os.getenv('CONFIG_DIR') or
                             os.getenv('HOME'))

    if log_file is None or os.path.isdir(log_file):
        log_file = os.path.expanduser('~/qtpyvcp.log')

    opts.log_file = log_file

    # init the logger
    from qtpyvcp.utilities import logger
    LOG = logger.initBaseLogger('qtpyvcp',
                                log_file=opts.log_file,
                                log_level=opts.log_level or "INFO")

    LOG.info("QtPyVCP Version: %s", QTPYVCP_VERSION)

    if LOG.getEffectiveLevel() == logger.logLevelFromName("DEBUG"):
        import qtpy
        LOG.debug("Qt Version: %s", qtpy.QT_VERSION)
        LOG.debug("Qt API: %s", qtpy.QT_API)
        LOG.debug("QtPy Version: %s", qtpy.__version__)


        LOG.debug("Command line options:\n%s",
                  json.dumps(opts, sort_keys=True, indent=4))

    return opts
Beispiel #12
0
import os
import sys

import linuxcnc
from tooldb import tooldb_callbacks  # functions
from tooldb import tooldb_tools  # list of tool numbers
from tooldb import tooldb_loop  # main loop

from qtpyvcp.utilities.misc import normalizePath
from qtpyvcp.plugins.plasma_processes import PlasmaProcesses
from qtpyvcp.utilities.config_loader import load_config_files

#import pydevd;pydevd.settrace()

base_ini_file = os.environ['INI_FILE_NAME']
ini_file_name = normalizePath(path=base_ini_file,
                              base=os.getenv('CONFIG_DIR', '~/'))
# ini_file_name = normalizePath(path='xyz.ini', base=os.getenv('CONFIG_DIR', '~/'))
INI_FILE = linuxcnc.ini(ini_file_name)
UNITS = INI_FILE.find('TRAJ', 'LINEAR_UNITS')
MACHINE = INI_FILE.find('PLASMAC', 'MACHINE')
PRESSURE = INI_FILE.find('PLASMAC', 'PRESSURE')

custom_config_yaml_file_name = normalizePath(path='custom_config.yml',
                                             base=os.getenv(
                                                 'CONFIG_DIR', '~/'))
cfg_dic = load_config_files(custom_config_yaml_file_name)

# we assume that things are sqlit unless we find custom_config.yml
# pointing to different type of DB
try:
    db_connect_str = cfg_dic['data_plugins']['plasmaprocesses']['kwargs'][