コード例 #1
0
    def __init__(self, smarthome, smartvisu_dir='', overwrite_templates='Yes', visu_style='std', smartvisu_version=''):
        self.logger = logging.getLogger(__name__)
        self._sh = smarthome
        self.items = Items.get_instance()

        self.smartvisu_dir = smartvisu_dir
        self.smartvisu_version = smartvisu_version
        self.overwrite_templates = overwrite_templates
        self.visu_style = visu_style.lower()
        if not self.visu_style in ['std','blk']:
            self.visu_style = 'std'
            self.logger.warning("SmartVisuGenerator: visu_style '{}' unknown, using visu_style '{1}'".format(visu_style, self.visu_style))

        self.logger.info("Generating pages for smartVISU v{}".format(self.smartvisu_version))

        self.outdir = os.path.join(self.smartvisu_dir, 'pages', 'smarthome')
        self.tpldir = os.path.join(self.smartvisu_dir, 'pages', 'base', 'tplNG')
        self.tmpdir = os.path.join(self.smartvisu_dir, 'temp')
        if self.smartvisu_version == '2.9':
            self.tpldir = os.path.join(self.smartvisu_dir, 'dropins')
        
        self.thisplgdir = os.path.dirname(os.path.abspath(__file__))
        self.copy_templates()
        
        self.pages()
        self.logger.info("Generating pages for smartVISU v{} End".format(self.smartvisu_version))
コード例 #2
0
    def __init__(self, webif_dir, plugin):
        """
        Initialization of instance of class WebInterface

        :param webif_dir: directory where the webinterface of the plugin resides
        :param plugin: instance of the plugin
        :type webif_dir: str
        :type plugin: object
        """
        self.logger = plugin.logger
        self.webif_dir = webif_dir
        self.plugin = plugin
        self.items = Items.get_instance()
        self.last_upload = ""

        self.tplenv = self.init_template_environment()
        self.knxdaemon = ''
        if os.name != 'nt':
            if self.get_process_info("ps cax|grep eibd") != '':
                self.knxdaemon = 'eibd'
            if self.get_process_info("ps cax|grep knxd") != '':
                if self.knxdaemon != '':
                    self.knxdaemon += ' and '
                self.knxdaemon += 'knxd'
        else:
            self.knxdaemon = 'can not be determined when running on Windows'
コード例 #3
0
    def __init__(self,
                 smarthome,
                 update='False',
                 ip='127.0.0.1',
                 port=2323,
                 hashed_password=''):
        """
        Constructor
        :param smarthome: smarthomeNG instance
        :param update: Flag: Updates allowed
        :param ip: IP to bind on
        :param port: Port to bind on
        :param hashed_password: Hashed password that is required to logon
        """
        self.logger = logging.getLogger(__name__)

        self.items = Items.get_instance()

        if hashed_password is None or hashed_password == '':
            self.logger.warning(
                "CLI: You should set a password for this plugin.")
            hashed_password = None
        elif hashed_password.lower() == 'none':
            hashed_password = None
        elif not Utils.is_hash(hashed_password):
            self.logger.error(
                "CLI: Value given for 'hashed_password' is not a valid hash value. Login will not be possible"
            )

        lib.connection.Server.__init__(self, ip, port)
        self.sh = smarthome
        self.updates_allowed = Utils.to_bool(update)
        self.hashed_password = hashed_password
        self.commands = CLICommands(self.sh, self.updates_allowed, self)
        self.alive = False
コード例 #4
0
ファイル: __init__.py プロジェクト: chrisr79/plugins
    def __init__(self, sh, *args, **kwargs):
        """
        Initalizes the plugin. The parameters describe for this method are pulled from the entry in plugin.conf.

        :param sh:  **Deprecated**: The instance of the smarthome object. For SmartHomeNG versions 1.4 and up: **Don't use it**!
        :param *args: **Deprecated**: Old way of passing parameter values. For SmartHomeNG versions 1.4 and up: **Don't use it**!
        :param **kwargs:**Deprecated**: Old way of passing parameter values. For SmartHomeNG versions 1.4 and up: **Don't use it**!
        """
        from bin.smarthome import VERSION
        if '.'.join(VERSION.split('.', 2)[:2]) <= '1.5':
            self.logger = logging.getLogger(__name__)

        self.logger.debug("rtr: init method called")

        self.alive = None
        sh = self.get_sh()
        self.path = sh.base_dir + '/var/rtr/timer/'
        self._items = Items.get_instance()

        # preset the controller defaults
        self._defaults['Tlast'] = time.time()
        self._defaults['Kp'] = self.get_parameter_value('default_Kp')
        self._defaults['Ki'] = self.get_parameter_value('default_Ki')
        self._defaults['tempBoostTime'] = self.get_parameter_value('defaultBoostTime')
        self._defaults['valveProtect'] = self.get_parameter_value('defaultValveProtect')
        self._cycle_time = self.get_parameter_value('cycle_time')
        self._defaultOnExpiredTimer = self.get_parameter_value('defaultOnExpiredTimer')

        return
コード例 #5
0
ファイル: api_services.py プロジェクト: stoepf/smarthome
    def yaml_syntax_checker(self, yaml_code):
        check_result = ''
        if yaml_code == '':
            return check_result

        yaml_code = self.strip_empty_lines(yaml_code)

        import lib.shyaml as shyaml
        import lib.config as shconfig

        # load yaml code to dict ydata, get error message (if error occures) to estr
        ydata, estr = shyaml.yaml_load_fromstring(yaml_code, True)
        self.logger.info(
            "yaml_syntax_checker(): type(ydata) = {},estr='{}'".format(
                type(ydata), estr))

        if estr != '':
            check_result = 'ERROR: \n\n' + estr
        elif not isinstance(ydata, collections.OrderedDict):
            check_result = 'ERROR: \n\n' + 'No valid YAML code'
        elif ydata != None:
            # found valid yaml code

            # Test if the loaded data items with 'struct' attribute
            config = collections.OrderedDict()
            self.items = Items.get_instance()
            struct_dict = self.items.structs._struct_definitions
            shconfig.search_for_struct_in_items(ydata, struct_dict, config)
            self.logger.info("ydata = {}".format(ydata))
            self.logger.info("config = {}".format(config))

            # return data structure converted back to yaml format
            check_result = convert_yaml(config).replace('\n\n', '\n')

        return check_result
コード例 #6
0
ファイル: itemdata.py プロジェクト: zatze/smarthome
    def items_json(self, mode="tree"):
        """
        returns a list of items as json structure

        :param mode:             tree (default) or list structure
        """
        if self.items == None:
            self.items = Items.get_instance()

        items_sorted = sorted(self.items.return_items(),
                              key=lambda k: str.lower(k['_path']),
                              reverse=False)

        if mode == 'tree':
            parent_items_sorted = []
            for item in items_sorted:
                if "." not in item._path:
                    parent_items_sorted.append(item)

            (item_data,
             item_count) = self._build_item_tree(parent_items_sorted)
            self.logger.info(
                "admin: items_json: In tree-mode, {} items returned".format(
                    item_count))
            return json.dumps([item_count, item_data])
        else:
            item_list = []
            for item in items_sorted:
                item_list.append(item._path)
            self.logger.info(
                "admin: items_json: Not in tree-mode, {} items returned".
                format(len(item_list)))
            return json.dumps(item_list)
コード例 #7
0
ファイル: api_services.py プロジェクト: stoepf/smarthome
    def eval_syntax_checker(self, eval_code, relative_to):
        expanded_code = ''

        # set up environment for calculating eval-expression
        sh = self._sh
        shtime = Shtime.get_instance()
        items = Items.get_instance()
        import math
        import lib.userfunctions as uf

        eval_code = eval_code.replace('\r',
                                      '').replace('\n',
                                                  ' ').replace('  ',
                                                               ' ').strip()
        if relative_to == '':
            expanded_code = eval_code
        else:
            rel_to_item = items.return_item(relative_to)
            if rel_to_item is not None:
                expanded_code = rel_to_item.get_stringwithabsolutepathes(
                    eval_code, 'sh.', '(')
                expanded_code = rel_to_item.get_stringwithabsolutepathes(
                    expanded_code, 'sh.', '.property')
            else:
                expanded_code = "Error: Item {} does not exist!".format(
                    relative_to)
        try:
            value = eval(expanded_code)
        except Exception as e:
            check_result = "Problem evaluating {}:  {}".format(
                expanded_code, e)
        else:
            check_result = value
        return expanded_code, check_result
コード例 #8
0
ファイル: scene.py プロジェクト: ThomasCr/smarthome
    def __init__(self, smarthome):
        self._sh = smarthome
        
        global _scenes_instance
        if _scenes_instance is not None:
            import inspect
            curframe = inspect.currentframe()
            calframe = inspect.getouterframes(curframe, 2)
            logger.critical("A second 'scenes' object has been created. There should only be ONE instance of class 'Scenes'!!! Called from: {} ({})".format(calframe[1][1], calframe[1][3]))

        _scenes_instance = self

        self.items = Items.get_instance()

        self._scenes = {}
        self._learned_values = {}
        self._scenes_dir = smarthome.base_dir + '/scenes/'
        if not os.path.isdir(self._scenes_dir):
            logger.warning("Directory scenes not found. Ignoring scenes.".format(self._scenes_dir))
            return

     #   for item in smarthome.return_items():
        for item in self.items.return_items():
            if item.type() == 'scene':
                scene_file = os.path.join(self._scenes_dir, item.id())

                scene_file_yaml = yaml.yaml_load(scene_file+'.yaml', ordered=False, ignore_notfound=True)
                if scene_file_yaml is not None:
                    # Reading yaml file with scene definition
                    for state in scene_file_yaml:
                        actions = scene_file_yaml[state]['actions']
                        if isinstance(actions, dict):
                            actions = [ actions ]
                        if isinstance( actions, list ):
                            for action in actions:
                                if isinstance(action, dict):
                                    self._add_scene_entry(item, str(state), 
                                                          action.get('item', ''), str(action.get('value', '')), 
                                                          action.get('learn', ''), scene_file_yaml[state].get('name', ''))
                                else:
                                    logger.warning("Scene {}, state {}: action '{}' is not a dict".format(item, state, action))
                        else:
                            logger.warning("Scene {}, state {}: actions are not a list".format(item, state))
                    self._load_learned_values(str(item.id()))
                else:
                    # Trying to read conf file with scene definition
                    scene_conf_file = scene_file + '.conf'
                    try:
                        with open(scene_conf_file, 'r', encoding='UTF-8') as f:
                            reader = csv.reader(f, delimiter=' ')
                            for row in reader:
                                if row == []:  # ignore empty lines
                                    continue
                                if row[0][0] == '#':  # ignore comments
                                    continue
                                self._add_scene_entry(item, row[0], row[1], row[2])
                    except Exception as e:
                        logger.warning("Problem reading scene file {0}: {1}".format(scene_file, e))
                        continue
                item.add_method_trigger(self._trigger)
コード例 #9
0
ファイル: __init__.py プロジェクト: zwopi/plugins
    def __init__(self, smarthome, driver, connect, prefix="", cycle=60):
        self._sh = smarthome
        self.shtime = Shtime.get_instance()
        self.items = Items.get_instance()

        self.logger = logging.getLogger(__name__)
        self._dump_cycle = int(cycle)
        self._name = self.get_instance_name()
        self._replace = {
            table: table if prefix == "" else prefix + "_" + table
            for table in ["log", "item"]
        }
        self._replace['item_columns'] = ", ".join(COL_ITEM)
        self._replace['log_columns'] = ", ".join(COL_LOG)
        self._buffer = {}
        self._buffer_lock = threading.Lock()
        self._dump_lock = threading.Lock()

        self._db = lib.db.Database(
            ("" if prefix == "" else prefix.capitalize() + "_") + "Database",
            driver, Utils.string_to_list(connect))
        self._initialized = False
        self._initialize()

        smarthome.scheduler.add('Database dump ' + self._name +
                                ("" if prefix == "" else " [" + prefix + "]"),
                                self._dump,
                                cycle=self._dump_cycle,
                                prio=5)

        if not self.init_webinterface():
            self._init_complete = False
コード例 #10
0
 def __init__(self, abitem, name, allow_value_list=False, value_type=None):
     super().__init__(abitem)
     self.__name = name
     self.__allow_value_list = allow_value_list
     self.__value = None
     self.__item = None
     self.__eval = None
     self.__regex = None
     self.__struct = None
     self.__varname = None
     self.__template = None
     self._additional_sources = []
     self.itemsApi = Items.get_instance()
     self.__itemClass = Item
     self.__listorder = []
     self.__type_listorder = []
     self.__valid_valuetypes = [
         "value", "regex", "eval", "var", "item", "template", "struct"
     ]
     if value_type == "str":
         self.__cast_func = StateEngineTools.cast_str
     elif value_type == "num":
         self.__cast_func = StateEngineTools.cast_num
     elif value_type == "item":
         self.__cast_func = self.cast_item
     elif value_type == "bool":
         self.__cast_func = StateEngineTools.cast_bool
     elif value_type == "time":
         self.__cast_func = StateEngineTools.cast_time
     elif value_type == "list":
         self.__cast_func = StateEngineTools.cast_list
     else:
         self.__cast_func = None
コード例 #11
0
 def __init__(self, abitem, item_state):
     super().__init__(abitem)
     self.itemsApi = Items.get_instance()
     self.__item = item_state
     self.__itemClass = Item
     try:
         self.__id = self.__item.property.path
         self._log_info("Init state {}", self.__id)
     except Exception as err:
         self.__id = None
         self._log_info("Problem init state ID of Item {}. {}", self.__item,
                        err)
     self.__text = StateEngineValue.SeValue(self._abitem, "State Name",
                                            False, "str")
     self.__use = StateEngineValue.SeValue(self._abitem,
                                           "State configuration extension",
                                           True, "item")
     self.__release = StateEngineValue.SeValue(self._abitem,
                                               "State released by", True,
                                               "item")
     self.__name = ''
     self.__use_done = []
     self.__conditions = StateEngineConditionSets.SeConditionSets(
         self._abitem)
     self.__actions_enter_or_stay = StateEngineActions.SeActions(
         self._abitem)
     self.__actions_enter = StateEngineActions.SeActions(self._abitem)
     self.__actions_stay = StateEngineActions.SeActions(self._abitem)
     self.__actions_leave = StateEngineActions.SeActions(self._abitem)
     self._log_increase_indent()
     try:
         self.__fill(self.__item, 0)
     finally:
         self._log_decrease_indent()
コード例 #12
0
    def item_change_value_html(self, item_path, value):
        """
        Is called by items.html when an item value has been changed
        """
        if self.items is None:
            self.items = Items.get_instance()
        self.logger.info(
            "item_change_value_html: item '{}' set to value '{}'".format(
                item_path, value))
        item_data = []
        try:
            item = self.items.return_item(item_path)
        except Exception as e:
            self.logger.error(
                "item_change_value_html: item '{}' set to value '{}' - Exception {}"
                .format(item_path, value, e))
            return
        if 'num' in item.type():
            if "." in value or "," in value:
                value = float(value)
            else:
                value = int(value)
        item(value, caller='admin')

        return
コード例 #13
0
    def __init__(self, smarthome, mode="all"):
        self.logger.debug("Plugin '{}': '__init__'".format(self.get_fullname()))
        self._mode = mode
        self.items = Items.get_instance()

        if not self.init_webinterfaces():
            self._init_complete = False
コード例 #14
0
    def __init__(self, sh, *args, **kwargs):

        global paired_nukis
        global nuki_event_items
        global nuki_action_items
        global nuki_door_items
        global nuki_battery_items
        global lock
        global request_queue

        if '.'.join(VERSION.split('.', 2)[:2]) <= '1.5':
            self.logger = logging.getLogger(__name__)

        self._base_url = self.get_parameter_value(
            'protocol') + '://' + self.get_parameter_value(
                'bridge_ip') + ":" + str(
                    self.get_parameter_value('bridge_port')) + '/'
        self._token = self.get_parameter_value('bridge_api_token')

        self._action = ''
        self._noWait = self.get_parameter_value('no_wait')
        self.items = Items.get_instance()

        if not self.init_webinterfaces():
            self._init_complete = False

        self._callback_ip = self.mod_http.get_local_ip_address(
        )  # get_parameter_value('bridge_callback_ip')
        self._callback_port = self.mod_http.get_local_servicesport(
        )  # get_parameter_value('bridge_callback_port')

        if self._callback_ip is None or self._callback_ip in ['0.0.0.0', '']:
            self._callback_ip = self.get_local_ipv4_address()

            if not self._callback_ip:
                self.logger.critical(
                    "Plugin '{}': Could not fetch internal ip address. Set it manually!"
                    .format(self.get_shortname()))
                self.alive = False
                return
            self.logger.info(
                "Plugin '{pluginname}': using local ip address {ip}".format(
                    pluginname=self.get_shortname(), ip=self._callback_ip))
        else:
            self.logger.info(
                "Plugin '{pluginname}': using given ip address {ip}".format(
                    pluginname=self.get_shortname(), ip=self._callback_ip))
        self._callback_url = "http://{ip}:{port}/nuki_callback/".format(
            ip=self._callback_ip, port=self._callback_port)

        self._lockActions = [
            1,  # unlock
            2,  # lock
            3,  # unlatch
            4,  # lockAndGo
            5,  # lockAndGoWithUnlatch
        ]

        self.init_webinterface()
コード例 #15
0
 def __init__(self, abitem, name: str):
     super().__init__(abitem)
     self.shtime = Shtime.get_instance()
     self.items = Items.get_instance()
     self._name = name
     self.__delay = StateEngineValue.SeValue(self._abitem, "delay")
     self.__repeat = None
     self.__order = StateEngineValue.SeValue(self._abitem, "order", False, "num")
     self._scheduler_name = None
コード例 #16
0
    def __init__(self, module):
        self._sh = module._sh
        self.module = module
        self.base_dir = self._sh.get_basedir()
        self.logger = logging.getLogger(__name__)

        self.items = Items.get_instance()

        return
コード例 #17
0
    def __init__(self, sh):

        if '.'.join(VERSION.split('.', 2)[:2]) <= '1.5':
            self.logger = logging.getLogger(__name__)
        self.items = Items.get_instance()
        self.__items = self.abitems = {}
        self.__sh = sh
        self.alive = False
        self.__cli = None
        self.init_webinterface()
        try:
            log_level = self.get_parameter_value("log_level")
            log_directory = self.get_parameter_value("log_directory")
            self.logger.info(
                "Init StateEngine (log_level={0}, log_directory={1})".format(
                    log_level, log_directory))

            StateEngineDefaults.startup_delay = self.get_parameter_value(
                "startup_delay_default")
            StateEngineDefaults.suspend_time = self.get_parameter_value(
                "suspend_time_default")
            StateEngineDefaults.instant_leaveaction = self.get_parameter_value(
                "instant_leaveaction")
            StateEngineDefaults.write_to_log(self.logger)

            StateEngineCurrent.init(self.get_sh())

            if log_level > 0:
                if log_directory[0] != "/":
                    base = self.get_sh().get_basedir()
                    if base[-1] != "/":
                        base += "/"
                    log_directory = base + log_directory
                if not os.path.exists(log_directory):
                    os.makedirs(log_directory)
                text = "StateEngine extended logging is active. Logging to '{0}' with loglevel {1}."
                self.logger.info(text.format(log_directory, log_level))
            log_maxage = self.get_parameter_value("log_maxage")
            if log_level > 0 and log_maxage > 0:
                self.logger.info(
                    "StateEngine extended log files will be deleted after {0} days."
                    .format(log_maxage))
                SeLogger.set_logmaxage(log_maxage)
                cron = ['init', '30 0 * *']
                self.scheduler_add('StateEngine: Remove old logfiles',
                                   SeLogger.remove_old_logfiles,
                                   cron=cron,
                                   offset=0)
            SeLogger.set_loglevel(log_level)
            SeLogger.set_logdirectory(log_directory)
            self.get_sh(
            ).stateengine_plugin_functions = StateEngineFunctions.SeFunctions(
                self.get_sh(), self.logger)
        except Exception:
            self._init_complete = False
            return
コード例 #18
0
    def __init__(self, sh):
        """
        Initalizes the plugin. The parameters described for this method are pulled from the entry in plugin.yaml.

        :param sh:                 The instance of the smarthome object, save it for later references
        :param apikey:             api key needed to access wunderground
        :param language:           language for the forcast messages
        :param location:           location to display the weather for
        :param cycle:              number of seconds between updates
        :param item_subtree:       subtree of items in which the plugin looks for items to update
        :param log_start:          x
        """
        # Call init code of parent class (SmartPlugin)
        super().__init__()

        from bin.smarthome import VERSION
        if '.'.join(VERSION.split('.', 2)[:2]) <= '1.5':
            self.logger = logging.getLogger(__name__)

        self.items = Items.get_instance()

        languagedict = {"de": "DL", "en": "EN", 'fr': "FR"}
        self.apikey = self.get_parameter_value('apikey')
        if self.apikey == '':
            self.logger.error(
                "Wunderground: No api key specified, plugin is not starting")

        self.language = ''
        self.language = languagedict.get(
            self.get_parameter_value('language').lower())
        if self.language == None:
            self.language = self.get_parameter_value('language').upper()

        self.location = self.get_parameter_value('location')
        if self.location == '':
            self.logger.error(
                "Wunderground: No location specified, plugin is not starting")

        self.url = 'https://api.wunderground.com/api/' + self.apikey + '/conditions/forecast/lang:' + self.language + '/q/' + self.location + '.json'

        self.logger.info("Wunderground: url={}".format(str(self.url)))

        self._cycle = self.get_parameter_value('cycle')
        #self._cycle = 600
        #self.logger.error("Wunderground: Invalid value '"+str(cycle)+"' configured for attribute cycle in plugin.conf, using '"+str(self._cycle)+"' instead")

        self.item_subtree = self.get_parameter_value('item_subtree')
        if self.item_subtree == '':
            self.logger.warning(
                "Wunderground: item_subtree is not configured, searching complete item-tree instead. Please configure item_subtree to reduce processing overhead"
            )

        # if plugin should start even without web interface
        self.init_webinterface()

        return
コード例 #19
0
    def __init__(self, sh):
        super().__init__()
        self.logger = logging.getLogger('{}.general'.format(__name__))
        self.itemsApi = Items.get_instance()
        self.__items = self.abitems = {}
        self.mod_http = None
        self.__sh = sh
        self.alive = False
        self.__cli = None
        self.init_webinterface()
        self.__log_directory = self.get_parameter_value("log_directory")
        try:
            log_level = self.get_parameter_value("log_level")
            StateEngineDefaults.log_level = log_level
            log_directory = self.__log_directory
            self.logger.info(
                "Init StateEngine (log_level={0}, log_directory={1})".format(
                    log_level, log_directory))

            StateEngineDefaults.startup_delay = self.get_parameter_value(
                "startup_delay_default")
            StateEngineDefaults.suspend_time = self.get_parameter_value(
                "suspend_time_default")
            StateEngineDefaults.instant_leaveaction = self.get_parameter_value(
                "instant_leaveaction")
            StateEngineDefaults.write_to_log(self.logger)
            self.get_sh(
            ).stateengine_plugin_functions = StateEngineFunctions.SeFunctions(
                self.get_sh(), self.logger)
            StateEngineCurrent.init(self.get_sh())

            base = self.get_sh().get_basedir()
            log_directory = SeLogger.create_logdirectory(base, log_directory)

            if log_level > 0:
                text = "StateEngine extended logging is active. Logging to '{0}' with log level {1}."
                self.logger.info(text.format(log_directory, log_level))
            log_maxage = self.get_parameter_value("log_maxage")
            if log_maxage > 0:
                self.logger.info(
                    "StateEngine extended log files will be deleted after {0} days."
                    .format(log_maxage))
                SeLogger.set_logmaxage(log_maxage)
                cron = ['init', '30 0 * *']
                self.scheduler_add('StateEngine: Remove old logfiles',
                                   SeLogger.remove_old_logfiles,
                                   cron=cron,
                                   offset=0)
            SeLogger.set_loglevel(log_level)
            SeLogger.set_logdirectory(log_directory)

        except Exception as ex:
            self._init_complete = False
            self.logger.warning(
                "Problem loading Stateengine plugin: {}".format(ex))
            return
コード例 #20
0
    def __init__(self, webif_dir, plugin):
        """
        Initialization of instance of class WebInterface

        :param webif_dir: directory where the webinterface of the plugin resides
        :param plugin: instance of the plugin
        :type webif_dir: str
        :type plugin: object
        """
        self.logger = plugin.logger
        self.webif_dir = webif_dir
        self.plugin = plugin
        self.items = Items.get_instance()

        self.tplenv = self.init_template_environment()

        # try to get API handles
        self.items = Items.get_instance()
        self.logics = Logics.get_instance()
コード例 #21
0
    def index(self, reload=None):
        """
        Build index.html for cherrypy

        Display a list of all connected visu clients
        Render the template and return the html file to be delivered to the browser

        :return: contents of the template after beeing rendered
        """

        # get API handles that were unavailable during __init__
        if self.items is None:
            self.items = Items.get_instance()
        if self.logics is None:
            self.logics = Logics.get_instance()

        clients = []

        for clientinfo in self.plugin.return_clients():
            c = clientinfo.get('addr', '')
            client = dict()
            client['ip'] = clientinfo.get('ip', '')
            client['port'] = clientinfo.get('port', '')
            try:
                client['name'] = socket.gethostbyaddr(client['ip'])[0]
            except:
                client['name'] = client['ip']

            client['sw'] = clientinfo.get('sw', '')
            client['swversion'] = clientinfo.get('swversion', '')
            client['protocol'] = clientinfo.get('protocol', '')
            client['hostname'] = clientinfo.get('hostname', '')
            client['browser'] = clientinfo.get('browser', '')
            client['browserversion'] = clientinfo.get('browserversion', '')
            clients.append(client)

        clients_sorted = sorted(clients, key=lambda k: k['name'])

        plgitems = []
        for item in self.items.return_items():
            if ('visu_acl' in item.conf):
                plgitems.append(item)

        plglogics = []
        for logic in self.logics.return_logics():
            plglogics.append(self.logics.get_logic_info(logic))

        tmpl = self.tplenv.get_template('index.html')
        return tmpl.render(p=self.plugin,
                           items=sorted(plgitems,
                                        key=lambda k: str.lower(k['_path'])),
                           logics=sorted(plglogics,
                                         key=lambda k: str.lower(k['name'])),
                           clients=clients_sorted,
                           client_count=len(clients_sorted))
コード例 #22
0
ファイル: __init__.py プロジェクト: soft-rudi/plugins
    def __init__(self, sh, *args, **kwargs):
        self.logger.debug("Plugin '{}': '__init__'".format(
            self.get_fullname()))

        # Call init code of parent class (SmartPlugin or MqttPlugin)
        super().__init__()

        self._mode = self.get_parameter_value('mode')
        self.items = Items.get_instance()

        if not self.init_webinterfaces():
            self._init_complete = False
コード例 #23
0
ファイル: __init__.py プロジェクト: wvhn/plugins
    def __init__(self, sh):
        """
        Initalizes the plugin.

        If the sh object is needed at all, the method self.get_sh() should be used to get it.
        There should be almost no need for a reference to the sh object any more.

        Plugins have to use the new way of getting parameter values:
        use the SmartPlugin method get_parameter_value(parameter_name). Anywhere within the Plugin you can get
        the configured (and checked) value for a parameter by calling self.get_parameter_value(parameter_name). It
        returns the value in the datatype that is defined in the metadata.
        """

        # Call init code of parent class (SmartPlugin)
        super().__init__()

        from bin.smarthome import VERSION
        if '.'.join(VERSION.split('.', 2)[:2]) <= '1.5':
            self.logger = logging.getLogger(__name__)

        self.items = Items.get_instance()

        self.updates_allowed = self.get_parameter_value('update')
        self.ip = self.get_parameter_value('ip')
        self.port = self.get_parameter_value('port')
        self.hashed_password = self.get_parameter_value('hashed_password')
        if self.hashed_password is None or self.hashed_password == '':
            self.logger.warning(
                "CLI: You should set a password for this plugin.")
            self.hashed_password = None
        elif self.hashed_password.lower() == 'none':
            self.hashed_password = None
        elif not Utils.is_hash(self.hashed_password):
            self.logger.error(
                "CLI: Value given for 'hashed_password' is not a valid hash value. Login will not be possible"
            )

        name = 'plugins.' + self.get_fullname()
        self.server = Tcp_server(interface=self.ip,
                                 port=self.port,
                                 name=name,
                                 mode=Tcp_server.MODE_TEXT_LINE)
        self.server.set_callbacks(incoming_connection=self.handle_connection)
        self.commands = CLICommands(self.get_sh(), self.updates_allowed, self)
        self.alive = False

        # On initialization error use:
        #   self._init_complete = False
        #   return

        # if plugin should start even without web interface
        self.init_webinterface(WebInterface)
コード例 #24
0
 async def get_shng_class_instances(self):
     """
     Ensure that the instance vars for items and logics are initialized
     """
     while self.items is None:
         self.items = Items.get_instance()
         if self.items is None:
             await asyncio.sleep(1)
     while self.logics is None:
         self.logics = Logics.get_instance()
         if self.logics is None:
             await asyncio.sleep(1)
     return
コード例 #25
0
ファイル: api_scenes.py プロジェクト: stoepf/smarthome
    def read(self, id=None):
        """
        Handle GET requests for scenes API
        """
        if self.items == None:
            self.items = Items.get_instance()

        from lib.scene import Scenes
        get_param_func = getattr(Scenes, "get_instance", None)
        if callable(get_param_func):
            supported = True
            self.scenes = Scenes.get_instance()
            scene_list = []
            if self.scenes is not None:
                scene_list = self.scenes.get_loaded_scenes()

            disp_scene_list = []
            for scene in scene_list:
                scene_dict = {}
                scene_dict['path'] = scene
                #                scene_dict['name'] = str(self._sh.return_item(scene))
                scene_dict['name'] = str(self.items.return_item(scene))

                action_list = self.scenes.get_scene_actions(scene)
                scene_dict['value_list'] = action_list
                #                scene_dict[scene] = action_list

                disp_action_list = []
                for value in action_list:
                    action_dict = {}
                    action_dict['action'] = value
                    action_dict[
                        'action_name'] = self.scenes.get_scene_action_name(
                            scene, value)
                    action_list = self.scenes.return_scene_value_actions(
                        scene, value)
                    for action in action_list:
                        if not isinstance(action[0], str):
                            action[0] = action[0].id()
                    action_dict['action_list'] = action_list

                    disp_action_list.append(action_dict)
                scene_dict['values'] = disp_action_list
                self.logger.debug(
                    "scenes_html: disp_action_list for scene {} = {}".format(
                        scene, disp_action_list))

                disp_scene_list.append(scene_dict)
        else:
            supported = False
        return json.dumps(disp_scene_list)
コード例 #26
0
ファイル: api_items.py プロジェクト: zobi/smarthome-1
    def read(self, id=None):
        """
        Handle GET requests
        """

        if self.items is None:
            self.items = Items.get_instance()

        items_sorted = sorted(self.items.return_items(), key=lambda k: str.lower(k['_path']), reverse=False)

        item_list = []
        for item in items_sorted:
            item_list.append(item._path)
        return json.dumps(item_list)
コード例 #27
0
ファイル: __init__.py プロジェクト: RedTiger26/shng_plugins
    def __init__(self, webif_dir, plugin):
        """
        Initialization of instance of class WebInterface

        :param webif_dir: directory where the webinterface of the plugin resides
        :param plugin: instance of the plugin
        :type webif_dir: str
        :type plugin: object
        """
        self.logger = logging.getLogger(__name__)
        self.webif_dir = webif_dir
        self.plugin = plugin
        self.itemsApi = Items.get_instance()
        self.tplenv = self.init_template_environment()
コード例 #28
0
 def __init__(self, abitem, struct_path, global_struct):
     super().__init__(abitem)
     self.itemsApi = Items.get_instance()
     self.struct_path = struct_path
     self._conf = {}
     self._full_conf = {}
     self._struct = None
     self._global_struct = global_struct  # copy.deepcopy(self.itemsApi.return_struct_definitions())
     self._struct_rest = None
     self._children_structs = []
     self._parent_struct = None
     self.valid_se_use = False
     self.property = StructProperty(self)
     self.convert()
コード例 #29
0
ファイル: StateEngineAction.py プロジェクト: pakka11/plugins
 def __init__(self, abitem, name: str):
     super().__init__(abitem)
     self._parent = abitem
     self._caller = StateEngineDefaults.plugin_identification
     self.shtime = Shtime.get_instance()
     self.items = Items.get_instance()
     self._name = name
     self.__delay = StateEngineValue.SeValue(self._abitem, "delay")
     self.__repeat = None
     self.conditionset = StateEngineValue.SeValue(self._abitem, "conditionset", True, "str")
     self.__mode = StateEngineValue.SeValue(self._abitem, "mode", True, "str")
     self.__order = StateEngineValue.SeValue(self._abitem, "order", False, "num")
     self._scheduler_name = None
     self.__function = None
     self.__template = None
コード例 #30
0
ファイル: __init__.py プロジェクト: zwopi/plugins
    def __init__(self, smarthome, data_file, callers=None):
        self.logger = logging.getLogger(__name__)
        self.logger.info('Init Simulation release 1.5.0.6')
        self._sh = smarthome
        self.shtime = Shtime.get_instance()
        self._datafile = data_file
        self.lastday = ''
        self.items = Items.get_instance()
        self.scheduler = Scheduler.get_instance()
        self._callers = callers
        self._items = []
        self.scheduler_add('midnight', self._midnight, cron='0 0 * *', prio=3)

        if not self.init_webinterface():
            self._init_complete = False
コード例 #31
0
ファイル: __init__.py プロジェクト: RedTiger26/shng_plugins
    def __init__(self, webif_dir, plugin):
        """
        Initialization of instance of class WebInterface

        :param webif_dir: directory where the webinterface of the plugin resides
        :param plugin: instance of the plugin
        :type webif_dir: str
        :type plugin: object
        """
        self.logger = plugin.logger
        self.webif_dir = webif_dir
        self.plugin = plugin
        self.tplenv = self.init_template_environment()
        self.tplenv.filters['dateformat'] = self.dateformat
        self.tplenv.filters['timeformat'] = self.timeformat
        self.items = Items.get_instance()
コード例 #32
0
ファイル: scheduler.py プロジェクト: ThomasCr/smarthome
    def __init__(self, smarthome):
        threading.Thread.__init__(self, name='Scheduler')
        logger.info('Init Scheduler')
        self._sh = smarthome
        self._lock = threading.Lock()
        self._runc = threading.Condition()
        
        global _scheduler_instance
        if _scheduler_instance is not None:
            import inspect
            curframe = inspect.currentframe()
            calframe = inspect.getouterframes(curframe, 4)
            logger.critical("A second 'scheduler' object has been created. There should only be ONE instance of class 'Scheduler'!!! Called from: {} ({})".format(calframe[1][1], calframe[1][3]))

        _scheduler_instance = self
        
        self.shtime = Shtime.get_instance()
        self.items = Items.get_instance()
コード例 #33
0
ファイル: logic.py プロジェクト: ThomasCr/smarthome
    def __init__(self, smarthome, userlogicconf, envlogicconf):
        logger.info('Start Logics')
        self.shtime = Shtime.get_instance()
        self.items = Items.get_instance()
        self.plugins = Plugins.get_instance()
        self.scheduler = Scheduler.get_instance()

        self._sh = smarthome
        self._userlogicconf = userlogicconf
        self._env_dir = smarthome._env_dir
        self._envlogicconf = envlogicconf
        self._etc_dir = smarthome._etc_dir
        self._logic_dir = smarthome._logic_dir
        self._workers = []
        self._logics = {}
        self._bytecode = {}
        self.alive = True

        global _logics_instance
        if _logics_instance is not None:
            import inspect
            curframe = inspect.currentframe()
            calframe = inspect.getouterframes(curframe, 4)
            logger.critical("A second 'logics' object has been created. There should only be ONE instance of class 'Logics'!!! Called from: {} ({})".format(calframe[1][1], calframe[1][3]))

        _logics_instance = self

        self.scheduler = Scheduler.get_instance()
        
        _config = {}
        self._systemlogics = self._read_logics(envlogicconf, self._env_dir)
        _config.update(self._systemlogics)
        self._userlogics = self._read_logics(userlogicconf, self._logic_dir)
        _config.update(self._userlogics)

        for name in _config:
            self._load_logic(name, _config)
コード例 #34
0
ファイル: scheduler.py プロジェクト: ThomasCr/smarthome
    def add(self, name, obj, prio=3, cron=None, cycle=None, value=None, offset=None, next=None, from_smartplugin=False):
        """
        Adds an entry to the scheduler.
        
        :param name:
        :param obj:
        :param prio: a priority with default of 3 having 1 as most important and higher numbes less important
        :param cron: a crontab entry of type string or a list of entries
        :param cycle: a time given as integer in seconds or a string with a time given in seconds and a value after an equal sign
        :param value:
        :param offset: an optional offset for cycle. If not given, cycle start point will be varied between 10..15 seconds to prevent too many scheduler entries with the same starting times
        :param next:
        :param from_smartplugin:
        """
        if self.shtime == None:
            self.shtime = Shtime.get_instance()
        if self.shtime == None:
            self.items = Items.get_instance()
        self._lock.acquire()
        if isinstance(cron, str):
            cron = [cron, ]
        if isinstance(cron, list):
            _cron = {}
            for entry in cron:
                desc, __, _value = entry.partition('=')
                desc = desc.strip()
                if _value == '':
                    _value = None
                else:
                    _value = _value.strip()
                if desc.startswith('init'):
                    offset = 5  # default init offset
                    desc, op, seconds = desc.partition('+')
                    if op:
                        offset += int(seconds)
                    else:
                        desc, op, seconds = desc.partition('-')
                        if op:
                            offset -= int(seconds)
                    value = _value
#                    next = self._sh.now() + datetime.timedelta(seconds=offset)
                    next = self.shtime.now() + datetime.timedelta(seconds=offset)
                else:
                    _cron[desc] = _value
            if _cron == {}:
                cron = None
            else:
                cron = _cron
        if isinstance(cycle, int):
            cycle = {cycle: None}
        elif isinstance(cycle, str):
            cycle, __, _value = cycle.partition('=')
            try:
                cycle = int(cycle.strip())
            except Exception:
                logger.warning("Scheduler: invalid cycle entry for {0} {1}".format(name, cycle))
                return
            if _value != '':
                _value = _value.strip()
            else:
                _value = None
            cycle = {cycle: _value}
        if cycle is not None and offset is None:  # spread cycle jobs
                offset = random.randint(10, 15)
        # change name for multi instance plugins
        if obj.__class__.__name__ == 'method':
            if isinstance(obj.__self__, SmartPlugin):
                if obj.__self__.get_instance_name() != '':
                    #if not (name).startswith(self._pluginname_prefix):
                    if not from_smartplugin:
                        name = name +'_'+ obj.__self__.get_instance_name()
                    logger.debug("Scheduler: Name changed by adding plugin instance name to: " + name)
        self._scheduler[name] = {'prio': prio, 'obj': obj, 'cron': cron, 'cycle': cycle, 'value': value, 'next': next, 'active': True}
        if next is None:
            self._next_time(name, offset)
        self._lock.release()