How to use the appdaemon.utils.run_in_executor function in appdaemon

To help you get started, we’ve selected a few appdaemon examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github home-assistant / appdaemon / appdaemon / app_management.py View on Github external
init = getattr(self.objects[name]["object"], "initialize", None)
            if init is None:
                self.logger.warning("Unable to find initialize() function in module %s - skipped", name)
                await self.increase_inactive_apps(name)
                return
        else:
            self.logger.warning("Unable to find module %s - initialize() skipped", name)
            await self.increase_inactive_apps(name)
            return

        # Call its initialize function
        try:
            if asyncio.iscoroutinefunction(init):
                await init()
            else:
                await utils.run_in_executor(self, init)
            await self.set_state(name, state="idle")
            await self.increase_active_apps(name)
                        
            event_data = {
                "event_type": "app_initialized", 
                    "data": {'app' : name}
                }

            await self.AD.events.process_event("admin", event_data)

        except TypeError:
            self.AD.threading.report_callback_sig(name, "initialize", init, {})
        except:
            error_logger = logging.getLogger("Error.{}".format(name))
            error_logger.warning('-' * 60)
            error_logger.warning("Unexpected error running initialize() for %s", name)
github home-assistant / appdaemon / appdaemon / threading.py View on Github external
async def check_days_constraint(self, args, name):
        unconstrained = True
        if "constrain_days" in args:
            days = args["constrain_days"]
            now = await self.AD.sched.get_now()
            daylist = []
            for day in days.split(","):
                daylist.append(await utils.run_in_executor(self, utils.day_of_week, day))

            if now.weekday() not in daylist:
                unconstrained = False

        return unconstrained
github home-assistant / appdaemon / appdaemon / run_admin.py View on Github external
async def apps(self, request):
        response = await utils.run_in_executor(self.loop, self.executor, self.admin_obj.apps, request.scheme, request.host)
        return web.Response(text=response, content_type="text/html")
github home-assistant / appdaemon / appdaemon / http.py View on Github external
async def logon_page(self, request):
        response = await utils.run_in_executor(self, self.generate_logon_page, request.scheme, request.host)
        return web.Response(text=response, content_type="text/html")
github home-assistant / appdaemon / appdaemon / admin.py View on Github external
async def admin_page(self, scheme, url):

        try:
            params = {}

            params["transport"] = self.transport
            params["title"] = self.title

            if self.AD.http.dashboard_obj is not None:
                params["dashboard"] = True
            else:
                params["dashboard"] = False

            # Logs

            params["logs"] = await utils.run_in_executor(self, self.AD.logging.get_admin_logs)

            # Entities

            params["namespaces"] = await self.AD.state.list_namespaces()

            env = Environment(
                loader=FileSystemLoader(self.template_dir),
                autoescape=select_autoescape(['html', 'xml'])
            )

            template = env.get_template("admin.jinja2")
            rendered_template = await utils.run_in_executor(self, template.render, params)

            return (rendered_template)

        except:
github home-assistant / appdaemon / appdaemon / app_management.py View on Github external
if root not in self.module_dirs:
                    self.logger.info("Adding %s to module import path", root)
                    sys.path.insert(0, root)
                    self.module_dirs.append(root)

            for file in files:
                if file[-3:] == ".py":
                    found_files.append(os.path.join(root, file))

        for file in found_files:
            if file == os.path.join(self.AD.app_dir, "__init__.py"):
                continue
            try:

                # check we can actually open the file
                await utils.run_in_executor(self, self.check_file, file)

                modified = await utils.run_in_executor(self, os.path.getmtime, file)
                if file in self.monitored_files:
                    if self.monitored_files[file] < modified:
                        modules.append({"name": file, "reload": True})
                        self.monitored_files[file] = modified
                else:
                    self.logger.debug("Found module %s", file)
                    modules.append({"name": file, "reload": False})
                    self. monitored_files[file] = modified
            except IOError as err:
                self.logger.warning("Unable to read app %s: %s - skipping", file, err)

        # Check for deleted modules and add them to the terminate list
        deleted_modules = []
        for file in self.monitored_files:
github home-assistant / appdaemon / appdaemon / run_admin.py View on Github external
async def show_logon(self, request):
        response = await utils.run_in_executor(self.loop, self.executor, self.admin_obj.logon)
        return web.Response(text=response, content_type="text/html")
github home-assistant / appdaemon / appdaemon / plugins / mqtt / mqttplugin.py View on Github external
result = None
        if 'topic' in kwargs:
            if not self.mqtt_connected:  # ensure mqtt plugin is connected
                self.logger.warning("Attempt to call Mqtt Service while disconnected: %s", service)
                return None
            try:
                topic = kwargs['topic']
                payload = kwargs.get('payload', None)
                retain = kwargs.get('retain', False)
                qos = int(kwargs.get('qos', self.mqtt_qos))

                if service == 'publish':
                    self.logger.debug("Publish Payload: %s to Topic: %s", payload, topic)

                    result = await utils.run_in_executor(self, self.mqtt_client.publish, topic, payload, qos, retain)

                    if result[0] == 0:
                        self.logger.debug("Publishing Payload %s to Topic %s Successful", payload, topic)
                    else:
                        self.logger.warning("Publishing Payload %s to Topic %s was not Successful", payload, topic)

                elif service == 'subscribe':
                    self.logger.debug("Subscribe to Topic: %s", topic)

                    if topic not in self.mqtt_client_topics:
                        result = await utils.run_in_executor(self, self.mqtt_client.subscribe, topic, qos)

                        if result[0] == 0:
                            self.logger.debug("Subscription to Topic %s Successful", topic)
                            self.mqtt_client_topics.append(topic)
                        else:
github home-assistant / appdaemon / appdaemon / plugins / hass / hassplugin.py View on Github external
#
                if result["type"] == "auth_required":
                    if self.token is not None:
                        auth = json.dumps({
                            "type": "auth",
                            "access_token": self.token
                        })
                    elif self.ha_key is not None:
                        auth = json.dumps({
                            "type": "auth",
                            "api_password": self.ha_key
                        })
                    else:
                        raise ValueError("HASS requires authentication and none provided in plugin config")

                    await utils.run_in_executor(self, self.ws.send, auth)
                    result = json.loads(self.ws.recv())
                    if result["type"] != "auth_ok":
                        self.logger.warning("Error in authentication")
                        raise ValueError("Error in authentication")
                #
                # Subscribe to event stream
                #
                sub = json.dumps({
                    "id": _id,
                    "type": "subscribe_events"
                })
                await utils.run_in_executor(self, self.ws.send, sub)
                result = json.loads(self.ws.recv())
                if not (result["id"] == _id and result["type"] == "result" and result["success"] is True):
                    self.logger.warning("Unable to subscribe to HA events, id = %s", _id)
                    self.logger.warning(result)
github home-assistant / appdaemon / appdaemon / http.py View on Github external
async def _list_dash(self, request):
        response = await utils.run_in_executor(self, self.dashboard_obj.get_dashboard_list)
        return web.Response(text=response, content_type="text/html")