Пример #1
0
    def __init__(self):
        self.os_release = {}
        self.cpu_info = {}
        self.pypi_sorted_package_list = []

        self.shpypi = Shpypi.get_instance()

        self.read_cpuinfo()
        return
Пример #2
0
    def __init__(self):
        self.logger = logging.getLogger(__name__)
        self.logger = logging.getLogger('modules.admin.systemdata')
        self.logger.debug("Systemdata.__init__()")

        self.os_release = {}
        self.cpu_info = {}
        self.pypi_sorted_package_list = []

        self.shpypi = Shpypi.get_instance()

        self.read_cpuinfo()
        return
Пример #3
0
    def __init__(self, MODE, extern_conf_dir=''):
        """
        Initialization of main smarthome object
        """
        self.shng_status = {'code': 0, 'text': 'Initalizing'}
        self._logger = logging.getLogger(__name__)
        self._logger_main = logging.getLogger(__name__ + '.main')

        self.initialize_vars()
        self.initialize_dir_vars()
        self.create_directories()

        os.chdir(self._base_dir)

        self.PYTHON_VERSION = lib.utils.get_python_version()

        if os.name != 'nt':
            self.python_bin = os.environ.get('_', '')
        else:
            self.python_bin = sys.executable

        if extern_conf_dir != '':
            self._extern_conf_dir = extern_conf_dir

        # set default timezone to UTC
        self.shtime = Shtime(self)

        threading.currentThread().name = 'Main'
        self.alive = True

        import bin.shngversion
        VERSION = bin.shngversion.get_shng_version()
        self.version = VERSION
        self.connections = []

        self._etc_dir = os.path.join(self._extern_conf_dir, 'etc')
        self._items_dir = os.path.join(self._extern_conf_dir,
                                       'items' + os.path.sep)
        self._logic_dir = os.path.join(self._extern_conf_dir,
                                       'logics' + os.path.sep)
        self._scenes_dir = os.path.join(self._extern_conf_dir,
                                        'scenes' + os.path.sep)
        self._smarthome_conf_basename = os.path.join(self._etc_dir,
                                                     'smarthome')
        self._logic_conf_basename = os.path.join(self._etc_dir, 'logic')
        self._module_conf_basename = os.path.join(self._etc_dir, 'module')
        self._plugin_conf_basename = os.path.join(self._etc_dir, 'plugin')
        self._log_conf_basename = os.path.join(self._etc_dir, 'logging')

        self._pidfile = PIDFILE

        # check config files
        self.checkConfigFiles()

        if MODE == 'unittest':
            return

        #############################################################
        # Reading smarthome.yaml

        config = lib.config.parse_basename(self._smarthome_conf_basename,
                                           configtype='SmartHomeNG')
        if config != {}:
            for attr in config:
                if not isinstance(config[attr], dict):  # ignore sub items
                    vars(self)['_' + attr] = config[attr]
            del (config)  # clean up
        else:
            # no valid smarthome.yaml found
            print("No base configuration - terminating SmartHomeNG")
            print(
                "Hint: Are Language (preferably: DE_de) and character (UTF-8) set configured in operating system?"
            )
            exit(1)
        if hasattr(self, '_module_paths'):
            sys.path.extend(self._module_paths if type(self._module_paths) is
                            list else [self._module_paths])

        #############################################################
        # Setting (local) tz if set in smarthome.yaml
        if hasattr(self, '_tz'):
            self.shtime.set_tz(self._tz)
            del (self._tz)

        #############################################################
        # test if needed Python packages are installed
        # - core requirements = libs
        # self.shpypi = Shpypi(self)
        # core_reqs = shpypi.test_core_requirements(logging=False)
        # if core_reqs == 0:
        #     print("Trying to restart shng")
        #     print()
        #     exit(0)
        # elif core_reqs == -1:
        #     print("Unable to install core requirements")
        #     print()
        #     exit(1)

        #############################################################
        # setup logging
        self.init_logging(self._log_conf_basename, MODE)

        self.shng_status = {
            'code': 1,
            'text': 'Initalizing: Logging initalized'
        }

        #############################################################
        # Fork process and write pidfile
        if MODE == 'default':
            lib.daemon.daemonize(PIDFILE)
        else:
            lib.daemon.write_pidfile(os.getpid(), PIDFILE)
            print(
                "--------------------   Init SmartHomeNG {}   --------------------"
                .format(self.version))

        #############################################################
        # Write startup message to log(s)
        pid = lib.daemon.read_pidfile(PIDFILE)
        virtual_text = ''
        if lib.utils.running_virtual():
            virtual_text = ' in virtual environment'
        self._logger_main.warning(
            "--------------------   Init SmartHomeNG {}   --------------------"
            .format(self.version))
        self._logger_main.warning(
            f"Running in Python interpreter 'v{self.PYTHON_VERSION}'{virtual_text}, from directory {self._base_dir}"
        )
        self._logger_main.warning(f" - on {platform.platform()} (pid={pid})")

        default_encoding = locale.getpreferredencoding(
        )  # returns cp1252 on windows
        if not (default_encoding in ['UTF8', 'UTF-8']):
            self._logger.warning(
                "Encoding should be UTF8 but is instead {}".format(
                    default_encoding))

        if self._extern_conf_dir != BASE:
            self._logger.warning("Using config dir {}".format(
                self._extern_conf_dir))

        #############################################################
        # Initialize multi-language support
        lib.translation.initialize_translations(self._base_dir,
                                                self._default_language,
                                                self._fallback_language_order)

        #############################################################
        # Test if plugins are installed
        if not os.path.isdir(self._plugins_dir):
            self._logger.critical("Plugin folder does not exist!")
            self._logger.critical(
                "Please create folder '{}' and install plugins.".format(
                    self._plugins_dir))
            self._logger.critical("Aborting")
            exit(1)
        if not os.path.isdir(os.path.join(self._plugins_dir, 'database')):
            self._logger.critical(
                "No plugins found in folder '{}'. Please install plugins.".
                format(self._plugins_dir))
            self._logger.critical("Aborting")
            exit(1)

        #############################################################
        # test if needed Python packages for configured plugins
        # are installed
        self.shpypi = Shpypi.get_instance()
        if self.shpypi is None:
            self.shpypi = Shpypi(self)
        if hasattr(self, '_shpypi_crontab'):
            self.shpypi.set_scheduler_crontab(self._shpypi_crontab)

        base_reqs = self.shpypi.test_base_requirements(self)
        if base_reqs == 0:
            self.restart('SmartHomeNG (Python package installation)')
            exit(5)  # exit code 5 -> for systemctl to restart ShamrtHomeNG
        elif base_reqs == -1:
            self._logger.critical(
                "Python package requirements for modules are not met and unable to install base requirements"
            )
            self._logger.critical(
                "Do you have multiple Python3 Versions installed? Maybe PIP3 looks into a wrong Python environment. Try to configure pip_command in etc/smarthome.yaml"
            )
            self._logger.critical("Aborting")
            exit(1)

        plugin_reqs = self.shpypi.test_conf_plugins_requirements(
            self._plugin_conf_basename, self._plugins_dir)
        if plugin_reqs == 0:
            self.restart('SmartHomeNG (Python package installation)')
            exit(5)  # exit code 5 -> for systemctl to restart ShamrtHomeNG
        elif plugin_reqs == -1:
            self._logger.critical(
                "Python package requirements for configured plugins are not met and unable to install those requirements"
            )
            self._logger.critical(
                "Do you have multiple Python3 Versions installed? Maybe PIP3 looks into a wrong Python environment. Try to configure pip_command in etc/smarthome.yaml"
            )

            self._logger.critical("Aborting")
            exit(1)

        self.shng_status = {
            'code': 2,
            'text': 'Initalizing: Requirements checked'
        }

        self.shtime._initialize_holidays()
        self._logger_main.warning(" - " + self.shtime.log_msg)

        # Add Signal Handling
        #        signal.signal(signal.SIGHUP, self.reload_logics)
        signal.signal(signal.SIGINT, self.stop)
        signal.signal(signal.SIGTERM, self.stop)

        #############################################################
        # Check Time
        while datetime.date.today().isoformat(
        ) < '2016-03-16':  # XXX update date
            time.sleep(5)
            self._logger.info("Waiting for updated time.")

        #############################################################
        # Catching Exceptions
        sys.excepthook = self._excepthook

        #############################################################
        # Setting debug level and adding memory handler
        self.initMemLog()

        # test if a valid locale is set in the operating system
        if os.name != 'nt':
            pass
        try:
            if not any(utf in os.environ['LANG'].lower()
                       for utf in ['utf-8', 'utf8']):
                self._logger.error(
                    "Locale for the enviroment is not set to a valid value. Set the LANG environment variable to a value supporting UTF-8"
                )
        except:
            self._logger.error(
                "Locale for the enviroment is not set. Defaulting to en_US.UTF-8"
            )
            os.environ["LANG"] = 'en_US.UTF-8'
            os.environ["LC_ALL"] = 'en_US.UTF-8'

        #############################################################
        # Link Tools
        self.tools = lib.tools.Tools()

        #############################################################
        # Link Sun and Moon
        self.sun = False
        self.moon = False
        if lib.orb.ephem is None:
            self._logger.warning("Could not find/use ephem!")
        elif not hasattr(self, '_lon') and hasattr(self, '_lat'):
            self._logger.warning(
                'No latitude/longitude specified => you could not use the sun and moon object.'
            )
        else:
            if not hasattr(self, '_elev'):
                self._elev = None
            self.sun = lib.orb.Orb('sun', self._lon, self._lat, self._elev)
            self.moon = lib.orb.Orb('moon', self._lon, self._lat, self._elev)
    def __init__(self):

        self.logger.info("BackendSysteminfo __init__ {}".format(''))

        self.shpypi = Shpypi.get_instance()
Пример #5
0
#####################################################################
# Base
#####################################################################
BASE = os.path.sep.join(os.path.realpath(__file__).split(os.path.sep)[:-2])
sys.path.insert(0, BASE)
PIDFILE = os.path.join(BASE, 'var', 'run', 'smarthome.pid')

# Only used for Version Check in Plugins to decide if a logger must be explicitly declared
import bin.shngversion
VERSION = bin.shngversion.get_shng_version()

#############################################################
# test if needed Python packages are installed
# - core requirements = libs
from lib.shpypi import Shpypi
shpypi = Shpypi.get_instance()
if shpypi is None:
    shpypi = Shpypi(base=BASE)

core_reqs = shpypi.test_core_requirements(logging=False,
                                          pip3_command=args.pip3_command)
if core_reqs == 0:
    print("Starting SmartHomeNG again...")
    python_bin = sys.executable
    if ' ' in python_bin:
        python_bin = '"' + python_bin + '"'
    command = python_bin + ' ' + os.path.join(BASE, 'bin', 'smarthome.py')
    try:
        p = subprocess.Popen(command, shell=True)
    except subprocess.SubprocessError as e:
        print("Restart command '{}' failed with error {}".format(command, e))
Пример #6
0
    def __init__(self):

        self.pypi_sorted_package_list = []

        self.shpypi = Shpypi.get_instance()
        return